import { mountFlex } from "https://cdn.jsdelivr.net/npm/p5.flex@0.1.1/src/p5.flex.min.mjs"
import { mountGrid } from "./Grid.js"
import { vert, frag } from "./shader.js"
const [WIDTH, HEIGHT] = [600, 600]
const CANVAS_SIZE = [WIDTH, HEIGHT]
const TEXEL_SIZE = [1 / (WIDTH * PIXEL_DENSITY), 1 / (HEIGHT * PIXEL_DENSITY)]
const [cols, rows] = [15, 15]
let cnv, gfx, theShader, gs, curr
p.createCanvas(WIDTH, HEIGHT)
p.flex({ container: { padding: "20px" } })
p.pixelDensity(PIXEL_DENSITY)
cnv = p.createGraphics(WIDTH, HEIGHT)
gfx = p.createGraphics(WIDTH, HEIGHT, p.WEBGL)
theShader = p.createShader(vert, frag)
gs = cnv.Grid({ cols, rows, order: p.LRTB })
const calcID = (col, row) => {
if (col < 0 || row < 0 || col >= gs.cols || row >= gs.rows) return -1
return col + row * gs.cols
for (let cell of gs.cells) {
cell.walls = [true, true, true, true]
cell.chooseNeighbor = () => p.random(cell.neighbors)
cell.hasUnvisitedNeighbors = () => {
const t = gs.cells[calcID(cell.col, cell.row - 1)]
const r = gs.cells[calcID(cell.col + 1, cell.row)]
const b = gs.cells[calcID(cell.col, cell.row + 1)]
const l = gs.cells[calcID(cell.col - 1, cell.row)]
if (t && !t.visited) cell.neighbors.push(t)
if (r && !r.visited) cell.neighbors.push(r)
if (b && !b.visited) cell.neighbors.push(b)
if (l && !l.visited) cell.neighbors.push(l)
return cell.neighbors.length > 0
curr = gs.cells[p.floor(p.random(cols * rows))]
if (curr.hasUnvisitedNeighbors()) {
const next = curr.chooseNeighbor()
theShader.setUniform("tex0", cnv)
theShader.setUniform("canvasSize", CANVAS_SIZE)
theShader.setUniform("texelSize", TEXEL_SIZE)
theShader.setUniform("color", color)
gfx.quad(-1, 1, 1, 1, 1, -1, -1, -1)
const content = (cell) => {
cnv.strokeCap(cnv.PROJECT)
cnv.strokeWeight(cell.w / 2)
const visited = cell.visited
if (walls[0]) cnv.line(0, 0, cell.w, 0)
if (walls[1]) cnv.line(cell.w, 0, cell.w, cell.h)
if (walls[2]) cnv.line(0, cell.h, cell.w, cell.h)
if (walls[3]) cnv.line(0, 0, 0, cell.h)
cnv.translate(cell.w / 2, cell.h / 2)
const removeWalls = (curr, next) => {
const hor = curr.col - next.col
if (hor === +1) [curr.walls[3], next.walls[1]] = [false, false]
if (hor === -1) [curr.walls[1], next.walls[3]] = [false, false]
const ver = curr.row - next.row
if (ver === +1) [curr.walls[0], next.walls[2]] = [false, false]
if (ver === -1) [curr.walls[2], next.walls[0]] = [false, false]