split 'world', 'frame'.

This commit is contained in:
2026-07-05 20:55:54 -04:00
parent 5b99030093
commit 6f8ca350ca
4 changed files with 162 additions and 195 deletions

View File

@@ -1,17 +1,17 @@
import {mat4Ortho, mat4LookAt, mat4Multiply} from './math.js';
export class Diorama {
constructor(elementId, world, requestRenderCallback) {
constructor(elementId, frame, requestRenderCallback) {
this.element = document.getElementById(elementId);
this.canvas = document.createElement('canvas')
this.element.appendChild(this.canvas)
this.ctx2d = this.canvas.getContext('2d');
this.world = world;
this.frame = frame;
this.requestRender = requestRenderCallback;
this.target = [0.5, 0, 0.5];
this.radius = 4;
this.theta = 45;
this.theta = 135;
this.phi = 30;
this.projMatrix = new Float32Array(16);
@@ -73,7 +73,7 @@ export class Diorama {
}
centerView() {
if (this.world.blocks.size === 0) {
if (this.frame.blocks.size === 0) {
this.target = [0.5, 0.5, 0.5];
return;
}
@@ -81,7 +81,7 @@ export class Diorama {
let minX = Infinity, minY = Infinity, minZ = Infinity;
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
for (const block of this.world.blocks.values()) {
for (const block of this.frame.blocks.values()) {
minX = Math.min(minX, block.pos[0]);
minY = Math.min(minY, block.pos[1]);
minZ = Math.min(minZ, block.pos[2]);

View File

@@ -104,9 +104,9 @@ export class Engine {
this.cache.register('textures', this.atlas);
this.dioramas = [];
this.worldMeshes = new Map();
this.frameMeshes = new Map();
this.renderRequested = false;
this.observedWorlds = new Set();
this.observedFrames = new Set();
this.updateRequested = false;
window.addEventListener('resize', () => this.requestRender());
@@ -137,43 +137,43 @@ export class Engine {
addDiorama(diorama) {
this.dioramas.push(diorama);
if (!this.observedWorlds.has(diorama.world)) {
this.observedWorlds.add(diorama.world);
diorama.world.subscribe(() => this.requestUpdate());
if (!this.observedFrames.has(diorama.frame)) {
this.observedFrames.add(diorama.frame);
diorama.frame.subscribe(() => this.requestUpdate());
}
}
async updateAll() {
const uniqueWorlds = new Set(this.dioramas.map(d => d.world));
if (uniqueWorlds.size === 0) return;
const uniqueFrames = new Set(this.dioramas.map(d => d.frame));
if (uniqueFrames.size === 0) return;
const uniqueBlockIds = new Set();
for (const world of uniqueWorlds) {
for (const block of world.blocks.values()) uniqueBlockIds.add(block.id);
for (const frame of uniqueFrames) {
for (const block of frame.blocks.values()) uniqueBlockIds.add(block.id);
}
await Promise.all(Array.from(uniqueBlockIds).map(id => this.cache.get(id, 'blockstates')));
const uniqueModelIds = new Set();
const parsedWorlds = new Map();
const parsedFrames = new Map();
for (const world of uniqueWorlds) {
for (const frame of uniqueFrames) {
const parsedBlocks = [];
for (const block of world.blocks.values()) {
for (const block of frame.blocks.values()) {
const state = await this.cache.get(block.id, 'blockstates');
const parts = state.resolveParts(block.state);
parsedBlocks.push({block, parts});
for (const p of parts) uniqueModelIds.add(p.model);
}
parsedWorlds.set(world, parsedBlocks);
parsedFrames.set(frame, parsedBlocks);
}
await Promise.all(Array.from(uniqueModelIds).map(id => this.cache.get(id, 'models')));
const textureTasks = [];
const worldPools = new Map();
const framePools = new Map();
for (const world of uniqueWorlds) {
for (const frame of uniqueFrames) {
const instancePool = new Map();
for (const {block, parts} of parsedWorlds.get(world)) {
for (const {block, parts} of parsedFrames.get(frame)) {
for (const part of parts) {
const hash = Blockstate.getVariantHash(part);
if (!instancePool.has(hash)) {
@@ -205,15 +205,15 @@ export class Engine {
}
}
}
worldPools.set(world, instancePool);
framePools.set(frame, instancePool);
}
await Promise.all(textureTasks);
this.updateAtlasTexture();
for (const world of uniqueWorlds) {
for (const frame of uniqueFrames) {
const newMeshes = [];
for (const pool of worldPools.get(world).values()) {
for (const pool of framePools.get(frame).values()) {
const blockModel = await this.cache.get(pool.partDef.model, 'models');
const geometry = blockModel.buildGeometry(this.atlas.uvmap, pool.partDef);
@@ -223,7 +223,7 @@ export class Engine {
newMeshes.push(this.createInstancedMesh(geometry, instanceCount, matrixArray, colorArray));
}
this.worldMeshes.set(world, newMeshes);
this.frameMeshes.set(frame, newMeshes);
}
this.requestRender();
@@ -317,11 +317,11 @@ export class Engine {
const viewProj = diorama.updateMatrices(aspect);
gl.uniformMatrix4fv(this.uniforms.viewProj, false, viewProj);
gl.uniform3f(this.uniforms.lightDir, 1.0, 3.0, -2.0);
gl.uniform3f(this.uniforms.lightDir, 1.0, 3.0, 2.0);
gl.uniform3f(this.uniforms.viewDir, diorama.viewDir[0], diorama.viewDir[1], diorama.viewDir[2]);
gl.uniform3f(this.uniforms.upDir, diorama.upDir[0], diorama.upDir[1], diorama.upDir[2]);
const meshes = this.worldMeshes.get(diorama.world) || [];
const meshes = this.frameMeshes.get(diorama.frame) || [];
for (const mesh of meshes) {
gl.bindVertexArray(mesh.vao);
gl.drawElementsInstanced(gl.TRIANGLES, mesh.indexCount, gl.UNSIGNED_SHORT, 0, mesh.instanceCount);

View File

@@ -52,77 +52,76 @@
<script type="module">
import {Engine} from './engine.js';
import {Diorama} from './diorama.js';
import {World} from './world.js';
import {World, WorldFrame} from './world.js';
async function initDocument() {
try {
const engine = new Engine();
document.getElementById('atlas-container')?.appendChild(engine.atlas.canvas);
const world1 = new World(`
const w_static = new World(`
p -1 0 0 redstone_wire east=side west=none north=none south=none power=15
p 0 0 0 repeater facing=east delay=1 locked=false powered=true
p 2 0 0 oak_trapdoor facing=east half=bottom open=true
p 0 -1 0 lodestone
p 0 -2 0 piston facing=north extended=false
`)
const f_static = new WorldFrame(w_static);
const d_static_top = new Diorama('demo-2', f_static, () => engine.requestRender());
d_static_top.radius = 5;
d_static_top.theta = 180;
d_static_top.phi = 90;
d_static_top.centerView();
d_static_top.saveState();
engine.addDiorama(d_static_top)
const d_static_iso = new Diorama('demo-3', f_static, () => engine.requestRender());
d_static_iso.radius = 5;
d_static_iso.centerView();
d_static_iso.saveState();
engine.addDiorama(d_static_iso);
const pulses = `
p 0 0 0 observer facing=north powered=false
p 0 0 1 piston facing=south extended=false
p 0 -1 1 observer facing=up powered=false
p 0 -1 2 observer facing=up powered=false
t 2
const w_pulses = new World(`
p 0 0 0 observer facing=south powered=false
p 0 0 1 observer facing=east powered=false
p 1 0 1 observer facing=north powered=false
p 1 0 0 observer facing=west powered=false
t 0
p 0 0 1 powered=false
p 0 0 0 powered=true
p 0 0 1 extended=true
t 3
p 0 0 1.5 piston_head facing=south short=true type=normal
t 4
t 2
p 0 0 0 powered=false
p 0 -1 1 powered=true
p 0 -1 2 powered=true
p 1 0 0 powered=true
t 4
p 1 0 0 powered=false
p 1 0 1 powered=true
t 6
p 0 -1 1 powered=false
p 0 -1 2 powered=false
`;
p 1 0 1 powered=false
p 0 0 1 powered=true
`);
const f_pulses = new WorldFrame(w_pulses);
const d_pulses = new Diorama('demo-pulses', f_pulses, () => engine.requestRender());
d_pulses.radius = 4;
d_pulses.centerView()
d_pulses.saveState()
engine.addDiorama(d_pulses);
const world_pulses = new World(pulses);
const demo_pulses = new Diorama('demo-pulses', world_pulses, () => engine.requestRender())
demo_pulses.radius = 4;
demo_pulses.centerView()
demo_pulses.saveState()
engine.addDiorama(demo_pulses);
const piston = `
const w_piston = new World(`
p 0 0 0 redstone_wire power=0 east=side west=none north=none south=none
p 1 0 0 repeater facing=west powered=false locked=false delay=2
p 2 0 0 piston facing=east extended=false
p 3 0 0 slime_block
p 4 0 0 slime_block
t 2
p 0 0 0 power=15
t 6
p 1 0 0 powered=true
t 7
p 2 0 0 extended=true
p 4.0 0 0 air &
p 4.5 0 0 slime_block
p 3.0 0 0 air &
p 3.5 0 0 slime_block
p 2.5 0 0 piston_head facing=east short=true type=normal
t 8
p 4.5 0 0 air &
p 5.0 0 0 slime_block
@@ -130,13 +129,10 @@
p 4.0 0 0 slime_block
p 2.5 0 0 air &
p 3.0 0 0 piston_head facing=east short=false type=normal
t 12
p 0 0 0 power=0
t 16
p 1 0 0 powered=false
t 17
p 3 0 0 air &
p 2.5 0 0 piston_head facing=east short=true type=normal
@@ -144,7 +140,6 @@
p 3.5 0 0 slime_block
p 5.0 0 0 air &
p 4.5 0 0 slime_block
t 18
p 2.5 0 0 air
p 3.5 0 0 air &
@@ -152,36 +147,19 @@
p 4.5 0 0 air &
p 4.0 0 0 slime_block
p 2 0 0 extended=false
`;
const piston_time = new World(piston);
const piston_state = new World(piston);
const demo_time = new Diorama('demo-time', piston_time, () => engine.requestRender())
demo_time.radius = 4;
demo_time.centerView()
demo_time.saveState()
engine.addDiorama(demo_time);
const demo_state = new Diorama('demo-state', piston_state, () => engine.requestRender())
demo_state.radius = 4;
demo_state.centerView()
demo_state.saveState()
engine.addDiorama(demo_state);
const demo2 = new Diorama('demo-2', world1, () => engine.requestRender())
demo2.radius = 5;
demo2.theta = 180;
demo2.phi = 90;
demo2.centerView()
demo2.saveState()
engine.addDiorama(demo2);
const demo3 = new Diorama('demo-3', world1, () => engine.requestRender())
demo3.radius = 5;
demo3.centerView()
demo3.saveState()
engine.addDiorama(demo3);
`);
const f_piston_t = new WorldFrame(w_piston);
const d_piston_t = new Diorama('demo-time', f_piston_t, () => engine.requestRender());
d_piston_t.radius = 4;
d_piston_t.centerView();
d_piston_t.saveState();
engine.addDiorama(d_piston_t);
const f_piston_s = new WorldFrame(w_piston);
const d_piston_s = new Diorama('demo-state', f_piston_s, () => engine.requestRender());
d_piston_s.radius = 4;
d_piston_s.centerView();
d_piston_s.saveState();
engine.addDiorama(d_piston_s);
// Fetch and build everything concurrently!
await engine.updateAll();
@@ -189,38 +167,28 @@
const factor = 2.5;
const update_time = () => {
for (let i = 0; i < 20; i++) {
setTimeout(() => piston_time.seek(i), i * factor * 50)
setTimeout(() => f_piston_t.seek(i), i * factor * 50)
}
};
setInterval(update_time, factor * 1000)
update_time();
let i = 0;
let n = piston_state.eventCount;
let n = w_piston.eventCount;
const update_state = () => {
piston_state.seekIndex(i);
f_piston_s.seekIndex(i);
i = (i + 1) % n;
};
setInterval(update_state, 250);
update_state()
const update_pulses = () => {
for (let i = 0; i < 10; i++) {
setTimeout(() => world_pulses.seek(i), i * factor * 50)
for (let i = 0; i < 8; i++) {
setTimeout(() => f_pulses.seek(i), i * factor * 50)
}
};
setInterval(update_pulses, factor * 500)
setInterval(update_pulses, factor * 8 * 50)
update_pulses();
// let j = 0;
// let m = world_pulses.eventCount;
// const update_pulses = () => {
// world_pulses.seekIndex(j);
// j = (j + 1) % m;
// };
// setInterval(update_pulses, 250);
// update_state()
} catch (err) {
console.error("Renderer Initialization Failed:", err);
}

159
world.js
View File

@@ -1,3 +1,5 @@
// world.js
export class Block {
constructor(id, pos, state) {
this.id = id;
@@ -8,19 +10,11 @@ export class Block {
export class World {
constructor(script = '') {
this.blocks = new Map();
this.listeners = new Set();
// Timeline State
// Pure Data State
this.events = [];
this.labels = new Map();
this.currentIndex = 0;
this.currentTime = -Infinity;
this.initialState = new Map();
this.initialIndex = 0;
this.eventCount = 0;
if (script) {
@@ -28,60 +22,6 @@ export class World {
}
}
subscribe(callback) {
this.listeners.add(callback);
return () => this.listeners.delete(callback);
}
notify() {
for (const listener of this.listeners) listener();
}
set(id, x, y, z, state = {}) {
const key = `${x},${y},${z}`;
const isAir = id === 'air' || id === 'minecraft:air';
if (isAir) {
if (this.blocks.delete(key)) {
this.notify();
}
} else {
this.blocks.set(key, new Block(id, [x, y, z], state));
this.notify();
}
}
get(x, y, z) {
return this.blocks.get(`${x},${y},${z}`);
}
#apply(data, x, y, z) {
const key = `${x},${y},${z}`;
if (data) {
this.blocks.set(key, new Block(data.id, [x, y, z], {...data.state}));
} else {
this.blocks.delete(key);
}
}
reset() {
this.blocks.clear();
for (const [key, block] of this.initialState.entries()) {
this.blocks.set(key, new Block(block.id, [...block.pos], {...block.state}));
}
this.currentIndex = this.initialIndex;
if (this.initialIndex > 0 && this.events.length > 0) {
this.currentTime = this.events[this.initialIndex - 1].time;
} else {
this.currentTime = -Infinity;
}
this.notify();
}
#compile(script) {
let currentTime = -1;
let capturedInitialState = false;
@@ -104,7 +44,6 @@ export class World {
for (let line of lines) {
let mergeNext = false;
// Check for the continuation operator
if (line.endsWith('&')) {
mergeNext = true;
line = line.slice(0, -1).trim();
@@ -118,7 +57,6 @@ export class World {
if (newTime >= 0 && !capturedInitialState) captureInitial();
// Force flush any pending batch if time suddenly changes
if (currentBatch.length > 0) {
this.events.push({time: currentTime, actions: currentBatch});
currentBatch = [];
@@ -173,7 +111,6 @@ export class World {
currentBatch.push({x, y, z, prev, next});
// Commit the batch to the timeline if it's not waiting for a continuation
if (!mergeNext) {
this.events.push({time: currentTime, actions: currentBatch});
currentBatch = [];
@@ -188,63 +125,125 @@ export class World {
if (!capturedInitialState) captureInitial();
this.eventCount = this.events.length - this.initialIndex;
}
}
export class WorldFrame {
constructor(world) {
this.world = world;
// Playback State
this.blocks = new Map();
this.listeners = new Set();
this.currentIndex = 0;
this.currentTime = -Infinity;
// Immediately sync frame to the bedrock state
this.reset();
}
subscribe(callback) {
this.listeners.add(callback);
return () => this.listeners.delete(callback);
}
notify() {
for (const listener of this.listeners) listener();
}
get(x, y, z) {
return this.blocks.get(`${x},${y},${z}`);
}
#apply(data, x, y, z) {
const key = `${x},${y},${z}`;
if (data) {
this.blocks.set(key, new Block(data.id, [x, y, z], {...data.state}));
} else {
this.blocks.delete(key);
}
}
seek(target) {
let targetTime = target;
if (typeof target === 'string') {
targetTime = this.labels.get(target);
targetTime = this.world.labels.get(target);
if (targetTime === undefined) throw new Error(`Label not found: ${target}`);
}
while (this.currentIndex < this.events.length && this.events[this.currentIndex].time <= targetTime) {
const batch = this.events[this.currentIndex];
let changed = false;
while (this.currentIndex < this.world.events.length && this.world.events[this.currentIndex].time <= targetTime) {
const batch = this.world.events[this.currentIndex];
for (const action of batch.actions) {
this.#apply(action.next, action.x, action.y, action.z);
}
this.currentIndex++;
changed = true;
}
while (this.currentIndex > 0 && this.events[this.currentIndex - 1].time > targetTime) {
while (this.currentIndex > 0 && this.world.events[this.currentIndex - 1].time > targetTime) {
this.currentIndex--;
const batch = this.events[this.currentIndex];
const batch = this.world.events[this.currentIndex];
for (let i = batch.actions.length - 1; i >= 0; i--) {
const action = batch.actions[i];
this.#apply(action.prev, action.x, action.y, action.z);
}
changed = true;
}
this.currentTime = targetTime;
this.notify();
if (changed) this.notify();
}
seekIndex(targetIndex) {
targetIndex = targetIndex + this.initialIndex;
targetIndex = targetIndex + this.world.initialIndex;
let changed = false;
while (this.currentIndex < this.events.length && this.currentIndex < targetIndex) {
const batch = this.events[this.currentIndex];
while (this.currentIndex < this.world.events.length && this.currentIndex < targetIndex) {
const batch = this.world.events[this.currentIndex];
for (const action of batch.actions) {
this.#apply(action.next, action.x, action.y, action.z);
}
this.currentIndex++;
changed = true;
}
while (this.currentIndex > 0 && this.currentIndex > targetIndex) {
this.currentIndex--;
const batch = this.events[this.currentIndex];
const batch = this.world.events[this.currentIndex];
for (let i = batch.actions.length - 1; i >= 0; i--) {
const action = batch.actions[i];
this.#apply(action.prev, action.x, action.y, action.z);
}
changed = true;
}
if (this.currentIndex < this.events.length) {
this.currentTime = this.events[this.currentIndex].time;
} else if (this.events.length > 0) {
this.currentTime = this.events[this.events.length - 1].time;
if (this.currentIndex < this.world.events.length) {
this.currentTime = this.world.events[this.currentIndex].time;
} else if (this.world.events.length > 0) {
this.currentTime = this.world.events[this.world.events.length - 1].time;
} else {
this.currentTime = -Infinity;
}
if (changed) this.notify();
}
reset() {
this.blocks.clear();
for (const [key, block] of this.world.initialState.entries()) {
this.blocks.set(key, new Block(block.id, [...block.pos], {...block.state}));
}
this.currentIndex = this.world.initialIndex;
if (this.world.initialIndex > 0 && this.world.events.length > 0) {
this.currentTime = this.world.events[this.world.initialIndex - 1].time;
} else {
this.currentTime = -Infinity;
}
this.notify();