xxxxxxxxxx
98
/*************************************
Sean Harding - Marching Squares
-------------------------------------
A contribution to Daniel Shiffman's
"Coding in the Cabana" series
This implementation of the Marching
Squares algorithm uses inverse
interpolation to help smooth
out the contours.
The simulation is interactive!
Use the left mouse button to
remove material and the right mouse
button to add material, and watch
the contours update in real time!
*************************************/
var field = [];
const cellWidth = 24;
const cellHeight = 24;
var rows, columns, marchingSquares;
function setup() {
createCanvas(768, 768);
fill(255, 204, 153);
rows = floor(width / cellWidth);
columns = floor(height / cellHeight);
// initialize the array
for (var i = 0; i <= columns; i++) {
field.push([]);
for (var j = 0; j <= rows; j++) {
field[i].push(random(-1, 1));
}
}
marchingSquares = new MarchingSquares(field, cellWidth, cellHeight);
}
function draw() {
background(0, 51, 102);
const mouseCellX = round(mouseX / cellWidth);
const mouseCellY = round(mouseY / cellHeight);
if (mouseIsPressed && mouseCellX > 0 && mouseCellX < columns && mouseCellY > 0 && mouseCellY < rows) {
switch (mouseButton) {
case LEFT: {
field[mouseCellX - 1][mouseCellY - 1] -= 0.001 * deltaTime;
field[mouseCellX + 0][mouseCellY - 1] -= 0.002 * deltaTime;
field[mouseCellX + 1][mouseCellY - 1] -= 0.001 * deltaTime;
field[mouseCellX - 1][mouseCellY + 0] -= 0.002 * deltaTime;
field[mouseCellX + 0][mouseCellY + 0] -= 0.004 * deltaTime;
field[mouseCellX + 1][mouseCellY + 0] -= 0.002 * deltaTime;
field[mouseCellX - 1][mouseCellY + 1] -= 0.001 * deltaTime;
field[mouseCellX + 0][mouseCellY + 1] -= 0.002 * deltaTime;
field[mouseCellX + 1][mouseCellY + 1] -= 0.001 * deltaTime;
break;
}
case RIGHT: {
field[mouseCellX - 1][mouseCellY - 1] += 0.001 * deltaTime;
field[mouseCellX + 0][mouseCellY - 1] += 0.002 * deltaTime;
field[mouseCellX + 1][mouseCellY - 1] += 0.001 * deltaTime;
field[mouseCellX - 1][mouseCellY + 0] += 0.002 * deltaTime;
field[mouseCellX + 0][mouseCellY + 0] += 0.004 * deltaTime;
field[mouseCellX + 1][mouseCellY + 0] += 0.002 * deltaTime;
field[mouseCellX - 1][mouseCellY + 1] += 0.001 * deltaTime;
field[mouseCellX + 0][mouseCellY + 1] += 0.002 * deltaTime;
field[mouseCellX + 1][mouseCellY + 1] += 0.001 * deltaTime;
break;
}
}
}
noStroke();
ellipse(mouseX, mouseY, cellWidth * 3, cellHeight * 3)
// draw the points
strokeWeight(8);
for (var i = 0; i <= columns; i++) {
for (var j = 0; j <= rows; j++) {
stroke(map(field[i][j], -1, 1, 0, 256));
point(i * cellWidth, j * cellHeight);
}
}
stroke(255);
strokeWeight(1);
// Go!
marchingSquares.march(0);
}