xxxxxxxxxx
172
let col1;
let col2;
let rsep;
let threads;
let mweave;
let msize;
let moffs;
let draw_strokes = true;
let draw_sep = true;
let sc = 10;
function unit(hcol, vcol, h_on_top) {
push();
translate(0.5, 0.5);
let my_sep = draw_sep ? sep : 0;
const a = 0.5 - my_sep / 2;
if (!h_on_top) {
rotate(HALF_PI);
let tmp = hcol;
hcol = vcol;
vcol = tmp;
}
for (let c of [vcol, hcol]) {
fill(c);
noStroke();
rect(-a, -0.5, 1 - my_sep, 1);
stroke(0);
strokeWeight(0.05);
if( draw_strokes ) {
line(-a, -0.5, -a, 0.5);
line(a, -0.5, a, 0.5);
}
rotate(HALF_PI);
}
pop();
}
function makeWeaveMatrix() {
// Create a weaving pattern that works the same for both
// warp and weft.
msize = int(random(2, 6));
moffs = int(random(1, msize));
mweave = new Array(msize * msize).fill(0);
for (let y = 0; y < msize; ++y) {
for (let x = 0; x < msize; ++x) {
if (mweave[y * msize + x] != 0) {
continue;
}
const b = int(random(2)) * 2 - 1;
mweave[y * msize + x] = b;
mweave[((x + moffs) % msize) * msize + y] = -b;
}
}
}
function isLegalWeaveMatrix() {
// Can't have a row or column that's all over or all under.
for (let y = 0; y < msize; ++y) {
let ok = false;
for (let x = 1; x < msize; ++x) {
if (mweave[y * msize + x - 1] != mweave[y * msize + x]) {
ok = true;
break;
}
}
if (!ok) {
return false;
}
}
for (let x = 0; x < msize; ++x) {
let ok = false;
for (let y = 1; y < msize; ++y) {
if (mweave[(y - 1) * msize + x] != mweave[y * msize + x]) {
ok = true;
break;
}
}
if (!ok) {
return false;
}
}
return true;
}
function makeSystem() {
colorMode(HSB, 255);
const h = random(255);
const s = random(0, 200);
col1 = color(h, s, 100);
col2 = color(h, s, 250);
colorMode(RGB, 255);
sep = 0.3;
threads = [];
let ct = 2 * int(random(1, 4));
let b = false;
for (let idx = 0; idx < ct; ++idx) {
let tc = int(random(1, 4));
for (let jdx = 0; jdx < tc; ++jdx) {
threads.push(b);
}
b = !b;
}
ct = 0;
do {
makeWeaveMatrix();
++ct;
if (ct == 100) {
break;
}
} while (!isLegalWeaveMatrix());
// console.log("" + mweave);
// console.log(isLegalWeaveMatrix());
}
function setup() {
createCanvas(800, 800);
makeSystem();
}
function draw() {
background(255);
push();
scale(sc);
for (let y = 0; y < height / sc; ++y) {
for (let x = 0; x < width / sc; ++x) {
const c1 = threads[y % threads.length] ? col1 : col2;
const c2 = threads[x % threads.length] ? col1 : col2;
const b = mweave[(y % msize) * msize + (x % msize)];
push();
translate(x, y);
unit(c1, c2, b == 1);
pop();
}
}
pop();
noLoop();
}
function keyPressed() {
if (key == " ") {
makeSystem();
loop();
} else if( key == 't' ) {
draw_strokes = !draw_strokes;
loop();
} else if( key == 'c' ) {
draw_sep = !draw_sep;
loop();
} else if( key == 's' ) {
save( 'output.png' );
} else if( keyCode == UP_ARROW ) {
sc *= 1.05;
loop();
} else if( keyCode == DOWN_ARROW ) {
sc /= 1.05;
loop();
}
}