@i7r.tech/moveby 0.0.0-stage → 0.21.1-ywc
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +67 -2
- package/bin/index.js +34557 -0
- package/bin/moveby.js +8994 -0
- package/bin/parse-worker.mjs +39 -0
- package/bin/tooling/wasm_engine.cjs +131 -0
- package/bin/tooling/wasm_engine_bg.wasm +0 -0
- package/dist/engine/wasm_engine.d.ts +358 -0
- package/dist/engine/wasm_engine.js +766 -0
- package/dist/engine/wasm_engine_bg.wasm +0 -0
- package/dist/errors.d.ts +16 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1942 -0
- package/dist/passes/backdrop.d.ts +9 -0
- package/dist/passes/field.d.ts +33 -0
- package/dist/passes/index.d.ts +5 -0
- package/dist/passes/road.d.ts +23 -0
- package/dist/passes/scenery.d.ts +30 -0
- package/dist/passes/sky.d.ts +12 -0
- package/dist/passes/text.d.ts +27 -0
- package/dist/scene-module.d.ts +165 -0
- package/dist/scene.d.ts +59 -0
- package/dist/utils.d.ts +22 -0
- package/docs/attribution.md +31 -0
- package/docs/decisions.md +26 -0
- package/package.json +33 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1942 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined")
|
|
5
|
+
return require.apply(this, arguments);
|
|
6
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
// ../engine-binding/src/errors.ts
|
|
10
|
+
class MovebyError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "MovebyError";
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
var CORE_ERRORS = {
|
|
19
|
+
ELEV_MISMATCH: "The elevation data does not match the route: one height for each point of the route.",
|
|
20
|
+
TRACK_EMPTY: "The route has fewer than 2 points, or its text is cut short.",
|
|
21
|
+
WIRE_TRUNCATED: "The track file is cut short or malformed: a value runs past its section.",
|
|
22
|
+
WIRE_TRAILING: "A section of the track file has bytes after its content.",
|
|
23
|
+
WIRE_VERSION: "The track file has a format or a section version that this library does not read. Build the file again.",
|
|
24
|
+
WIRE_SECTION: "The track file has a section that is unknown, repeated, empty or out of order. Build the file again.",
|
|
25
|
+
WIRE_ROUTE: "The track file has no route section. Build the file again.",
|
|
26
|
+
WIRE_UNSUPPORTED: "The track file cannot carry a field span with a texture ground. Use an atlas cell for the span.",
|
|
27
|
+
WIRE_ANIM: "The track file holds animation. Animation moved to the scene module. Build the file again without it.",
|
|
28
|
+
WIRE_GLYPH_METRIC: "A glyph of the font does not fit the track file: the atlas sides are powers of two, and each glyph rectangle is whole pixels."
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// ../engine-binding/src/passes/backdrop.ts
|
|
32
|
+
class BackdropPass {
|
|
33
|
+
gl;
|
|
34
|
+
ground;
|
|
35
|
+
sky;
|
|
36
|
+
constructor(gl, ground, sky) {
|
|
37
|
+
this.gl = gl;
|
|
38
|
+
this.ground = ground;
|
|
39
|
+
this.sky = sky;
|
|
40
|
+
}
|
|
41
|
+
clearToGround() {
|
|
42
|
+
const gl = this.gl;
|
|
43
|
+
const ground = this.ground;
|
|
44
|
+
gl.clearColor(ground[0], ground[1], ground[2], 1);
|
|
45
|
+
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
|
46
|
+
}
|
|
47
|
+
fillSky(horizonRow, width, height) {
|
|
48
|
+
const gl = this.gl;
|
|
49
|
+
if (horizonRow >= height)
|
|
50
|
+
return;
|
|
51
|
+
const sky = this.sky;
|
|
52
|
+
gl.enable(gl.SCISSOR_TEST);
|
|
53
|
+
gl.scissor(0, horizonRow, width, height - horizonRow);
|
|
54
|
+
gl.clearColor(sky[0], sky[1], sky[2], 1);
|
|
55
|
+
gl.clear(gl.COLOR_BUFFER_BIT);
|
|
56
|
+
gl.disable(gl.SCISSOR_TEST);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ../engine-binding/src/shaders/field.vert.glsl
|
|
61
|
+
var field_vert_default = `// project-in-shader: projection now runs HERE (road's twin — kept a DISTINCT file per pass, not
|
|
62
|
+
// collapsed: WebGL1 has no #include, and each pass is free to diverge). Rust still resolves every
|
|
63
|
+
// cz-DEPENDENT DECISION (the λ outward-extension distance, via Camera::depth — layers/field/mesh.rs
|
|
64
|
+
// emit_field_trapezoid) and hands this shader a fully-resolved WORLD-SPACE corner; only the FINAL
|
|
65
|
+
// per-vertex projection (dot(q, forward) etc — Camera::project's exact math, camera.rs) moves CPU → GPU.
|
|
66
|
+
|
|
67
|
+
precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader
|
|
68
|
+
// (mediump would visibly wobble the projection at depth; project-in-shader.md).
|
|
69
|
+
|
|
70
|
+
attribute float a_cornerX; // world-space X of this corner (inner OR outer — λ already resolved in Rust)
|
|
71
|
+
attribute float a_cornerY; // world-space Y (elevation) of this corner
|
|
72
|
+
attribute float a_cornerZ; // world-space Z of this corner
|
|
73
|
+
attribute float a_u; // lateral / FIELD_TILE_M, RAW (unscaled) — the shader multiplies by its own scale
|
|
74
|
+
attribute float a_v; // (surface_s − tile_anchor) / FIELD_TILE_M, RAW
|
|
75
|
+
|
|
76
|
+
uniform vec3 u_camPos; // camera eye, world-space (Camera::pos, camera.rs)
|
|
77
|
+
uniform vec3 u_camForward; // unit look direction (Camera::forward)
|
|
78
|
+
uniform float u_aspect; // canvasW / canvasH — divides ndc_x ONLY, applied here exactly once
|
|
79
|
+
uniform float u_cameraDepth; // focal length, Rust consts::CAMERA_DEPTH — no GLSL literal (OQ4)
|
|
80
|
+
|
|
81
|
+
uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
|
|
82
|
+
uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
|
|
83
|
+
|
|
84
|
+
varying float v_scale;
|
|
85
|
+
varying float v_uScaled;
|
|
86
|
+
varying float v_vScaled;
|
|
87
|
+
|
|
88
|
+
// IDENTICAL to the road's depthNdc — same uniforms ⇒ the field shares the road's depth space exactly,
|
|
89
|
+
// so per-pixel depth-testing between road and field is correct. MUST match the Rust depth_ndc.
|
|
90
|
+
float depthNdc(float scale) {
|
|
91
|
+
return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Line-for-line mirror of Rust's Camera::project (camera.rs) — see road.vert.glsl's project() for the
|
|
95
|
+
// full derivation comment; identical here, just re-declared per the twin rule (kept distinct, not shared).
|
|
96
|
+
vec2 project(vec3 corner, out float cz, out float scale) {
|
|
97
|
+
vec3 right = vec3(u_camForward.z, 0.0, -u_camForward.x);
|
|
98
|
+
vec3 ray = corner - u_camPos;
|
|
99
|
+
cz = dot(ray, u_camForward);
|
|
100
|
+
scale = u_cameraDepth / max(cz, 1e-4);
|
|
101
|
+
return vec2(scale * dot(ray, right) / u_aspect, scale * ray.y);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
void main() {
|
|
105
|
+
vec3 corner = vec3(a_cornerX, a_cornerY, a_cornerZ);
|
|
106
|
+
float cz, scale;
|
|
107
|
+
vec2 ndc = project(corner, cz, scale);
|
|
108
|
+
|
|
109
|
+
// Per-vertex behind-camera cull (branchless — feedback_shader_branching.md), the shader-side twin of
|
|
110
|
+
// road's — DEFENSE-IN-DEPTH only: Rust's \`emit_field_trapezoid\` already drops the whole quad when any
|
|
111
|
+
// of its 4 corners is unsafe (a GLSL vertex invocation sees ONE vertex, never its quad's siblings).
|
|
112
|
+
// Field corners are NOT window-guaranteed clear of the camera plane the way road's are (a span
|
|
113
|
+
// can start at s=0, right at the player), which is why the Rust gate exists there; this step() flags
|
|
114
|
+
// the one corner that could still be unsafe, degrading it to a per-vertex vanish rather than a wedge.
|
|
115
|
+
float visible = step(1e-4, cz);
|
|
116
|
+
ndc = mix(vec2(2.0, 2.0), ndc, visible);
|
|
117
|
+
|
|
118
|
+
gl_Position = vec4(ndc, depthNdc(scale), 1.0); // w=1 → affine UV varyings, exact depth
|
|
119
|
+
|
|
120
|
+
v_scale = scale;
|
|
121
|
+
v_uScaled = a_u * scale;
|
|
122
|
+
v_vScaled = a_v * scale;
|
|
123
|
+
}
|
|
124
|
+
`;
|
|
125
|
+
|
|
126
|
+
// ../engine-binding/src/shaders/field.frag.glsl
|
|
127
|
+
var field_frag_default = `precision mediump float;
|
|
128
|
+
|
|
129
|
+
uniform sampler2D u_field; // the bound POT REPEAT ground tile — JS-owned pixels (WASM never sees them)
|
|
130
|
+
|
|
131
|
+
varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
|
|
132
|
+
varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
|
|
133
|
+
varying float v_vScaled; // v·scale ∝ v/cz — affine
|
|
134
|
+
|
|
135
|
+
void main() {
|
|
136
|
+
// Recover perspective-correct (u, v): u·scale ∝ u/cz and scale ∝ 1/cz are BOTH affine under w = 1,
|
|
137
|
+
// so their ratio is the true UV at this pixel — it FORESHORTENS toward the horizon, exactly the
|
|
138
|
+
// centre-line dash trick (RFC §4). REPEAT (set JS-side) wraps it into the world-anchored tile.
|
|
139
|
+
vec2 uv = vec2(v_uScaled, v_vScaled) / v_scale;
|
|
140
|
+
gl_FragColor = vec4(texture2D(u_field, uv).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
|
|
141
|
+
}
|
|
142
|
+
`;
|
|
143
|
+
|
|
144
|
+
// ../engine-binding/src/shaders/field-atlas.frag.glsl
|
|
145
|
+
var field_atlas_frag_default = `precision mediump float;
|
|
146
|
+
|
|
147
|
+
uniform sampler2D u_atlas; // the field's OWN atlas — JS-owned, NEAREST/CLAMP/no-mips (v1.2 field-owned atlas)
|
|
148
|
+
uniform vec4 u_cellRect; // [u0, v0, u1, v1] — this ground cell's ½-texel-inset sub-rect (per-draw uniform)
|
|
149
|
+
|
|
150
|
+
varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
|
|
151
|
+
varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
|
|
152
|
+
varying float v_vScaled; // v·scale ∝ v/cz — affine
|
|
153
|
+
|
|
154
|
+
void main() {
|
|
155
|
+
// Recover the perspective-correct world-tile UV (the dash ÷scale trick — IDENTICAL to field.frag), then
|
|
156
|
+
// fract-TILE it into the atlas sub-rect. An atlas sub-rect can't hardware-REPEAT (WebGL-1 wrap is whole-
|
|
157
|
+
// texture), so the wrap is done in-shader; NEAREST/no-mips (the shared sampler) ⇒ no mip-seam tear at the
|
|
158
|
+
// fract 1→0 jump (scenery-atlas-cells §2, ENGINE_FOUNDATIONS §12). Branchless — a SEPARATE program from
|
|
159
|
+
// the REPEAT-tile field.frag, chosen per bucket, not an in-fragment \`if\`.
|
|
160
|
+
vec2 worldUV = vec2(v_uScaled, v_vScaled) / v_scale;
|
|
161
|
+
vec2 cellUV = mix(u_cellRect.xy, u_cellRect.zw, fract(worldUV));
|
|
162
|
+
gl_FragColor = vec4(texture2D(u_atlas, cellUV).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
|
|
163
|
+
}
|
|
164
|
+
`;
|
|
165
|
+
|
|
166
|
+
// ../engine-binding/src/utils.ts
|
|
167
|
+
var VERTS_PER_QUAD_INDEXED = 4;
|
|
168
|
+
var UINT16_INDEX_QUAD_CAP = Math.floor(65535 / VERTS_PER_QUAD_INDEXED);
|
|
169
|
+
function buildQuadIndices(maxQuads) {
|
|
170
|
+
const idx = new Uint16Array(maxQuads * 6);
|
|
171
|
+
for (let i = 0;i < maxQuads; i++) {
|
|
172
|
+
const v = i * VERTS_PER_QUAD_INDEXED;
|
|
173
|
+
idx.set([v, v + 1, v + 2, v, v + 2, v + 3], i * 6);
|
|
174
|
+
}
|
|
175
|
+
return idx;
|
|
176
|
+
}
|
|
177
|
+
function assertQuadCapacity(pass, maxQuads, code, message) {
|
|
178
|
+
if (maxQuads > UINT16_INDEX_QUAD_CAP) {
|
|
179
|
+
throw new MovebyError(code, `${message} (${pass} pass: ${maxQuads} quads exceeds the Uint16 index cap (${UINT16_INDEX_QUAD_CAP}))`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function pixelSize(bitmap) {
|
|
183
|
+
if ("naturalWidth" in bitmap)
|
|
184
|
+
return { width: bitmap.naturalWidth, height: bitmap.naturalHeight };
|
|
185
|
+
if ("videoWidth" in bitmap)
|
|
186
|
+
return { width: bitmap.videoWidth, height: bitmap.videoHeight };
|
|
187
|
+
if ("displayWidth" in bitmap)
|
|
188
|
+
return { width: bitmap.displayWidth, height: bitmap.displayHeight };
|
|
189
|
+
return { width: bitmap.width, height: bitmap.height };
|
|
190
|
+
}
|
|
191
|
+
var isPowerOfTwo = (n) => n > 0 && (n & n - 1) === 0;
|
|
192
|
+
function assertMipmapable(code, message, what, bitmap) {
|
|
193
|
+
const { width, height } = pixelSize(bitmap);
|
|
194
|
+
if (!isPowerOfTwo(width) || !isPowerOfTwo(height)) {
|
|
195
|
+
throw new MovebyError(code, `${message} (${what}: ${width} × ${height})`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function drawQuadRange(gl, startVertex, countVertex) {
|
|
199
|
+
if (startVertex % VERTS_PER_QUAD_INDEXED !== 0 || countVertex % VERTS_PER_QUAD_INDEXED !== 0) {
|
|
200
|
+
throw new Error(`non-quad-aligned range: start=${startVertex} count=${countVertex}`);
|
|
201
|
+
}
|
|
202
|
+
const quadStart = startVertex / VERTS_PER_QUAD_INDEXED;
|
|
203
|
+
const quadCount = countVertex / VERTS_PER_QUAD_INDEXED;
|
|
204
|
+
gl.drawElements(gl.TRIANGLES, quadCount * 6, gl.UNSIGNED_SHORT, quadStart * 6 * 2);
|
|
205
|
+
}
|
|
206
|
+
var CAMERA_PART_FLOATS = 3;
|
|
207
|
+
var CAMERA_PART_BYTES = CAMERA_PART_FLOATS * Float32Array.BYTES_PER_ELEMENT;
|
|
208
|
+
|
|
209
|
+
class CameraViews {
|
|
210
|
+
position;
|
|
211
|
+
forward;
|
|
212
|
+
memory;
|
|
213
|
+
address;
|
|
214
|
+
buffer;
|
|
215
|
+
constructor(engine) {
|
|
216
|
+
this.memory = engine.wasm_memory();
|
|
217
|
+
this.address = engine.camera_ptr();
|
|
218
|
+
this.buffer = this.memory.buffer;
|
|
219
|
+
this.position = new Float32Array(this.buffer, this.address, CAMERA_PART_FLOATS);
|
|
220
|
+
this.forward = new Float32Array(this.buffer, this.address + CAMERA_PART_BYTES, CAMERA_PART_FLOATS);
|
|
221
|
+
}
|
|
222
|
+
current() {
|
|
223
|
+
if (this.memory.buffer !== this.buffer) {
|
|
224
|
+
this.buffer = this.memory.buffer;
|
|
225
|
+
this.position = new Float32Array(this.buffer, this.address, CAMERA_PART_FLOATS);
|
|
226
|
+
this.forward = new Float32Array(this.buffer, this.address + CAMERA_PART_BYTES, CAMERA_PART_FLOATS);
|
|
227
|
+
}
|
|
228
|
+
return this;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function disableAttributes(gl, locations) {
|
|
232
|
+
for (let i = 0;i < locations.length; i++) {
|
|
233
|
+
const location = locations[i];
|
|
234
|
+
if (location >= 0)
|
|
235
|
+
gl.disableVertexAttribArray(location);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function compileShader(gl, type, source) {
|
|
239
|
+
const shader = gl.createShader(type);
|
|
240
|
+
gl.shaderSource(shader, source);
|
|
241
|
+
gl.compileShader(shader);
|
|
242
|
+
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
|
243
|
+
const log = gl.getShaderInfoLog(shader);
|
|
244
|
+
gl.deleteShader(shader);
|
|
245
|
+
throw new Error(`Shader compile error:
|
|
246
|
+
${log}`);
|
|
247
|
+
}
|
|
248
|
+
return shader;
|
|
249
|
+
}
|
|
250
|
+
function uploadGridAtlas(gl, bitmap) {
|
|
251
|
+
const tex = gl.createTexture();
|
|
252
|
+
if (!tex)
|
|
253
|
+
throw new Error("createTexture failed");
|
|
254
|
+
gl.bindTexture(gl.TEXTURE_2D, tex);
|
|
255
|
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
|
256
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
|
257
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
|
258
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
|
259
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
|
260
|
+
return tex;
|
|
261
|
+
}
|
|
262
|
+
async function decodeAtlas(url) {
|
|
263
|
+
const response = await fetch(url);
|
|
264
|
+
if (!response.ok) {
|
|
265
|
+
throw new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
266
|
+
}
|
|
267
|
+
return await createImageBitmap(await response.blob(), {
|
|
268
|
+
premultiplyAlpha: "none",
|
|
269
|
+
colorSpaceConversion: "none"
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
function createProgram(gl, vsSource, fsSource) {
|
|
273
|
+
const vs = compileShader(gl, gl.VERTEX_SHADER, vsSource);
|
|
274
|
+
const fs = compileShader(gl, gl.FRAGMENT_SHADER, fsSource);
|
|
275
|
+
const prog = gl.createProgram();
|
|
276
|
+
gl.attachShader(prog, vs);
|
|
277
|
+
gl.attachShader(prog, fs);
|
|
278
|
+
gl.linkProgram(prog);
|
|
279
|
+
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
|
|
280
|
+
throw new Error(`Program link error:
|
|
281
|
+
${gl.getProgramInfoLog(prog)}`);
|
|
282
|
+
}
|
|
283
|
+
gl.deleteShader(vs);
|
|
284
|
+
gl.deleteShader(fs);
|
|
285
|
+
return prog;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ../engine-binding/src/passes/field.ts
|
|
289
|
+
var FIELD_FLOATS_PER_VERTEX = 5;
|
|
290
|
+
var FLOAT = 4;
|
|
291
|
+
var STRIDE = FIELD_FLOATS_PER_VERTEX * FLOAT;
|
|
292
|
+
function bindFloat(gl, loc, fieldIndex) {
|
|
293
|
+
if (loc < 0)
|
|
294
|
+
return;
|
|
295
|
+
gl.enableVertexAttribArray(loc);
|
|
296
|
+
gl.vertexAttribPointer(loc, 1, gl.FLOAT, false, STRIDE, fieldIndex * FLOAT);
|
|
297
|
+
}
|
|
298
|
+
function drawBucket(gl, startVertex, countVertex) {
|
|
299
|
+
if (startVertex + countVertex > UINT16_INDEX_QUAD_CAP * VERTS_PER_QUAD_INDEXED) {
|
|
300
|
+
throw new MovebyError("FIELD_CAPACITY", `${FIELD_ERRORS.FIELD_CAPACITY} (${startVertex + countVertex} vertices)`);
|
|
301
|
+
}
|
|
302
|
+
drawQuadRange(gl, startVertex, countVertex);
|
|
303
|
+
}
|
|
304
|
+
var FIELD_ERRORS = {
|
|
305
|
+
FIELD_RANGE: "A field span has a bad range: 0 ≤ start < end.",
|
|
306
|
+
FIELD_END: "A field span ends past the end of the track.",
|
|
307
|
+
FIELD_OVERLAP: "Two field spans overlap on the same side.",
|
|
308
|
+
FIELD_ATLAS_CELL: "A field span uses an atlas cell, but the track has no field atlas, or the cell block does not fit its grid.",
|
|
309
|
+
FIELD_ATLAS_DIMS: "The field atlas grid is bad: cols and rows are at least 1, each pixel size is a whole number of cells, and the grid has at most 65,536 cells.",
|
|
310
|
+
FIELD_IMAGE_MISSING: "The field layer has no image to draw from.",
|
|
311
|
+
FIELD_IMAGE_SIZE: "A field tile image must be loaded, with power-of-two sides such as 256 × 256.",
|
|
312
|
+
FIELD_CAPACITY: "The track has more field quads in one frame than one draw can index."
|
|
313
|
+
};
|
|
314
|
+
function noImage(detail) {
|
|
315
|
+
return new MovebyError("FIELD_IMAGE_MISSING", `${FIELD_ERRORS.FIELD_IMAGE_MISSING} (${detail})`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
class FieldPass {
|
|
319
|
+
gl;
|
|
320
|
+
engine;
|
|
321
|
+
fieldProgram = null;
|
|
322
|
+
fieldBuffer = null;
|
|
323
|
+
fieldIndexBuffer = null;
|
|
324
|
+
fieldLoc = null;
|
|
325
|
+
fieldLocList = [];
|
|
326
|
+
fieldUni = null;
|
|
327
|
+
fieldTextures = new Map;
|
|
328
|
+
fieldAtlasProgram = null;
|
|
329
|
+
fieldAtlasLoc = null;
|
|
330
|
+
fieldAtlasLocList = [];
|
|
331
|
+
fieldAtlasUni = null;
|
|
332
|
+
fieldAtlasCellRectLoc = null;
|
|
333
|
+
fieldAtlas = null;
|
|
334
|
+
constructor(gl, engine) {
|
|
335
|
+
this.gl = gl;
|
|
336
|
+
this.engine = engine;
|
|
337
|
+
const bounds = engine.depth_bounds();
|
|
338
|
+
if (engine.max_field_draw_bytes() > 0) {
|
|
339
|
+
this.fieldProgram = createProgram(gl, field_vert_default, field_frag_default);
|
|
340
|
+
this.fieldLoc = {
|
|
341
|
+
a_cornerX: gl.getAttribLocation(this.fieldProgram, "a_cornerX"),
|
|
342
|
+
a_cornerY: gl.getAttribLocation(this.fieldProgram, "a_cornerY"),
|
|
343
|
+
a_cornerZ: gl.getAttribLocation(this.fieldProgram, "a_cornerZ"),
|
|
344
|
+
a_u: gl.getAttribLocation(this.fieldProgram, "a_u"),
|
|
345
|
+
a_v: gl.getAttribLocation(this.fieldProgram, "a_v")
|
|
346
|
+
};
|
|
347
|
+
this.fieldLocList = Object.values(this.fieldLoc);
|
|
348
|
+
this.fieldUni = {
|
|
349
|
+
u_camPos: gl.getUniformLocation(this.fieldProgram, "u_camPos"),
|
|
350
|
+
u_camForward: gl.getUniformLocation(this.fieldProgram, "u_camForward"),
|
|
351
|
+
u_aspect: gl.getUniformLocation(this.fieldProgram, "u_aspect")
|
|
352
|
+
};
|
|
353
|
+
gl.useProgram(this.fieldProgram);
|
|
354
|
+
gl.uniform1f(gl.getUniformLocation(this.fieldProgram, "u_scaleNear"), bounds[0]);
|
|
355
|
+
gl.uniform1f(gl.getUniformLocation(this.fieldProgram, "u_scaleFar"), bounds[1]);
|
|
356
|
+
gl.uniform1i(gl.getUniformLocation(this.fieldProgram, "u_field"), 0);
|
|
357
|
+
gl.uniform1f(gl.getUniformLocation(this.fieldProgram, "u_cameraDepth"), engine.camera_depth());
|
|
358
|
+
this.fieldAtlasProgram = createProgram(gl, field_vert_default, field_atlas_frag_default);
|
|
359
|
+
this.fieldAtlasLoc = {
|
|
360
|
+
a_cornerX: gl.getAttribLocation(this.fieldAtlasProgram, "a_cornerX"),
|
|
361
|
+
a_cornerY: gl.getAttribLocation(this.fieldAtlasProgram, "a_cornerY"),
|
|
362
|
+
a_cornerZ: gl.getAttribLocation(this.fieldAtlasProgram, "a_cornerZ"),
|
|
363
|
+
a_u: gl.getAttribLocation(this.fieldAtlasProgram, "a_u"),
|
|
364
|
+
a_v: gl.getAttribLocation(this.fieldAtlasProgram, "a_v")
|
|
365
|
+
};
|
|
366
|
+
this.fieldAtlasLocList = Object.values(this.fieldAtlasLoc);
|
|
367
|
+
this.fieldAtlasUni = {
|
|
368
|
+
u_camPos: gl.getUniformLocation(this.fieldAtlasProgram, "u_camPos"),
|
|
369
|
+
u_camForward: gl.getUniformLocation(this.fieldAtlasProgram, "u_camForward"),
|
|
370
|
+
u_aspect: gl.getUniformLocation(this.fieldAtlasProgram, "u_aspect")
|
|
371
|
+
};
|
|
372
|
+
this.fieldAtlasCellRectLoc = gl.getUniformLocation(this.fieldAtlasProgram, "u_cellRect");
|
|
373
|
+
gl.useProgram(this.fieldAtlasProgram);
|
|
374
|
+
gl.uniform1f(gl.getUniformLocation(this.fieldAtlasProgram, "u_scaleNear"), bounds[0]);
|
|
375
|
+
gl.uniform1f(gl.getUniformLocation(this.fieldAtlasProgram, "u_scaleFar"), bounds[1]);
|
|
376
|
+
gl.uniform1i(gl.getUniformLocation(this.fieldAtlasProgram, "u_atlas"), 0);
|
|
377
|
+
gl.uniform1f(gl.getUniformLocation(this.fieldAtlasProgram, "u_cameraDepth"), engine.camera_depth());
|
|
378
|
+
this.fieldBuffer = gl.createBuffer();
|
|
379
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.fieldBuffer);
|
|
380
|
+
gl.bufferData(gl.ARRAY_BUFFER, engine.max_field_draw_bytes(), gl.DYNAMIC_DRAW);
|
|
381
|
+
const maxQuads = engine.max_field_draw_bytes() / 4 / FIELD_FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
|
|
382
|
+
this.fieldIndexBuffer = gl.createBuffer();
|
|
383
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.fieldIndexBuffer);
|
|
384
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(maxQuads), gl.STATIC_DRAW);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
setFieldTexture(id, bitmap) {
|
|
388
|
+
assertMipmapable("FIELD_IMAGE_SIZE", FIELD_ERRORS.FIELD_IMAGE_SIZE, `field({ textures }) tile for texture_id ${id}`, bitmap);
|
|
389
|
+
const gl = this.gl;
|
|
390
|
+
if (!this.fieldProgram)
|
|
391
|
+
return;
|
|
392
|
+
const tex = gl.createTexture();
|
|
393
|
+
if (!tex)
|
|
394
|
+
throw new Error("createTexture failed");
|
|
395
|
+
gl.bindTexture(gl.TEXTURE_2D, tex);
|
|
396
|
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, bitmap);
|
|
397
|
+
gl.generateMipmap(gl.TEXTURE_2D);
|
|
398
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
|
|
399
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
|
|
400
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
|
401
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
|
402
|
+
this.fieldTextures.set(id, tex);
|
|
403
|
+
}
|
|
404
|
+
setFieldAtlas(bitmap) {
|
|
405
|
+
if (!this.fieldAtlasProgram)
|
|
406
|
+
return;
|
|
407
|
+
this.fieldAtlas = uploadGridAtlas(this.gl, bitmap);
|
|
408
|
+
}
|
|
409
|
+
draw(camera) {
|
|
410
|
+
const gl = this.gl;
|
|
411
|
+
if (!this.fieldProgram || !this.fieldLoc)
|
|
412
|
+
return;
|
|
413
|
+
gl.useProgram(this.fieldProgram);
|
|
414
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.fieldBuffer);
|
|
415
|
+
const view = this.engine.fill_field_and_view();
|
|
416
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
|
|
417
|
+
bindFloat(gl, this.fieldLoc.a_cornerX, 0);
|
|
418
|
+
bindFloat(gl, this.fieldLoc.a_cornerY, 1);
|
|
419
|
+
bindFloat(gl, this.fieldLoc.a_cornerZ, 2);
|
|
420
|
+
bindFloat(gl, this.fieldLoc.a_u, 3);
|
|
421
|
+
bindFloat(gl, this.fieldLoc.a_v, 4);
|
|
422
|
+
const aspect = this.engine.aspect();
|
|
423
|
+
if (this.fieldUni) {
|
|
424
|
+
const cam = camera.current();
|
|
425
|
+
gl.uniform3fv(this.fieldUni.u_camPos, cam.position);
|
|
426
|
+
gl.uniform3fv(this.fieldUni.u_camForward, cam.forward);
|
|
427
|
+
gl.uniform1f(this.fieldUni.u_aspect, aspect);
|
|
428
|
+
}
|
|
429
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.fieldIndexBuffer);
|
|
430
|
+
const ranges = this.engine.field_draw_ranges();
|
|
431
|
+
gl.activeTexture(gl.TEXTURE0);
|
|
432
|
+
for (let i = 0;i + 2 < ranges.length; i += 3) {
|
|
433
|
+
const id = ranges[i];
|
|
434
|
+
const start = ranges[i + 1];
|
|
435
|
+
const count = ranges[i + 2];
|
|
436
|
+
const tex = this.fieldTextures.get(id);
|
|
437
|
+
if (!tex)
|
|
438
|
+
throw noImage(`no texture for texture_id ${id}`);
|
|
439
|
+
gl.bindTexture(gl.TEXTURE_2D, tex);
|
|
440
|
+
drawBucket(gl, start, count);
|
|
441
|
+
}
|
|
442
|
+
disableAttributes(gl, this.fieldLocList);
|
|
443
|
+
const atlasRanges = this.engine.field_atlas_draw_ranges();
|
|
444
|
+
if (this.fieldAtlasProgram && this.fieldAtlasLoc && atlasRanges.length > 0) {
|
|
445
|
+
if (!this.fieldAtlas)
|
|
446
|
+
throw noImage("the track has atlas-cell ground and field() has no atlas");
|
|
447
|
+
gl.useProgram(this.fieldAtlasProgram);
|
|
448
|
+
bindFloat(gl, this.fieldAtlasLoc.a_cornerX, 0);
|
|
449
|
+
bindFloat(gl, this.fieldAtlasLoc.a_cornerY, 1);
|
|
450
|
+
bindFloat(gl, this.fieldAtlasLoc.a_cornerZ, 2);
|
|
451
|
+
bindFloat(gl, this.fieldAtlasLoc.a_u, 3);
|
|
452
|
+
bindFloat(gl, this.fieldAtlasLoc.a_v, 4);
|
|
453
|
+
if (this.fieldAtlasUni) {
|
|
454
|
+
const cam = camera.current();
|
|
455
|
+
gl.uniform3fv(this.fieldAtlasUni.u_camPos, cam.position);
|
|
456
|
+
gl.uniform3fv(this.fieldAtlasUni.u_camForward, cam.forward);
|
|
457
|
+
gl.uniform1f(this.fieldAtlasUni.u_aspect, aspect);
|
|
458
|
+
}
|
|
459
|
+
gl.bindTexture(gl.TEXTURE_2D, this.fieldAtlas);
|
|
460
|
+
for (let i = 0;i + 5 < atlasRanges.length; i += 6) {
|
|
461
|
+
gl.uniform4f(this.fieldAtlasCellRectLoc, atlasRanges[i], atlasRanges[i + 1], atlasRanges[i + 2], atlasRanges[i + 3]);
|
|
462
|
+
drawBucket(gl, atlasRanges[i + 4], atlasRanges[i + 5]);
|
|
463
|
+
}
|
|
464
|
+
disableAttributes(gl, this.fieldAtlasLocList);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
// ../engine-binding/src/shaders/road.vert.glsl
|
|
469
|
+
var road_vert_default = `// ── Inputs from our vertex buffer (12 floats per vertex, see consts.rs) ──────
|
|
470
|
+
//
|
|
471
|
+
// project-in-shader: projection now runs HERE. Rust emits absolute WORLD-SPACE corners; this shader
|
|
472
|
+
// does the camera dot-products — the EXACT math of Rust's Camera::project (camera.rs), only relocated
|
|
473
|
+
// CPU → GPU — then derives gl_Position.z from the resulting scale, so the GPU can still depth-test
|
|
474
|
+
// (per-pixel nearest-wins) instead of relying on draw order. w stays 1.0.
|
|
475
|
+
//
|
|
476
|
+
// The 6 PER-CORNER floats are individual \`attribute float\`s; the 6 PER-QUAD divider-style floats pack into
|
|
477
|
+
// TWO vec3 attributes (a_divider + a_color), so the total is 8 attributes — the WebGL-1 MAX_VERTEX_ATTRIBS
|
|
478
|
+
// baseline floor (9 individual floats would exceed it). The vec3 grouping is deliberate, forced by that floor.
|
|
479
|
+
|
|
480
|
+
precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader
|
|
481
|
+
// (mediump would visibly wobble the projection at depth; project-in-shader.md).
|
|
482
|
+
|
|
483
|
+
attribute float a_cornerX; // world-space X of this quad corner
|
|
484
|
+
attribute float a_cornerY; // world-space Y (elevation) of this quad corner — 0 on a flat road
|
|
485
|
+
attribute float a_cornerZ; // world-space Z of this quad corner
|
|
486
|
+
attribute float a_lateral; // signed metres from the centreline (sign · half_width at this corner), RAW
|
|
487
|
+
attribute float a_half; // road half-width here (m) — per-vertex (varies along a lane taper)
|
|
488
|
+
attribute float a_s; // road-SURFACE arc-length (m) at this corner, RAW — drives the dash
|
|
489
|
+
attribute vec3 a_divider; // PER-QUAD: (pattern 0=Dashed/1=Solid/2=Double, dashOn m, dashGap m)
|
|
490
|
+
attribute vec3 a_color; // PER-QUAD: divider colour, RGB 0..1
|
|
491
|
+
|
|
492
|
+
// Camera — Rust builds ONE camera per frame (Engine::fill_camera) and forwards it opaquely; JS computes
|
|
493
|
+
// no camera math, exactly as it forwarded opaque pre-projected vertices before this RFC.
|
|
494
|
+
uniform vec3 u_camPos; // camera eye, world-space (Camera::pos, camera.rs)
|
|
495
|
+
uniform vec3 u_camForward; // unit look direction (Camera::forward)
|
|
496
|
+
uniform float u_aspect; // canvasW / canvasH (Engine::set_aspect) — divides ndc_x ONLY, applied here
|
|
497
|
+
// exactly once (never folded into u_camPos/u_camForward)
|
|
498
|
+
uniform float u_cameraDepth; // focal, Rust consts::CAMERA_DEPTH (1/tan 75°) — no GLSL literal
|
|
499
|
+
uniform float u_dashAnchor; // per-frame dash anchor, Engine::dash_anchor()
|
|
500
|
+
|
|
501
|
+
// Depth-map bounds — fed from Rust via Engine::depth_bounds() (single source with the Rust
|
|
502
|
+
// depth_ndc, so no constant drifts between GLSL and Rust). See depth-test.md.
|
|
503
|
+
uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → nearest, z = -1
|
|
504
|
+
uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → farthest, z = +1
|
|
505
|
+
|
|
506
|
+
// ── Outputs to the fragment shader ───────────────────────────────────────
|
|
507
|
+
varying float v_sScaled; // ÷ v_scale → perspective-correct surface arc-length (the dash)
|
|
508
|
+
varying float v_lateralScaled; // ÷ v_scale → perspective-correct signed lateral L (the lane dividers)
|
|
509
|
+
varying float v_scale; // perspective scale for correct stripe width at any depth
|
|
510
|
+
varying float v_half; // road half-width here (m) — for the edge-vs-interior divider test
|
|
511
|
+
varying float v_pattern; // PER-QUAD divider pattern code (0=Dashed, 1=Solid, 2=Double)
|
|
512
|
+
varying float v_dashOn; // PER-QUAD dash painted length (m) — the per-span dash ruler
|
|
513
|
+
varying float v_dashGap; // PER-QUAD dash gap length (m); period = v_dashOn + v_dashGap
|
|
514
|
+
varying vec3 v_color; // PER-QUAD divider colour (RGB 0..1)
|
|
515
|
+
|
|
516
|
+
// Map perspective scale (CAMERA_DEPTH / cz) → NDC depth z ∈ [-1, 1]. Linear in scale, so with
|
|
517
|
+
// w = 1 it is the EXACT perspective depth (scale ∝ 1/cz is screen-linear, and a linear map
|
|
518
|
+
// commutes with the GPU's screen-linear interpolation). MUST stay identical to the Rust
|
|
519
|
+
// depth_ndc in consts.rs. clamp() is the branchless far-plane-clip backstop (no if/else).
|
|
520
|
+
float depthNdc(float scale) {
|
|
521
|
+
return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// Project a world-space corner into (ndc_x, ndc_y), outing the depth \`cz\` and perspective \`scale\` —
|
|
525
|
+
// a line-for-line mirror of Rust's Camera::project (camera.rs), only relocated CPU → GPU:
|
|
526
|
+
// right = (forward.z, 0, −forward.x) — Camera::right(): DERIVED from forward, never stored, so this
|
|
527
|
+
// mirror can't drift out of orthogonality with a hand-sent copy
|
|
528
|
+
// ray = corner − camPos
|
|
529
|
+
// cx = dot(ray, right) cy = ray.y (world-up is the constant (0,1,0), never dotted)
|
|
530
|
+
// cz = dot(ray, forward) — true depth along the look direction
|
|
531
|
+
// scale = cameraDepth / cz — perspective scale; max()'d so it stays finite past the cull
|
|
532
|
+
// ndc_x = scale · cx / aspect, ndc_y = scale · cy
|
|
533
|
+
vec2 project(vec3 corner, out float cz, out float scale) {
|
|
534
|
+
vec3 right = vec3(u_camForward.z, 0.0, -u_camForward.x);
|
|
535
|
+
vec3 ray = corner - u_camPos;
|
|
536
|
+
cz = dot(ray, u_camForward);
|
|
537
|
+
scale = u_cameraDepth / max(cz, 1e-4); // matches Rust's CULL_MIN_CZ; keeps scale finite past the cull
|
|
538
|
+
return vec2(scale * dot(ray, right) / u_aspect, scale * ray.y);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
void main() {
|
|
542
|
+
vec3 corner = vec3(a_cornerX, a_cornerY, a_cornerZ);
|
|
543
|
+
float cz, scale;
|
|
544
|
+
vec2 ndc = project(corner, cz, scale);
|
|
545
|
+
|
|
546
|
+
// Per-vertex behind-camera cull — the shader-side equivalent of Rust's old per-quad \`projects!\`→
|
|
547
|
+
// continue (camera.rs CULL_MIN_CZ). Branchless (no if/else — feedback_shader_branching.md): push the
|
|
548
|
+
// vertex off-screen so the GPU clips the triangle instead of drawing it. In practice this never fires:
|
|
549
|
+
// the window starts NEAR_PLANE (0.25 m) ahead of the player, so every corner has cz ≳ 0.25 ≫ 1e-4 — the
|
|
550
|
+
// guard only matters at the far tail of a sharp curve (project-in-shader.md § Edge cases).
|
|
551
|
+
float visible = step(1e-4, cz);
|
|
552
|
+
ndc = mix(vec2(2.0, 2.0), ndc, visible);
|
|
553
|
+
|
|
554
|
+
gl_Position = vec4(ndc, depthNdc(scale), 1.0); // w=1 → affine varyings → divider isoline fix intact
|
|
555
|
+
|
|
556
|
+
v_sScaled = (a_s - u_dashAnchor) * scale;
|
|
557
|
+
v_lateralScaled = a_lateral * scale;
|
|
558
|
+
v_scale = scale;
|
|
559
|
+
v_half = a_half;
|
|
560
|
+
v_pattern = a_divider.x;
|
|
561
|
+
v_dashOn = a_divider.y;
|
|
562
|
+
v_dashGap = a_divider.z;
|
|
563
|
+
v_color = a_color;
|
|
564
|
+
}
|
|
565
|
+
`;
|
|
566
|
+
|
|
567
|
+
// ../engine-binding/src/shaders/road.frag.glsl
|
|
568
|
+
var road_frag_default = `precision mediump float;
|
|
569
|
+
|
|
570
|
+
varying float v_sScaled; // (s − dash_anchor)·scale ∝ s/cz — affine in screen space
|
|
571
|
+
varying float v_lateralScaled; // L·scale, L = signed metres from the centreline ∝ L/cz — affine in screen space
|
|
572
|
+
varying float v_scale; // CAMERA_DEPTH / cz — perspective scale (∝ 1/cz)
|
|
573
|
+
varying float v_half; // road half-width here (m)
|
|
574
|
+
varying float v_pattern; // PER-QUAD divider pattern (0=Dashed, 1=Solid, 2=Double)
|
|
575
|
+
varying float v_dashOn; // PER-QUAD dash painted length (m) — the per-span dash ruler
|
|
576
|
+
varying float v_dashGap; // PER-QUAD dash gap length (m)
|
|
577
|
+
varying vec3 v_color; // PER-QUAD divider colour (RGB 0..1)
|
|
578
|
+
|
|
579
|
+
// Lane grid: a boundary every LANE_WIDTH m across the road. DOUBLE_GAP = the offset (m) of each of a Double
|
|
580
|
+
// line's two parallel stripes from the boundary (each is the single-line band shifted ±DOUBLE_GAP). Both MUST
|
|
581
|
+
// equal the Rust consts.rs values (LANE_WIDTH / DOUBLE_GAP) — duplicated across Rust + GLSL, kept in sync by
|
|
582
|
+
// hand (the DASH-const twin idiom). The dash ON/GAP lengths are now PER-SPAN varyings (v_dashOn / v_dashGap),
|
|
583
|
+
// not consts, so a Dashed span sets its own cadence (default 3/9 from the Rust decode).
|
|
584
|
+
const float LANE_WIDTH = 3.25;
|
|
585
|
+
const float DOUBLE_GAP = 0.2;
|
|
586
|
+
// Divider band half-width (world m). Shared by \`halfBand\` (the stripe AA) AND the edge-kill margin
|
|
587
|
+
// (DOUBLE_GAP + HALF_BAND_W) — they MUST use the same value: if they drift, a Double line's inner edge-flank
|
|
588
|
+
// leaks back in, or the nearest interior stripe gets over-eaten. (Mirrored by the P2 fragment-math test.)
|
|
589
|
+
const float HALF_BAND_W = 0.1;
|
|
590
|
+
|
|
591
|
+
// ── step() / mix() / mod() pattern (no if/else) ───────────────────────────────
|
|
592
|
+
//
|
|
593
|
+
// step(edge, x) = 0.0 when x < edge, 1.0 when x ≥ edge — branchless boolean.
|
|
594
|
+
// mix(a, b, t) = a*(1-t) + b*t — selects between two values with t ∈ {0,1}.
|
|
595
|
+
// floor()/mod()/min() are likewise branchless. Combining them avoids warp divergence.
|
|
596
|
+
|
|
597
|
+
void main() {
|
|
598
|
+
gl_FragColor = vec4(0.43, 0.43, 0.43, 1.0); // asphalt grey
|
|
599
|
+
|
|
600
|
+
// Recover surface arc-length AND signed lateral, both perspective-correct: v_sScaled ∝ s/cz,
|
|
601
|
+
// v_lateralScaled ∝ L/cz, and v_scale ∝ 1/cz are ALL affine in screen space, so each ratio is the
|
|
602
|
+
// true value at this pixel — exact on a straight (no naive-interp kink; the dash's proven ÷scale form).
|
|
603
|
+
float s = v_sScaled / v_scale;
|
|
604
|
+
float lat = v_lateralScaled / v_scale; // signed metres from the centreline (− left, + right)
|
|
605
|
+
|
|
606
|
+
// Dash phase: paint the first v_dashOn m of each per-span period (v_dashOn + v_dashGap). The Rust anchor
|
|
607
|
+
// subtracted whole DASH_FULL_PERIOD periods to keep \`s\` small for mediump; a per-span period is the
|
|
608
|
+
// AUTHOR's cadence, so a phase reset at a span boundary is intended (new span, new pattern). Default 3/9.
|
|
609
|
+
float period = v_dashOn + v_dashGap;
|
|
610
|
+
float dashOn = 1.0 - step(v_dashOn, mod(s, period));
|
|
611
|
+
|
|
612
|
+
// Branchless PATTERN select (Foundations §7 — no if/else):
|
|
613
|
+
// isCont = 1 for Solid(1)/Double(2) ⇒ force the line continuous (override the dash).
|
|
614
|
+
// isDouble = 1 for Double(2) only ⇒ swap the single boundary band for two flanking stripes.
|
|
615
|
+
float isCont = step(0.5, v_pattern);
|
|
616
|
+
float isDouble = step(1.5, v_pattern);
|
|
617
|
+
float lineOn = mix(dashOn, 1.0, isCont); // Dashed = the dash; Solid/Double = always on
|
|
618
|
+
|
|
619
|
+
// Lane boundary geometry (unchanged): a boundary sits every LANE_WIDTH from the LEFT edge (lat = −half).
|
|
620
|
+
// \`dist\` = world metres to the nearest boundary; \`dist·v_scale\` is the SCREEN distance, so the AA band is
|
|
621
|
+
// screen-constant at any depth. \`interior\` kills the two ROAD EDGES (k=0 at lat=−half, k=laneCount at
|
|
622
|
+
// lat=+half): step(0.1, half − |lat|) = 0 on an edge, 1 strictly inside ⇒ only interior boundaries paint.
|
|
623
|
+
float m = mod(lat + v_half, LANE_WIDTH); // 0 at any boundary (edges included)
|
|
624
|
+
float dist = min(m, LANE_WIDTH - m); // world metres to the nearest boundary
|
|
625
|
+
float halfBand = HALF_BAND_W * v_scale; // stripe outer edge (fixed world width at any depth)
|
|
626
|
+
float coreBand = 0.75 * halfBand; // plateau (full colour) ends here
|
|
627
|
+
|
|
628
|
+
// SINGLE stripe (Dashed/Solid): the band centred ON the boundary (dist = 0) — today's stripe.
|
|
629
|
+
float onSingle = 1.0 - smoothstep(coreBand, halfBand, dist * v_scale);
|
|
630
|
+
// DOUBLE stripe: \`dist\` is FOLDED (symmetric about the boundary), so ONE band at dist = DOUBLE_GAP lights
|
|
631
|
+
// BOTH flanking lines (m = DOUBLE_GAP and m = LANE_WIDTH − DOUBLE_GAP) — exactly two stripes straddling the
|
|
632
|
+
// boundary, the boundary itself unpainted. Kink-free like onSingle (the same dist·v_scale recovery).
|
|
633
|
+
float onDouble = 1.0 - smoothstep(coreBand, halfBand, abs(dist - DOUBLE_GAP) * v_scale);
|
|
634
|
+
float band = mix(onSingle, onDouble, isDouble);
|
|
635
|
+
|
|
636
|
+
// Kill the divider near the two ROAD EDGES. The threshold is DOUBLE_GAP + HALF_BAND_W (the band's outer
|
|
637
|
+
// reach) so it clears not just the single band ON an edge boundary but also a Double line's INNER flanking
|
|
638
|
+
// stripe (at edge ∓ DOUBLE_GAP) — without the wider margin a Double span would paint a spurious stripe just
|
|
639
|
+
// inside each edge. For a single band this is a no-op (it never reaches that zone), so Dashed/Solid is unchanged.
|
|
640
|
+
float interior = step(DOUBLE_GAP + HALF_BAND_W, v_half - abs(lat)); // 1 strictly inside, 0 near the edges
|
|
641
|
+
|
|
642
|
+
// Paint the divider in its per-span colour; lineOn·band·interior = the coverage (dash × band × not-edge).
|
|
643
|
+
gl_FragColor = mix(gl_FragColor, vec4(v_color, 1.0), lineOn * band * interior);
|
|
644
|
+
}
|
|
645
|
+
`;
|
|
646
|
+
|
|
647
|
+
// ../engine-binding/src/passes/road.ts
|
|
648
|
+
var FLOAT2 = 4;
|
|
649
|
+
var FLOATS_PER_VERTEX = 12;
|
|
650
|
+
var STRIDE2 = FLOATS_PER_VERTEX * FLOAT2;
|
|
651
|
+
var ROAD_ERRORS = {
|
|
652
|
+
LANE_COUNT: "A lane span's lane count must be from 1 to 8.",
|
|
653
|
+
LANE_BOUNDS: "A lane span has a bad range: 0 ≤ start < end ≤ track length.",
|
|
654
|
+
LANE_OVERLAP: "Two lane spans overlap.",
|
|
655
|
+
LANE_TAPER: "Two changes of road width are closer than the 30 m taper.",
|
|
656
|
+
LANE_DASH: "A dashed divider needs dashOn and dashGap above 0.",
|
|
657
|
+
LANE_COLOR: "A divider colour needs each part from 0 to 1.",
|
|
658
|
+
ROAD_CAPACITY: "The track has more road quads in one frame than one draw can index."
|
|
659
|
+
};
|
|
660
|
+
function bindFloat2(gl, loc, size, fieldIndex) {
|
|
661
|
+
if (loc < 0)
|
|
662
|
+
return;
|
|
663
|
+
gl.enableVertexAttribArray(loc);
|
|
664
|
+
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, STRIDE2, fieldIndex * FLOAT2);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
class RoadPass {
|
|
668
|
+
gl;
|
|
669
|
+
engine;
|
|
670
|
+
program;
|
|
671
|
+
vertexBuffer;
|
|
672
|
+
indexBuffer;
|
|
673
|
+
loc;
|
|
674
|
+
locList;
|
|
675
|
+
uni;
|
|
676
|
+
constructor(gl, engine) {
|
|
677
|
+
this.gl = gl;
|
|
678
|
+
this.program = createProgram(gl, road_vert_default, road_frag_default);
|
|
679
|
+
this.vertexBuffer = gl.createBuffer();
|
|
680
|
+
this.loc = {
|
|
681
|
+
a_cornerX: gl.getAttribLocation(this.program, "a_cornerX"),
|
|
682
|
+
a_cornerY: gl.getAttribLocation(this.program, "a_cornerY"),
|
|
683
|
+
a_cornerZ: gl.getAttribLocation(this.program, "a_cornerZ"),
|
|
684
|
+
a_lateral: gl.getAttribLocation(this.program, "a_lateral"),
|
|
685
|
+
a_half: gl.getAttribLocation(this.program, "a_half"),
|
|
686
|
+
a_s: gl.getAttribLocation(this.program, "a_s"),
|
|
687
|
+
a_divider: gl.getAttribLocation(this.program, "a_divider"),
|
|
688
|
+
a_color: gl.getAttribLocation(this.program, "a_color")
|
|
689
|
+
};
|
|
690
|
+
this.locList = Object.values(this.loc);
|
|
691
|
+
this.uni = {
|
|
692
|
+
u_scaleNear: gl.getUniformLocation(this.program, "u_scaleNear"),
|
|
693
|
+
u_scaleFar: gl.getUniformLocation(this.program, "u_scaleFar"),
|
|
694
|
+
u_camPos: gl.getUniformLocation(this.program, "u_camPos"),
|
|
695
|
+
u_camForward: gl.getUniformLocation(this.program, "u_camForward"),
|
|
696
|
+
u_aspect: gl.getUniformLocation(this.program, "u_aspect"),
|
|
697
|
+
u_cameraDepth: gl.getUniformLocation(this.program, "u_cameraDepth"),
|
|
698
|
+
u_dashAnchor: gl.getUniformLocation(this.program, "u_dashAnchor")
|
|
699
|
+
};
|
|
700
|
+
this.engine = engine;
|
|
701
|
+
gl.useProgram(this.program);
|
|
702
|
+
const bounds = engine.depth_bounds();
|
|
703
|
+
gl.uniform1f(this.uni.u_scaleNear, bounds[0]);
|
|
704
|
+
gl.uniform1f(this.uni.u_scaleFar, bounds[1]);
|
|
705
|
+
gl.uniform1f(this.uni.u_cameraDepth, engine.camera_depth());
|
|
706
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
|
707
|
+
gl.bufferData(gl.ARRAY_BUFFER, engine.max_draw_bytes(), gl.DYNAMIC_DRAW);
|
|
708
|
+
const maxQuads = engine.max_draw_bytes() / 4 / FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
|
|
709
|
+
assertQuadCapacity("road", maxQuads, "ROAD_CAPACITY", ROAD_ERRORS.ROAD_CAPACITY);
|
|
710
|
+
this.indexBuffer = gl.createBuffer();
|
|
711
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
|
|
712
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(maxQuads), gl.STATIC_DRAW);
|
|
713
|
+
}
|
|
714
|
+
draw(camera) {
|
|
715
|
+
const gl = this.gl;
|
|
716
|
+
const engine = this.engine;
|
|
717
|
+
gl.useProgram(this.program);
|
|
718
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
|
719
|
+
const view = engine.fill_and_view();
|
|
720
|
+
const floatCount = view.length;
|
|
721
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
|
|
722
|
+
bindFloat2(gl, this.loc.a_cornerX, 1, 0);
|
|
723
|
+
bindFloat2(gl, this.loc.a_cornerY, 1, 1);
|
|
724
|
+
bindFloat2(gl, this.loc.a_cornerZ, 1, 2);
|
|
725
|
+
bindFloat2(gl, this.loc.a_lateral, 1, 3);
|
|
726
|
+
bindFloat2(gl, this.loc.a_half, 1, 4);
|
|
727
|
+
bindFloat2(gl, this.loc.a_s, 1, 5);
|
|
728
|
+
bindFloat2(gl, this.loc.a_divider, 3, 6);
|
|
729
|
+
bindFloat2(gl, this.loc.a_color, 3, 9);
|
|
730
|
+
const cam = camera.current();
|
|
731
|
+
gl.uniform3fv(this.uni.u_camPos, cam.position);
|
|
732
|
+
gl.uniform3fv(this.uni.u_camForward, cam.forward);
|
|
733
|
+
gl.uniform1f(this.uni.u_aspect, engine.aspect());
|
|
734
|
+
gl.uniform1f(this.uni.u_dashAnchor, engine.dash_anchor());
|
|
735
|
+
const quadCount = floatCount / FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
|
|
736
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
|
|
737
|
+
gl.drawElements(gl.TRIANGLES, quadCount * 6, gl.UNSIGNED_SHORT, 0);
|
|
738
|
+
disableAttributes(gl, this.locList);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
// ../engine-binding/src/shaders/scenery.vert.glsl
|
|
742
|
+
var scenery_vert_default = `// project-in-shader (scenery; road and field project the same way, text is still projected in Rust):
|
|
743
|
+
// projection now runs HERE. Rust still resolves the cz-dependent
|
|
744
|
+
// DECISIONS (the back-to-front sort key, the far cull — \`SceneryLayer::emit\`, layers/scenery.rs)
|
|
745
|
+
// and hands this shader a fully-resolved WORLD-SPACE billboard corner (built on the ROAD frame — camera-
|
|
746
|
+
// independent); only the FINAL per-vertex projection (dot(q, forward) etc — Camera::project's exact
|
|
747
|
+
// math) moves CPU → GPU.
|
|
748
|
+
|
|
749
|
+
precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader
|
|
750
|
+
// (mediump would visibly wobble the projection at depth; project-in-shader.md).
|
|
751
|
+
|
|
752
|
+
attribute float a_cornerX; // world-space X of this billboard corner
|
|
753
|
+
attribute float a_cornerY; // world-space Y (elevation) of this billboard corner
|
|
754
|
+
attribute float a_cornerZ; // world-space Z of this billboard corner
|
|
755
|
+
attribute float a_u; // atlas u, RAW (unscaled) — the shader multiplies by its own scale
|
|
756
|
+
attribute float a_v; // atlas v, RAW
|
|
757
|
+
|
|
758
|
+
uniform vec3 u_camPos; // camera eye, world-space (Camera::pos, camera.rs)
|
|
759
|
+
uniform vec3 u_camForward; // unit look direction (Camera::forward)
|
|
760
|
+
uniform float u_aspect; // canvasW / canvasH — divides ndc_x ONLY, applied here exactly once
|
|
761
|
+
uniform float u_cameraDepth; // focal length, Rust consts::CAMERA_DEPTH — no GLSL literal (OQ4)
|
|
762
|
+
uniform float u_nearPlane; // near-clip margin, Rust consts::NEAR_PLANE — the cull threshold below
|
|
763
|
+
|
|
764
|
+
uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
|
|
765
|
+
uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
|
|
766
|
+
|
|
767
|
+
varying float v_scale;
|
|
768
|
+
varying float v_uScaled;
|
|
769
|
+
varying float v_vScaled;
|
|
770
|
+
|
|
771
|
+
// IDENTICAL to road/field's depthNdc (pre-existing, from depth-test.md, unaffected by this cut-down) —
|
|
772
|
+
// same uniforms ⇒ billboards share their depth space exactly, so a sprite depth-tests per-pixel against
|
|
773
|
+
// the road and the ground. MUST match the Rust depth_ndc.
|
|
774
|
+
float depthNdc(float scale) {
|
|
775
|
+
return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// Line-for-line mirror of Rust's Camera::project (camera.rs) — the derivation: \`right\` is DERIVED from
|
|
779
|
+
// \`forward\` (Camera::right(), camera.rs) rather than sent, so it can never drift out of orthogonality;
|
|
780
|
+
// \`cz = dot(ray, forward)\` is the depth-fix math (curved-road.md); \`scale = CAMERA_DEPTH / cz\` is the
|
|
781
|
+
// perspective divisor AND the depth source (depthNdc above).
|
|
782
|
+
vec2 project(vec3 corner, out float cz, out float scale) {
|
|
783
|
+
vec3 right = vec3(u_camForward.z, 0.0, -u_camForward.x);
|
|
784
|
+
vec3 ray = corner - u_camPos;
|
|
785
|
+
cz = dot(ray, u_camForward);
|
|
786
|
+
scale = u_cameraDepth / max(cz, 1e-4);
|
|
787
|
+
return vec2(scale * dot(ray, right) / u_aspect, scale * ray.y);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
void main() {
|
|
791
|
+
vec3 corner = vec3(a_cornerX, a_cornerY, a_cornerZ);
|
|
792
|
+
float cz, scale;
|
|
793
|
+
vec2 ndc = project(corner, cz, scale);
|
|
794
|
+
|
|
795
|
+
// Per-vertex near-clip cull (branchless — feedback_shader_branching.md), threshold u_nearPlane (NOT
|
|
796
|
+
// the old 1e-4 CULL_MIN_CZ — that's tuned for the pure behind-camera case and is far too permissive
|
|
797
|
+
// for a billboard whose corner can dip to cz ∈ (0, NEAR_PLANE) without ever going negative, where
|
|
798
|
+
// \`scale = CAMERA_DEPTH / cz\` still blows up). This is DEFENSE-IN-DEPTH, not the authoritative gate:
|
|
799
|
+
// Rust's \`SceneryLayer::emit\` already checks all 4 corners together before emitting the card at all
|
|
800
|
+
// (a GLSL vertex invocation only sees ITS OWN vertex, not its quad's siblings, so it structurally
|
|
801
|
+
// cannot express "drop the whole card" — only Rust can). This flags the one corner that's still
|
|
802
|
+
// unsafe, degrading it to a per-vertex vanish rather than a wedge, in case that guarantee is ever
|
|
803
|
+
// violated (feedback_near_clip_cull_needs_per_corner.md).
|
|
804
|
+
float visible = step(u_nearPlane, cz);
|
|
805
|
+
ndc = mix(vec2(2.0, 2.0), ndc, visible);
|
|
806
|
+
|
|
807
|
+
gl_Position = vec4(ndc, depthNdc(scale), 1.0); // w=1 → affine UV varyings, exact depth
|
|
808
|
+
|
|
809
|
+
v_scale = scale;
|
|
810
|
+
v_uScaled = a_u * scale;
|
|
811
|
+
v_vScaled = a_v * scale;
|
|
812
|
+
}
|
|
813
|
+
`;
|
|
814
|
+
|
|
815
|
+
// ../engine-binding/src/shaders/scenery.frag.glsl
|
|
816
|
+
var scenery_frag_default = `precision mediump float;
|
|
817
|
+
|
|
818
|
+
uniform sampler2D u_atlas; // the bound RGBA sprite sheet — JS-owned pixels, straight (non-premult) alpha
|
|
819
|
+
|
|
820
|
+
varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
|
|
821
|
+
varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
|
|
822
|
+
varying float v_vScaled; // v·scale ∝ v/cz — affine
|
|
823
|
+
|
|
824
|
+
void main() {
|
|
825
|
+
// Recover perspective-correct atlas (u, v): u·scale ∝ u/cz and scale ∝ 1/cz are BOTH affine under
|
|
826
|
+
// w = 1, so their ratio is the true UV (OQ7 — the field's ÷scale idiom; degrades to flat when the 4
|
|
827
|
+
// corners sit at equal cz, exact on a bend for a wide gantry).
|
|
828
|
+
vec2 uv = vec2(v_uScaled, v_vScaled) / v_scale;
|
|
829
|
+
gl_FragColor = texture2D(u_atlas, uv); // straight RGBA — no discard, no branch; the BLENDER composites it
|
|
830
|
+
}
|
|
831
|
+
`;
|
|
832
|
+
|
|
833
|
+
// ../engine-binding/src/passes/scenery.ts
|
|
834
|
+
var SCENERY_FLOATS_PER_VERTEX = 5;
|
|
835
|
+
var FLOAT3 = 4;
|
|
836
|
+
var STRIDE3 = SCENERY_FLOATS_PER_VERTEX * FLOAT3;
|
|
837
|
+
function bindFloat3(gl, loc, fieldIndex) {
|
|
838
|
+
if (loc < 0)
|
|
839
|
+
return;
|
|
840
|
+
gl.enableVertexAttribArray(loc);
|
|
841
|
+
gl.vertexAttribPointer(loc, 1, gl.FLOAT, false, STRIDE3, fieldIndex * FLOAT3);
|
|
842
|
+
}
|
|
843
|
+
var SCENERY_ERRORS = {
|
|
844
|
+
SCENERY_ATLAS: "The scenery atlas grid is bad: cols and rows are at least 1, each pixel size is a whole number of cells, and the grid has at most 65,536 cells.",
|
|
845
|
+
SCENERY_SPRITE: "A sprite is bad: its cell is outside the grid or declared twice, its cell block does not fit, or its size is not a positive finite number.",
|
|
846
|
+
SCENERY_ASSET: "A scenery asset is bad: its cell is outside the grid, or its cell block does not fit the grid.",
|
|
847
|
+
SCENERY_PLACED: "A placed object names an asset the track does not declare.",
|
|
848
|
+
SCENERY_OBJECT_SPRITE: "An object uses a sprite that the track does not declare.",
|
|
849
|
+
SCENERY_OBJECT_S: "An object is outside the track, or one of its positions is not a finite number.",
|
|
850
|
+
SCENERY_SCALE: "An object's scale must be a finite number, 0 or more. 0 hides the object.",
|
|
851
|
+
SCENERY_ROTATION: "An object's rotation must be a finite number.",
|
|
852
|
+
SCENERY_ORIGIN: "An object's rotation origin must be on the card: each part from 0 to 1.",
|
|
853
|
+
SCENERY_ANIM: "An object has an animate, oscillate or shape key. Animation moved to the scene module.",
|
|
854
|
+
SCENERY_CAPACITY: "The track has more scenery quads than one draw can index.",
|
|
855
|
+
SCENERY_IMAGE_MISSING: "The scenery layer has no image to draw from."
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
class SceneryPass {
|
|
859
|
+
gl;
|
|
860
|
+
engine;
|
|
861
|
+
sceneryProgram = null;
|
|
862
|
+
sceneryBuffer = null;
|
|
863
|
+
sceneryIndexBuffer = null;
|
|
864
|
+
sceneryLoc = null;
|
|
865
|
+
sceneryLocList = [];
|
|
866
|
+
sceneryUni = null;
|
|
867
|
+
sceneryTexture = null;
|
|
868
|
+
constructor(gl, engine) {
|
|
869
|
+
this.gl = gl;
|
|
870
|
+
this.engine = engine;
|
|
871
|
+
const bounds = engine.depth_bounds();
|
|
872
|
+
if (engine.max_scenery_draw_bytes() > 0) {
|
|
873
|
+
this.sceneryProgram = createProgram(gl, scenery_vert_default, scenery_frag_default);
|
|
874
|
+
this.sceneryLoc = {
|
|
875
|
+
a_cornerX: gl.getAttribLocation(this.sceneryProgram, "a_cornerX"),
|
|
876
|
+
a_cornerY: gl.getAttribLocation(this.sceneryProgram, "a_cornerY"),
|
|
877
|
+
a_cornerZ: gl.getAttribLocation(this.sceneryProgram, "a_cornerZ"),
|
|
878
|
+
a_u: gl.getAttribLocation(this.sceneryProgram, "a_u"),
|
|
879
|
+
a_v: gl.getAttribLocation(this.sceneryProgram, "a_v")
|
|
880
|
+
};
|
|
881
|
+
this.sceneryLocList = Object.values(this.sceneryLoc);
|
|
882
|
+
this.sceneryUni = {
|
|
883
|
+
u_camPos: gl.getUniformLocation(this.sceneryProgram, "u_camPos"),
|
|
884
|
+
u_camForward: gl.getUniformLocation(this.sceneryProgram, "u_camForward"),
|
|
885
|
+
u_aspect: gl.getUniformLocation(this.sceneryProgram, "u_aspect")
|
|
886
|
+
};
|
|
887
|
+
gl.useProgram(this.sceneryProgram);
|
|
888
|
+
gl.uniform1f(gl.getUniformLocation(this.sceneryProgram, "u_scaleNear"), bounds[0]);
|
|
889
|
+
gl.uniform1f(gl.getUniformLocation(this.sceneryProgram, "u_scaleFar"), bounds[1]);
|
|
890
|
+
gl.uniform1i(gl.getUniformLocation(this.sceneryProgram, "u_atlas"), 0);
|
|
891
|
+
gl.uniform1f(gl.getUniformLocation(this.sceneryProgram, "u_cameraDepth"), engine.camera_depth());
|
|
892
|
+
gl.uniform1f(gl.getUniformLocation(this.sceneryProgram, "u_nearPlane"), engine.near_plane());
|
|
893
|
+
this.sceneryBuffer = gl.createBuffer();
|
|
894
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.sceneryBuffer);
|
|
895
|
+
gl.bufferData(gl.ARRAY_BUFFER, engine.max_scenery_draw_bytes(), gl.DYNAMIC_DRAW);
|
|
896
|
+
const maxQuads = engine.max_scenery_draw_bytes() / 4 / SCENERY_FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
|
|
897
|
+
assertQuadCapacity("scenery", maxQuads, "SCENERY_CAPACITY", SCENERY_ERRORS.SCENERY_CAPACITY);
|
|
898
|
+
this.sceneryIndexBuffer = gl.createBuffer();
|
|
899
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.sceneryIndexBuffer);
|
|
900
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(maxQuads), gl.STATIC_DRAW);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
setSceneryAtlas(bitmap) {
|
|
904
|
+
if (!this.sceneryProgram)
|
|
905
|
+
return;
|
|
906
|
+
this.sceneryTexture = uploadGridAtlas(this.gl, bitmap);
|
|
907
|
+
}
|
|
908
|
+
draw(camera) {
|
|
909
|
+
const gl = this.gl;
|
|
910
|
+
if (!this.sceneryProgram || !this.sceneryLoc || !this.sceneryTexture)
|
|
911
|
+
return;
|
|
912
|
+
gl.useProgram(this.sceneryProgram);
|
|
913
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.sceneryBuffer);
|
|
914
|
+
const view = this.engine.fill_scenery_and_view();
|
|
915
|
+
if (view.length === 0)
|
|
916
|
+
return;
|
|
917
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
|
|
918
|
+
bindFloat3(gl, this.sceneryLoc.a_cornerX, 0);
|
|
919
|
+
bindFloat3(gl, this.sceneryLoc.a_cornerY, 1);
|
|
920
|
+
bindFloat3(gl, this.sceneryLoc.a_cornerZ, 2);
|
|
921
|
+
bindFloat3(gl, this.sceneryLoc.a_u, 3);
|
|
922
|
+
bindFloat3(gl, this.sceneryLoc.a_v, 4);
|
|
923
|
+
if (this.sceneryUni) {
|
|
924
|
+
const cam = camera.current();
|
|
925
|
+
gl.uniform3fv(this.sceneryUni.u_camPos, cam.position);
|
|
926
|
+
gl.uniform3fv(this.sceneryUni.u_camForward, cam.forward);
|
|
927
|
+
gl.uniform1f(this.sceneryUni.u_aspect, this.engine.aspect());
|
|
928
|
+
}
|
|
929
|
+
gl.enable(gl.BLEND);
|
|
930
|
+
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
|
931
|
+
gl.depthMask(false);
|
|
932
|
+
gl.activeTexture(gl.TEXTURE0);
|
|
933
|
+
gl.bindTexture(gl.TEXTURE_2D, this.sceneryTexture);
|
|
934
|
+
const quadCount = view.length / SCENERY_FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
|
|
935
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.sceneryIndexBuffer);
|
|
936
|
+
gl.drawElements(gl.TRIANGLES, quadCount * 6, gl.UNSIGNED_SHORT, 0);
|
|
937
|
+
disableAttributes(gl, this.sceneryLocList);
|
|
938
|
+
gl.depthMask(true);
|
|
939
|
+
gl.disable(gl.BLEND);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
// ../engine-binding/src/shaders/sky.vert.glsl
|
|
943
|
+
var sky_vert_default = `// ── Sky pass — vertex shader ──────────────────────────────────────────────────
|
|
944
|
+
//
|
|
945
|
+
// sky-cloud.md §1/§2 hook: this pass does NOT project. The buffer carries a static [-1,1]² NDC
|
|
946
|
+
// rectangle directly (a_ndc), so this shader is a pass-through — no Camera::project, no camera
|
|
947
|
+
// basis, w stays 1.0. v_uv just forwards the NDC corner to the fragment stage, which computes the
|
|
948
|
+
// whole cloud shape from it.
|
|
949
|
+
|
|
950
|
+
precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader.
|
|
951
|
+
|
|
952
|
+
attribute vec2 a_ndc; // static per-corner NDC position, uploaded once at construction — never per-frame.
|
|
953
|
+
|
|
954
|
+
varying vec2 v_uv; // forwarded NDC coordinate; the fragment shader samples the cloud shape from this.
|
|
955
|
+
|
|
956
|
+
// sky-cloud.md OQ7: z = +1, the far plane. Passes the LEQUAL depth test against the far-cleared sky
|
|
957
|
+
// band (WebGL's default clearDepth is 1.0); scenery and text draw AFTER this pass and blend on top,
|
|
958
|
+
// so nothing else shares this depth before a blend — no z-fight to guard against.
|
|
959
|
+
const float FAR_Z = 1.0;
|
|
960
|
+
|
|
961
|
+
void main() {
|
|
962
|
+
v_uv = a_ndc;
|
|
963
|
+
gl_Position = vec4(a_ndc, FAR_Z, 1.0);
|
|
964
|
+
}
|
|
965
|
+
`;
|
|
966
|
+
|
|
967
|
+
// ../engine-binding/src/shaders/sky.frag.glsl
|
|
968
|
+
var sky_frag_default = `// ── Sky pass — fragment shader ────────────────────────────────────────────────
|
|
969
|
+
//
|
|
970
|
+
// The whole cloud shape lives here (sky-cloud.md §4/§7): a small union of overlapping circular lobes,
|
|
971
|
+
// combined with \`max\` — no \`if\`/\`else\` (feedback_shader_branching.md). Blended over the existing
|
|
972
|
+
// sky-blue clear with the standard \`over\` operator; this shader never writes depth (depthMask(false),
|
|
973
|
+
// set by passes/sky.ts).
|
|
974
|
+
|
|
975
|
+
precision mediump float;
|
|
976
|
+
|
|
977
|
+
varying vec2 v_uv; // ~[-1,1]², the static NDC quad's interpolated corner.
|
|
978
|
+
|
|
979
|
+
uniform float u_aspect; // canvasW / canvasH — corrects a lobe from an oval to a circle on screen.
|
|
980
|
+
uniform float u_skyOffset; // camera-yaw parallax offset (Engine::sky_parallax(), sky-cloud.md Decision 5).
|
|
981
|
+
|
|
982
|
+
// ── Tunable constants (2026-08-03 tuning pass) ────────────────────────────────────────────────────
|
|
983
|
+
// A BIGGER CLOUD_OPACITY makes clouds more solid; a SMALLER one makes them wispier.
|
|
984
|
+
const float CLOUD_OPACITY = 0.85;
|
|
985
|
+
const vec3 CLOUD_WHITE = vec3(1.0, 1.0, 1.0);
|
|
986
|
+
// A BIGGER CLOUD_EDGE_FRAC (closer to 1.0) gives a harder, less feathered edge; a SMALLER one gives a
|
|
987
|
+
// softer, more spread-out fade. It is the fraction of a lobe's radius that stays fully solid.
|
|
988
|
+
const float CLOUD_EDGE_FRAC = 0.7;
|
|
989
|
+
|
|
990
|
+
// THE READING CORRIDOR — the constraint that actually governs cloud placement below, not just size.
|
|
991
|
+
// Road-anchored titles/signage render near screen CENTRE (measured: |x| well under 0.65, y roughly
|
|
992
|
+
// 0.3–0.75 in a typical frame) and drift with the camera/horizon, unlike this pass's static NDC quad.
|
|
993
|
+
// Rather than track that drift, every lobe center below is kept at |x| ≥ SAFE_X_MIN and y ≥ SAFE_Y_MIN
|
|
994
|
+
// — clear of the corridor with margin, and clear even at the worst-case parallax sweep
|
|
995
|
+
// (SKY_PARALLAX_STRENGTH, consts.rs, is kept small enough that SAFE_X_MIN minus the max sweep still
|
|
996
|
+
// clears the corridor — the two constants are coupled; re-check both if you change either one).
|
|
997
|
+
// SAFE_X_MIN/SAFE_Y_MIN are documentation, not shader inputs — the lobe centers below are hand-placed
|
|
998
|
+
// to respect them, since GLSL ES 1.00 has no assert to enforce it automatically.
|
|
999
|
+
const float SAFE_X_MIN = 0.65;
|
|
1000
|
+
const float SAFE_Y_MIN = 0.78;
|
|
1001
|
+
|
|
1002
|
+
// One soft-edged round lobe: 1.0 at the centre, fading to 0.0 at radius r. \`smoothstep\`'s edges are
|
|
1003
|
+
// given ASCENDING (edge0 < edge1) — GLSL ES 1.00 leaves edge0 > edge1 undefined — then inverted
|
|
1004
|
+
// (1.0 - …) so CLOUD_EDGE_FRAC still reads as "the solid fraction," matching the RFC §4 table's numbers.
|
|
1005
|
+
float lobe(vec2 p, vec2 c, float r) {
|
|
1006
|
+
float d = length((p - c) * vec2(u_aspect, 1.0));
|
|
1007
|
+
return 1.0 - smoothstep(r * CLOUD_EDGE_FRAC, r, d);
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
void main() {
|
|
1011
|
+
vec2 p = v_uv - vec2(u_skyOffset, 0.0);
|
|
1012
|
+
|
|
1013
|
+
// A few small clouds, tucked into the upper corners — clear of the reading corridor (see above) at
|
|
1014
|
+
// every point in the parallax sweep. Hand-picked constants — the exact seed / count / distribution
|
|
1015
|
+
// is a tuning spike (sky-cloud.md § Sub-tasks), not asserted here.
|
|
1016
|
+
|
|
1017
|
+
// Cloud 1 (upper-left): x = -0.72 / -0.85, both ≥ SAFE_X_MIN in magnitude.
|
|
1018
|
+
float a = lobe(p, vec2(-0.72, 0.85), 0.12);
|
|
1019
|
+
a = max(a, lobe(p, vec2(-0.85, 0.80), 0.09));
|
|
1020
|
+
|
|
1021
|
+
// Cloud 2 (upper-right).
|
|
1022
|
+
a = max(a, lobe(p, vec2(0.78, 0.87), 0.12));
|
|
1023
|
+
a = max(a, lobe(p, vec2(0.90, 0.83), 0.09));
|
|
1024
|
+
|
|
1025
|
+
// Cloud 3 (a smaller third puff, left side, still ≥ SAFE_X_MIN).
|
|
1026
|
+
a = max(a, lobe(p, vec2(-0.68, 0.92), 0.08));
|
|
1027
|
+
|
|
1028
|
+
gl_FragColor = vec4(CLOUD_WHITE, a * CLOUD_OPACITY);
|
|
1029
|
+
}
|
|
1030
|
+
`;
|
|
1031
|
+
|
|
1032
|
+
// ../engine-binding/src/passes/sky.ts
|
|
1033
|
+
var FLOAT4 = 4;
|
|
1034
|
+
var FLOATS_PER_VERTEX2 = 2;
|
|
1035
|
+
var STRIDE4 = FLOATS_PER_VERTEX2 * FLOAT4;
|
|
1036
|
+
var QUAD_NDC = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]);
|
|
1037
|
+
|
|
1038
|
+
class SkyPass {
|
|
1039
|
+
gl;
|
|
1040
|
+
program;
|
|
1041
|
+
vertexBuffer;
|
|
1042
|
+
indexBuffer;
|
|
1043
|
+
loc;
|
|
1044
|
+
locList;
|
|
1045
|
+
uni;
|
|
1046
|
+
constructor(gl) {
|
|
1047
|
+
this.gl = gl;
|
|
1048
|
+
this.program = createProgram(gl, sky_vert_default, sky_frag_default);
|
|
1049
|
+
this.loc = { a_ndc: gl.getAttribLocation(this.program, "a_ndc") };
|
|
1050
|
+
this.locList = Object.values(this.loc);
|
|
1051
|
+
this.uni = {
|
|
1052
|
+
u_aspect: gl.getUniformLocation(this.program, "u_aspect"),
|
|
1053
|
+
u_skyOffset: gl.getUniformLocation(this.program, "u_skyOffset")
|
|
1054
|
+
};
|
|
1055
|
+
this.vertexBuffer = gl.createBuffer();
|
|
1056
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
|
1057
|
+
gl.bufferData(gl.ARRAY_BUFFER, QUAD_NDC, gl.STATIC_DRAW);
|
|
1058
|
+
this.indexBuffer = gl.createBuffer();
|
|
1059
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
|
|
1060
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(1), gl.STATIC_DRAW);
|
|
1061
|
+
}
|
|
1062
|
+
draw(engine, groundRows, canvasWidth, canvasHeight) {
|
|
1063
|
+
const gl = this.gl;
|
|
1064
|
+
if (groundRows >= canvasHeight)
|
|
1065
|
+
return;
|
|
1066
|
+
gl.enable(gl.SCISSOR_TEST);
|
|
1067
|
+
gl.scissor(0, groundRows, canvasWidth, canvasHeight - groundRows);
|
|
1068
|
+
gl.enable(gl.BLEND);
|
|
1069
|
+
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
|
1070
|
+
gl.depthMask(false);
|
|
1071
|
+
gl.useProgram(this.program);
|
|
1072
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
|
1073
|
+
gl.enableVertexAttribArray(this.loc.a_ndc);
|
|
1074
|
+
gl.vertexAttribPointer(this.loc.a_ndc, 2, gl.FLOAT, false, STRIDE4, 0);
|
|
1075
|
+
gl.uniform1f(this.uni.u_aspect, engine.aspect());
|
|
1076
|
+
gl.uniform1f(this.uni.u_skyOffset, engine.sky_parallax());
|
|
1077
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
|
|
1078
|
+
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
|
|
1079
|
+
disableAttributes(gl, this.locList);
|
|
1080
|
+
gl.depthMask(true);
|
|
1081
|
+
gl.disable(gl.BLEND);
|
|
1082
|
+
gl.disable(gl.SCISSOR_TEST);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
// ../engine-binding/src/shaders/text.vert.glsl
|
|
1086
|
+
var text_vert_default = `precision mediump float;
|
|
1087
|
+
|
|
1088
|
+
attribute float a_ndcX; // screen X in [-1,1]
|
|
1089
|
+
attribute float a_ndcY; // screen Y in [-1,1]
|
|
1090
|
+
attribute float a_scale; // CAMERA_DEPTH / cz — perspective scale AND the ÷ divisor in the fragment
|
|
1091
|
+
attribute float a_uScaled; // atlas u · scale ∝ u/cz — affine in screen space
|
|
1092
|
+
attribute float a_vScaled; // atlas v · scale ∝ v/cz — affine
|
|
1093
|
+
|
|
1094
|
+
uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
|
|
1095
|
+
uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
|
|
1096
|
+
|
|
1097
|
+
varying float v_scale;
|
|
1098
|
+
varying float v_uScaled;
|
|
1099
|
+
varying float v_vScaled;
|
|
1100
|
+
|
|
1101
|
+
// \`precision mediump float;\` (line 1) is REQUIRED — the one divergence from the scenery.vert twin: text's
|
|
1102
|
+
// FRAGMENT reads \`u_scaleFar\` for the distance-fade, and a uniform shared across stages must MATCH precision.
|
|
1103
|
+
// The fragment declares mediump (it has no default float precision); the vertex defaults to highp, so without
|
|
1104
|
+
// the line \`u_scaleFar\` is highp-in-vertex / mediump-in-fragment → the link error "Precisions of uniform
|
|
1105
|
+
// 'u_scaleFar' differ between VERTEX and FRAGMENT shaders". scenery's fragment never reads u_scaleFar (it only
|
|
1106
|
+
// samples the atlas), so scenery.vert stays highp-default — hence this twin diverges by exactly that line.
|
|
1107
|
+
// (mediump depthNdc is safe: text is a lifted billboard, never coplanar with the highp road it depth-tests
|
|
1108
|
+
// against, so the ~mediump epsilon can't z-fight.) IDENTICAL otherwise to scenery/road depthNdc — same
|
|
1109
|
+
// uniforms ⇒ road-anchored glyphs depth-test per-pixel against the road; MUST match the Rust depth_ndc.
|
|
1110
|
+
float depthNdc(float scale) {
|
|
1111
|
+
return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
void main() {
|
|
1115
|
+
// w = 1 (already projected in Rust): keeps the UV varyings affine and the depth exact.
|
|
1116
|
+
gl_Position = vec4(a_ndcX, a_ndcY, depthNdc(a_scale), 1.0);
|
|
1117
|
+
v_scale = a_scale;
|
|
1118
|
+
v_uScaled = a_uScaled;
|
|
1119
|
+
v_vScaled = a_vScaled;
|
|
1120
|
+
}
|
|
1121
|
+
`;
|
|
1122
|
+
|
|
1123
|
+
// ../engine-binding/src/shaders/text.frag.glsl
|
|
1124
|
+
var text_frag_default = `precision mediump float;
|
|
1125
|
+
|
|
1126
|
+
uniform sampler2D u_atlas; // the gl.ALPHA glyph atlas (1-channel coverage mask), mipmapped — JS-owned
|
|
1127
|
+
uniform vec4 u_color; // per-label tint, .a = the label's alpha (lib-world-objects); the atlas's .a IS the coverage
|
|
1128
|
+
uniform float u_scaleFar; // far edge of the depth window — the distance-fade reference
|
|
1129
|
+
|
|
1130
|
+
varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
|
|
1131
|
+
varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
|
|
1132
|
+
varying float v_vScaled; // v·scale ∝ v/cz — affine
|
|
1133
|
+
|
|
1134
|
+
void main() {
|
|
1135
|
+
// Perspective-correct atlas (u, v): u·scale and scale ∝ 1/cz are BOTH affine under w = 1, so their ratio
|
|
1136
|
+
// is the true UV (the scenery/field ÷scale idiom — the oblique sign's mapping stays artifact-free).
|
|
1137
|
+
vec2 uv = vec2(v_uScaled, v_vScaled) / v_scale;
|
|
1138
|
+
// gl.ALPHA coverage; mipmaps (LINEAR_MIPMAP_LINEAR min) AA the receding tail, where a \`discard\` threshold
|
|
1139
|
+
// would instead COLLAPSE thin strokes down the mip chain (the reason this blends, not cuts out — §6).
|
|
1140
|
+
float cov = texture2D(u_atlas, uv).a;
|
|
1141
|
+
// Distance-fade: 0 far → 1 near. Retires the tiny unreadable far tail (where the 1px gutters would bleed).
|
|
1142
|
+
float fade = smoothstep(u_scaleFar, u_scaleFar * 3.0, v_scale);
|
|
1143
|
+
// Straight-alpha OVER, tinted by the per-label uniform (its .a = the placed label's alpha; road
|
|
1144
|
+
// labels pass 1.0) — branchless, no discard, no median3.
|
|
1145
|
+
gl_FragColor = vec4(u_color.rgb, u_color.a * cov * fade);
|
|
1146
|
+
}
|
|
1147
|
+
`;
|
|
1148
|
+
|
|
1149
|
+
// ../engine-binding/src/passes/text.ts
|
|
1150
|
+
var TEXT_FLOATS_PER_VERTEX = 5;
|
|
1151
|
+
var FLOAT5 = 4;
|
|
1152
|
+
var STRIDE5 = TEXT_FLOATS_PER_VERTEX * FLOAT5;
|
|
1153
|
+
function bindFloat4(gl, loc, fieldIndex) {
|
|
1154
|
+
if (loc < 0)
|
|
1155
|
+
return;
|
|
1156
|
+
gl.enableVertexAttribArray(loc);
|
|
1157
|
+
gl.vertexAttribPointer(loc, 1, gl.FLOAT, false, STRIDE5, fieldIndex * FLOAT5);
|
|
1158
|
+
}
|
|
1159
|
+
var TEXT_ERRORS = {
|
|
1160
|
+
TEXT_FONT: "The font is bad: scaleW, scaleH and lineHeight are finite and above 0, and base is finite and 0 or more.",
|
|
1161
|
+
TEXT_GLYPH: "A glyph has a bad rectangle, a negative size, or an offset or advance that is not a finite number.",
|
|
1162
|
+
TEXT_GLYPH_DUP: "The font declares one glyph twice.",
|
|
1163
|
+
TEXT_LABEL: "A label is bad: its height is a finite number, 0 or more (0 hides it), and each part of its colour is from 0 to 1.",
|
|
1164
|
+
TEXT_ROAD_S: "A label is outside the track, or one of its positions is not a finite number.",
|
|
1165
|
+
TEXT_CODEPOINT: "A label has a character with no glyph in the font.",
|
|
1166
|
+
TEXT_ANIM: "A label has an animate or shape key. Animation moved to the scene module.",
|
|
1167
|
+
TEXT_CAPACITY: "The track has more glyph quads than one draw can index.",
|
|
1168
|
+
TEXT_IMAGE_MISSING: "The text layer has no image to draw from.",
|
|
1169
|
+
TEXT_IMAGE_SIZE: "The text atlas image must be loaded, with power-of-two sides such as 256 × 256."
|
|
1170
|
+
};
|
|
1171
|
+
|
|
1172
|
+
class TextPass {
|
|
1173
|
+
gl;
|
|
1174
|
+
engine;
|
|
1175
|
+
textProgram = null;
|
|
1176
|
+
textBuffer = null;
|
|
1177
|
+
textIndexBuffer = null;
|
|
1178
|
+
textLoc = null;
|
|
1179
|
+
textLocList = [];
|
|
1180
|
+
uColor = null;
|
|
1181
|
+
textTexture = null;
|
|
1182
|
+
constructor(gl, engine) {
|
|
1183
|
+
this.gl = gl;
|
|
1184
|
+
this.engine = engine;
|
|
1185
|
+
const bounds = engine.depth_bounds();
|
|
1186
|
+
if (engine.max_text_draw_bytes() > 0) {
|
|
1187
|
+
this.textProgram = createProgram(gl, text_vert_default, text_frag_default);
|
|
1188
|
+
this.textLoc = {
|
|
1189
|
+
a_ndcX: gl.getAttribLocation(this.textProgram, "a_ndcX"),
|
|
1190
|
+
a_ndcY: gl.getAttribLocation(this.textProgram, "a_ndcY"),
|
|
1191
|
+
a_scale: gl.getAttribLocation(this.textProgram, "a_scale"),
|
|
1192
|
+
a_uScaled: gl.getAttribLocation(this.textProgram, "a_uScaled"),
|
|
1193
|
+
a_vScaled: gl.getAttribLocation(this.textProgram, "a_vScaled")
|
|
1194
|
+
};
|
|
1195
|
+
this.textLocList = Object.values(this.textLoc);
|
|
1196
|
+
gl.useProgram(this.textProgram);
|
|
1197
|
+
gl.uniform1f(gl.getUniformLocation(this.textProgram, "u_scaleNear"), bounds[0]);
|
|
1198
|
+
gl.uniform1f(gl.getUniformLocation(this.textProgram, "u_scaleFar"), bounds[1]);
|
|
1199
|
+
gl.uniform1i(gl.getUniformLocation(this.textProgram, "u_atlas"), 0);
|
|
1200
|
+
this.uColor = gl.getUniformLocation(this.textProgram, "u_color");
|
|
1201
|
+
this.textBuffer = gl.createBuffer();
|
|
1202
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.textBuffer);
|
|
1203
|
+
gl.bufferData(gl.ARRAY_BUFFER, engine.max_text_draw_bytes(), gl.DYNAMIC_DRAW);
|
|
1204
|
+
const maxQuads = engine.max_text_draw_bytes() / 4 / TEXT_FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
|
|
1205
|
+
assertQuadCapacity("text", maxQuads, "TEXT_CAPACITY", TEXT_ERRORS.TEXT_CAPACITY);
|
|
1206
|
+
this.textIndexBuffer = gl.createBuffer();
|
|
1207
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.textIndexBuffer);
|
|
1208
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(maxQuads), gl.STATIC_DRAW);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
setTextAtlas(bitmap) {
|
|
1212
|
+
assertMipmapable("TEXT_IMAGE_SIZE", TEXT_ERRORS.TEXT_IMAGE_SIZE, "text({ atlas })", bitmap);
|
|
1213
|
+
const gl = this.gl;
|
|
1214
|
+
if (!this.textProgram)
|
|
1215
|
+
return;
|
|
1216
|
+
const tex = gl.createTexture();
|
|
1217
|
+
if (!tex)
|
|
1218
|
+
throw new Error("createTexture failed");
|
|
1219
|
+
gl.bindTexture(gl.TEXTURE_2D, tex);
|
|
1220
|
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, gl.ALPHA, gl.UNSIGNED_BYTE, bitmap);
|
|
1221
|
+
gl.generateMipmap(gl.TEXTURE_2D);
|
|
1222
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
|
1223
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
|
1224
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
|
1225
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
|
1226
|
+
this.textTexture = tex;
|
|
1227
|
+
}
|
|
1228
|
+
draw() {
|
|
1229
|
+
const gl = this.gl;
|
|
1230
|
+
if (!this.textProgram || !this.textLoc || !this.textTexture)
|
|
1231
|
+
return;
|
|
1232
|
+
gl.useProgram(this.textProgram);
|
|
1233
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.textBuffer);
|
|
1234
|
+
const view = this.engine.fill_text_and_view();
|
|
1235
|
+
if (view.length === 0)
|
|
1236
|
+
return;
|
|
1237
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
|
|
1238
|
+
bindFloat4(gl, this.textLoc.a_ndcX, 0);
|
|
1239
|
+
bindFloat4(gl, this.textLoc.a_ndcY, 1);
|
|
1240
|
+
bindFloat4(gl, this.textLoc.a_scale, 2);
|
|
1241
|
+
bindFloat4(gl, this.textLoc.a_uScaled, 3);
|
|
1242
|
+
bindFloat4(gl, this.textLoc.a_vScaled, 4);
|
|
1243
|
+
gl.enable(gl.BLEND);
|
|
1244
|
+
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
|
1245
|
+
gl.enable(gl.DEPTH_TEST);
|
|
1246
|
+
gl.depthMask(false);
|
|
1247
|
+
gl.activeTexture(gl.TEXTURE0);
|
|
1248
|
+
gl.bindTexture(gl.TEXTURE_2D, this.textTexture);
|
|
1249
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.textIndexBuffer);
|
|
1250
|
+
const ranges = this.engine.text_draw_ranges();
|
|
1251
|
+
for (let i = 0;i + 5 < ranges.length; i += 6) {
|
|
1252
|
+
const start = ranges[i];
|
|
1253
|
+
const count = ranges[i + 1];
|
|
1254
|
+
gl.uniform4f(this.uColor, ranges[i + 2], ranges[i + 3], ranges[i + 4], ranges[i + 5]);
|
|
1255
|
+
drawQuadRange(gl, start, count);
|
|
1256
|
+
}
|
|
1257
|
+
disableAttributes(gl, this.textLocList);
|
|
1258
|
+
gl.depthMask(true);
|
|
1259
|
+
gl.disable(gl.BLEND);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
// ../engine-binding/src/scene-module.ts
|
|
1263
|
+
var SCENE_MODULE_ERRORS = {
|
|
1264
|
+
SCENE_HOST: "The scene module is not one this library reads: it has no moveby.host section of version 2, or that section is malformed. Build it again.",
|
|
1265
|
+
SCENE_POSITION: "The scene declares no dynamic input named position.",
|
|
1266
|
+
SCENE_KIND: `An object's kind is not image(<asset>) or text("<string>"), or its arguments are not one asset or one string.`,
|
|
1267
|
+
SCENE_PROPERTY: "An object does not declare exactly the properties its kind takes.",
|
|
1268
|
+
SCENE_NAME: "An out field of the scene is not camera_x or camera_y.",
|
|
1269
|
+
SCENE_ASSET: "An image does not bind an asset of the scene's moveby.asset group, or the page's asset records do not fit the scene.",
|
|
1270
|
+
SCENE_TRACK: "The track file and the scene do not fit: the track holds placed rows of its own, or it lacks the atlas grid or the font that the scene needs. Build the track again beside the scene.",
|
|
1271
|
+
SCENE_USING: "A using input of the scene gets no value at load, or one that is not a finite number.",
|
|
1272
|
+
SCENE_DYNAMIC: "A dynamic input is missing from the draw call, or is not a finite number.",
|
|
1273
|
+
SCENE_VALUE: "A value from the scene is out of range: not finite, a size below 0, or an alpha, a pivot part or a colour part outside 0 to 1. It is never clamped: the frame is rejected as a whole."
|
|
1274
|
+
};
|
|
1275
|
+
function sceneError(code, detail) {
|
|
1276
|
+
return new MovebyError(code, `${SCENE_MODULE_ERRORS[code]} (${detail})`);
|
|
1277
|
+
}
|
|
1278
|
+
var HOST_SECTION = "moveby.host";
|
|
1279
|
+
var HOST_VERSION = 2;
|
|
1280
|
+
var KIND_CALL = 1;
|
|
1281
|
+
var ARG_NUMBER = 0;
|
|
1282
|
+
var ARG_STRING = 1;
|
|
1283
|
+
var ARG_SLOT = 2;
|
|
1284
|
+
function readHostTable(section) {
|
|
1285
|
+
const view = new DataView(section.buffer, section.byteOffset, section.byteLength);
|
|
1286
|
+
const utf8 = new TextDecoder;
|
|
1287
|
+
let at = 0;
|
|
1288
|
+
const malformed = (detail) => {
|
|
1289
|
+
throw sceneError("SCENE_HOST", detail);
|
|
1290
|
+
};
|
|
1291
|
+
const byte = () => {
|
|
1292
|
+
if (at >= section.length)
|
|
1293
|
+
malformed("the host table ends early");
|
|
1294
|
+
return section[at++];
|
|
1295
|
+
};
|
|
1296
|
+
const u32 = () => {
|
|
1297
|
+
let result = 0;
|
|
1298
|
+
let shift = 0;
|
|
1299
|
+
for (;; ) {
|
|
1300
|
+
const b = byte();
|
|
1301
|
+
result |= (b & 127) << shift;
|
|
1302
|
+
if ((b & 128) === 0)
|
|
1303
|
+
return result >>> 0;
|
|
1304
|
+
shift += 7;
|
|
1305
|
+
if (shift > 28)
|
|
1306
|
+
malformed("the host table holds an over-long integer");
|
|
1307
|
+
}
|
|
1308
|
+
};
|
|
1309
|
+
const str = () => {
|
|
1310
|
+
const length = u32();
|
|
1311
|
+
if (at + length > section.length)
|
|
1312
|
+
malformed("the host table ends early");
|
|
1313
|
+
const text2 = utf8.decode(section.subarray(at, at + length));
|
|
1314
|
+
at += length;
|
|
1315
|
+
return text2;
|
|
1316
|
+
};
|
|
1317
|
+
const f32 = () => {
|
|
1318
|
+
if (at + 4 > section.length)
|
|
1319
|
+
malformed("the host table ends early");
|
|
1320
|
+
const value = view.getFloat32(at, true);
|
|
1321
|
+
at += 4;
|
|
1322
|
+
return value;
|
|
1323
|
+
};
|
|
1324
|
+
const vec = (read) => {
|
|
1325
|
+
const items = [];
|
|
1326
|
+
for (let n = u32();n > 0; n--)
|
|
1327
|
+
items.push(read());
|
|
1328
|
+
return items;
|
|
1329
|
+
};
|
|
1330
|
+
const argument = () => {
|
|
1331
|
+
const tag = byte();
|
|
1332
|
+
if (tag === ARG_NUMBER)
|
|
1333
|
+
return { kind: "literal", value: f32() };
|
|
1334
|
+
if (tag === ARG_STRING)
|
|
1335
|
+
return { kind: "literal", value: str() };
|
|
1336
|
+
if (tag === ARG_SLOT)
|
|
1337
|
+
return { kind: "using", slot: u32() };
|
|
1338
|
+
return malformed(`the host table holds an unknown argument tag 0x${tag.toString(16)}`);
|
|
1339
|
+
};
|
|
1340
|
+
const object = () => {
|
|
1341
|
+
const name = str();
|
|
1342
|
+
const firstLeaf = u32();
|
|
1343
|
+
const leafCount = u32();
|
|
1344
|
+
const tag = byte();
|
|
1345
|
+
if (tag !== KIND_CALL)
|
|
1346
|
+
malformed(`the host table holds an unknown kind tag 0x${tag.toString(16)}`);
|
|
1347
|
+
const kindName = str();
|
|
1348
|
+
const id = u32();
|
|
1349
|
+
const args = vec(argument);
|
|
1350
|
+
return { name, firstLeaf, leafCount, kind: { name: kindName, id, args } };
|
|
1351
|
+
};
|
|
1352
|
+
const version = u32();
|
|
1353
|
+
if (version !== HOST_VERSION) {
|
|
1354
|
+
malformed(`the host table has version ${version}, this reader reads ${HOST_VERSION}`);
|
|
1355
|
+
}
|
|
1356
|
+
const dynamic = vec(str);
|
|
1357
|
+
const using = vec(str);
|
|
1358
|
+
const outOffset = u32();
|
|
1359
|
+
const leaves = vec(str);
|
|
1360
|
+
const objects = vec(object);
|
|
1361
|
+
for (let n = u32();n > 0; n--) {
|
|
1362
|
+
u32();
|
|
1363
|
+
for (let m = u32();m > 0; m--) {
|
|
1364
|
+
str();
|
|
1365
|
+
u32();
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
if (u32() & 1)
|
|
1369
|
+
u32();
|
|
1370
|
+
if (at !== section.length)
|
|
1371
|
+
malformed("the host table holds trailing bytes");
|
|
1372
|
+
return { version, dynamic, using, outOffset, leaves, objects };
|
|
1373
|
+
}
|
|
1374
|
+
var IMAGE_PROPERTIES = ["x", "y", "z", "yaw", "pitch", "roll", "scale", "origin_x", "origin_y"];
|
|
1375
|
+
var LABEL_PROPERTIES = ["x", "y", "z", "yaw", "height", "alpha", "color_r", "color_g", "color_b"];
|
|
1376
|
+
var CAMERA_FIELDS = ["camera_x", "camera_y"];
|
|
1377
|
+
var CAMERA_SLOTS = CAMERA_FIELDS.length;
|
|
1378
|
+
var ASSET_SLOTS = 2;
|
|
1379
|
+
var ASSET_GROUP = "moveby.asset.";
|
|
1380
|
+
function checkScene(table) {
|
|
1381
|
+
const { dynamic, using, leaves, objects } = table;
|
|
1382
|
+
if (table.version !== HOST_VERSION) {
|
|
1383
|
+
throw sceneError("SCENE_HOST", `version ${table.version}, this reader reads ${HOST_VERSION}`);
|
|
1384
|
+
}
|
|
1385
|
+
if (!dynamic.includes("position")) {
|
|
1386
|
+
throw sceneError("SCENE_POSITION", `dynamic { ${dynamic.join(", ")} }`);
|
|
1387
|
+
}
|
|
1388
|
+
checkRanges(objects, leaves.length);
|
|
1389
|
+
const assets = planAssets(dynamic.length, using);
|
|
1390
|
+
const rows = readRows(table, assets);
|
|
1391
|
+
return {
|
|
1392
|
+
dynamic,
|
|
1393
|
+
using,
|
|
1394
|
+
assets: assets.names,
|
|
1395
|
+
objects: rows.objects,
|
|
1396
|
+
labels: rows.labels,
|
|
1397
|
+
map: gatherMap(assets.names.length, rows)
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
function checkRanges(objects, leafCount) {
|
|
1401
|
+
let end = 0;
|
|
1402
|
+
for (const object of objects) {
|
|
1403
|
+
if (object.firstLeaf < end || object.leafCount > leafCount - object.firstLeaf) {
|
|
1404
|
+
throw sceneError("SCENE_HOST", `${object.name} does not cover a range of its own in out[]`);
|
|
1405
|
+
}
|
|
1406
|
+
end = object.firstLeaf + object.leafCount;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
function planAssets(dynamicCount, using) {
|
|
1410
|
+
const names = [];
|
|
1411
|
+
const indexOfUsing = new Int32Array(using.length).fill(-1);
|
|
1412
|
+
using.forEach((path, i) => {
|
|
1413
|
+
if (path.startsWith(ASSET_GROUP)) {
|
|
1414
|
+
indexOfUsing[i] = names.length;
|
|
1415
|
+
names.push(path.slice(ASSET_GROUP.length));
|
|
1416
|
+
}
|
|
1417
|
+
});
|
|
1418
|
+
return { names, indexOfUsing, dynamicCount };
|
|
1419
|
+
}
|
|
1420
|
+
function readRows(table, assets) {
|
|
1421
|
+
const { leaves, objects } = table;
|
|
1422
|
+
const cameraLeaf = [-1, -1];
|
|
1423
|
+
const sceneObjects = [];
|
|
1424
|
+
const objectLeaves = [];
|
|
1425
|
+
const labels = [];
|
|
1426
|
+
const labelLeaves = [];
|
|
1427
|
+
let leaf = 0;
|
|
1428
|
+
let next = 0;
|
|
1429
|
+
while (leaf < leaves.length) {
|
|
1430
|
+
const object = objects[next];
|
|
1431
|
+
if (object && object.firstLeaf === leaf) {
|
|
1432
|
+
if (object.kind.name === "image") {
|
|
1433
|
+
sceneObjects.push(sceneImage(object, assets));
|
|
1434
|
+
objectLeaves.push(propertyLeaves(object, leaves, IMAGE_PROPERTIES));
|
|
1435
|
+
} else if (object.kind.name === "text") {
|
|
1436
|
+
labels.push(sceneLabel(object));
|
|
1437
|
+
labelLeaves.push(propertyLeaves(object, leaves, LABEL_PROPERTIES));
|
|
1438
|
+
} else {
|
|
1439
|
+
throw sceneError("SCENE_KIND", `${object.name}: ${object.kind.name}`);
|
|
1440
|
+
}
|
|
1441
|
+
leaf += object.leafCount;
|
|
1442
|
+
next++;
|
|
1443
|
+
} else {
|
|
1444
|
+
const at = CAMERA_FIELDS.indexOf(leaves[leaf]);
|
|
1445
|
+
if (at < 0)
|
|
1446
|
+
throw sceneError("SCENE_NAME", leaves[leaf]);
|
|
1447
|
+
cameraLeaf[at] = leaf;
|
|
1448
|
+
leaf++;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
return { cameraLeaf, objects: sceneObjects, objectLeaves, labels, labelLeaves };
|
|
1452
|
+
}
|
|
1453
|
+
function sceneImage(object, assets) {
|
|
1454
|
+
const [argument] = object.kind.args;
|
|
1455
|
+
if (object.kind.args.length !== 1 || !argument) {
|
|
1456
|
+
throw sceneError("SCENE_KIND", `${object.name}: image takes one argument`);
|
|
1457
|
+
}
|
|
1458
|
+
const slot = argument.kind === "using" ? argument.slot : -1;
|
|
1459
|
+
const usingIndex = slot - assets.dynamicCount;
|
|
1460
|
+
const inUsingRange = usingIndex >= 0 && usingIndex < assets.indexOfUsing.length;
|
|
1461
|
+
if (!inUsingRange || assets.indexOfUsing[usingIndex] < 0) {
|
|
1462
|
+
throw sceneError("SCENE_ASSET", `${object.name}: image takes an asset of the ${ASSET_GROUP}* group`);
|
|
1463
|
+
}
|
|
1464
|
+
return { name: object.name, assetSlot: slot };
|
|
1465
|
+
}
|
|
1466
|
+
function sceneLabel(object) {
|
|
1467
|
+
const [argument] = object.kind.args;
|
|
1468
|
+
if (object.kind.args.length !== 1 || argument?.kind !== "literal" || typeof argument.value !== "string") {
|
|
1469
|
+
throw sceneError("SCENE_KIND", `${object.name}: text takes one string argument`);
|
|
1470
|
+
}
|
|
1471
|
+
return { name: object.name, text: argument.value };
|
|
1472
|
+
}
|
|
1473
|
+
function propertyLeaves(object, leaves, properties) {
|
|
1474
|
+
const found = new Array(properties.length).fill(-1);
|
|
1475
|
+
for (let i = 0;i < object.leafCount; i++) {
|
|
1476
|
+
const leaf = object.firstLeaf + i;
|
|
1477
|
+
const at = properties.indexOf(leaves[leaf].slice(object.name.length + 1));
|
|
1478
|
+
if (at < 0 || found[at] >= 0) {
|
|
1479
|
+
throw sceneError("SCENE_PROPERTY", `${leaves[leaf]}: ${object.name} takes exactly ${properties.join(", ")}`);
|
|
1480
|
+
}
|
|
1481
|
+
found[at] = leaf;
|
|
1482
|
+
}
|
|
1483
|
+
const missing = found.indexOf(-1);
|
|
1484
|
+
if (missing >= 0) {
|
|
1485
|
+
throw sceneError("SCENE_PROPERTY", `${object.name}: ${properties[missing]} is missing`);
|
|
1486
|
+
}
|
|
1487
|
+
return found;
|
|
1488
|
+
}
|
|
1489
|
+
function gatherMap(assetCount, rows) {
|
|
1490
|
+
const objectBase = CAMERA_SLOTS + assetCount * ASSET_SLOTS;
|
|
1491
|
+
const labelBase = objectBase + rows.objectLeaves.length * IMAGE_PROPERTIES.length;
|
|
1492
|
+
const map = new Int32Array(labelBase + rows.labelLeaves.length * LABEL_PROPERTIES.length).fill(-1);
|
|
1493
|
+
rows.cameraLeaf.forEach((leaf, slot) => {
|
|
1494
|
+
if (leaf >= 0)
|
|
1495
|
+
map[slot] = leaf;
|
|
1496
|
+
});
|
|
1497
|
+
for (const [base, records] of [[objectBase, rows.objectLeaves], [labelBase, rows.labelLeaves]]) {
|
|
1498
|
+
records.forEach((leaves, i) => {
|
|
1499
|
+
leaves.forEach((leaf, p) => {
|
|
1500
|
+
map[base + i * leaves.length + p] = leaf;
|
|
1501
|
+
});
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
return map;
|
|
1505
|
+
}
|
|
1506
|
+
function asset(name, look) {
|
|
1507
|
+
return {
|
|
1508
|
+
name,
|
|
1509
|
+
cell: look.cell,
|
|
1510
|
+
cols: look.cols ?? 1,
|
|
1511
|
+
rows: look.rows ?? 1,
|
|
1512
|
+
width: look.width,
|
|
1513
|
+
height: look.height
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
var engineModule = null;
|
|
1517
|
+
function engineReady() {
|
|
1518
|
+
engineModule ??= import("./engine/wasm_engine.js").then((module) => {
|
|
1519
|
+
const start = module.default;
|
|
1520
|
+
return start ? start().then(() => module) : module;
|
|
1521
|
+
});
|
|
1522
|
+
return engineModule;
|
|
1523
|
+
}
|
|
1524
|
+
var FILL_BY_ARITY = [
|
|
1525
|
+
(fill) => fill(),
|
|
1526
|
+
(fill, v) => fill(v[0]),
|
|
1527
|
+
(fill, v) => fill(v[0], v[1]),
|
|
1528
|
+
(fill, v) => fill(v[0], v[1], v[2]),
|
|
1529
|
+
(fill, v) => fill(v[0], v[1], v[2], v[3]),
|
|
1530
|
+
(fill, v) => fill(v[0], v[1], v[2], v[3], v[4]),
|
|
1531
|
+
(fill, v) => fill(v[0], v[1], v[2], v[3], v[4], v[5]),
|
|
1532
|
+
(fill, v) => fill(v[0], v[1], v[2], v[3], v[4], v[5], v[6]),
|
|
1533
|
+
(fill, v) => fill(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7])
|
|
1534
|
+
];
|
|
1535
|
+
var FILL_MANY = (fill, values) => Reflect.apply(fill, undefined, values);
|
|
1536
|
+
function readPath(values, keys) {
|
|
1537
|
+
let value = values;
|
|
1538
|
+
for (let i = 0;i < keys.length; i++) {
|
|
1539
|
+
if (typeof value !== "object" || value === null)
|
|
1540
|
+
return;
|
|
1541
|
+
value = value[keys[i]];
|
|
1542
|
+
}
|
|
1543
|
+
return value;
|
|
1544
|
+
}
|
|
1545
|
+
function isNumber(value) {
|
|
1546
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1547
|
+
}
|
|
1548
|
+
function bindAssets(names, records) {
|
|
1549
|
+
const byName = new Map;
|
|
1550
|
+
for (const record of records ?? []) {
|
|
1551
|
+
if (byName.has(record.name))
|
|
1552
|
+
throw sceneError("SCENE_ASSET", `two records named ${record.name}`);
|
|
1553
|
+
byName.set(record.name, record);
|
|
1554
|
+
}
|
|
1555
|
+
return names.map((name) => {
|
|
1556
|
+
const record = byName.get(name);
|
|
1557
|
+
if (!record)
|
|
1558
|
+
throw sceneError("SCENE_ASSET", `no record for ${name}`);
|
|
1559
|
+
const { cell, cols, rows, width, height } = record;
|
|
1560
|
+
if (![cell, cols, rows, width, height].every(Number.isFinite)) {
|
|
1561
|
+
throw sceneError("SCENE_VALUE", `asset ${name} holds a value that is not finite`);
|
|
1562
|
+
}
|
|
1563
|
+
if (width < 0 || height < 0) {
|
|
1564
|
+
throw sceneError("SCENE_VALUE", `asset ${name}: a size below 0 (${width} × ${height})`);
|
|
1565
|
+
}
|
|
1566
|
+
if (![cell, cols, rows].every((n) => Number.isInteger(n)) || cols < 1 || rows < 1) {
|
|
1567
|
+
throw sceneError("SCENE_ASSET", `${name}: cell ${cell} with a block of ${cols} × ${rows} is not whole cells`);
|
|
1568
|
+
}
|
|
1569
|
+
return record;
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
function usingValues(paths, using) {
|
|
1573
|
+
const values = [];
|
|
1574
|
+
let asset2 = 0;
|
|
1575
|
+
for (const path of paths) {
|
|
1576
|
+
if (path.startsWith(ASSET_GROUP)) {
|
|
1577
|
+
values.push(asset2++);
|
|
1578
|
+
} else {
|
|
1579
|
+
const value = readPath(using ?? {}, path.split("."));
|
|
1580
|
+
if (!isNumber(value))
|
|
1581
|
+
throw sceneError("SCENE_USING", path);
|
|
1582
|
+
values.push(value);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
return values;
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
class Track {
|
|
1589
|
+
engine;
|
|
1590
|
+
scene;
|
|
1591
|
+
plan;
|
|
1592
|
+
leaves;
|
|
1593
|
+
out;
|
|
1594
|
+
sizes;
|
|
1595
|
+
inputs;
|
|
1596
|
+
dynamicKeys;
|
|
1597
|
+
fillWith;
|
|
1598
|
+
positionAt;
|
|
1599
|
+
constructor(engine, scene, table, plan, records, out) {
|
|
1600
|
+
this.engine = engine;
|
|
1601
|
+
this.scene = scene;
|
|
1602
|
+
this.plan = plan;
|
|
1603
|
+
this.leaves = table.leaves;
|
|
1604
|
+
this.out = out;
|
|
1605
|
+
this.sizes = Float32Array.from(records.flatMap((record) => [record.width, record.height]));
|
|
1606
|
+
this.inputs = new Float64Array(plan.dynamic.length);
|
|
1607
|
+
this.dynamicKeys = plan.dynamic.map((path) => path.split("."));
|
|
1608
|
+
this.fillWith = FILL_BY_ARITY[plan.dynamic.length] ?? FILL_MANY;
|
|
1609
|
+
this.positionAt = plan.dynamic.indexOf("position");
|
|
1610
|
+
}
|
|
1611
|
+
draw(dynamic) {
|
|
1612
|
+
const paths = this.plan.dynamic;
|
|
1613
|
+
for (let i = 0;i < paths.length; i++) {
|
|
1614
|
+
const value = readPath(dynamic, this.dynamicKeys[i]);
|
|
1615
|
+
if (!isNumber(value))
|
|
1616
|
+
throw sceneError("SCENE_DYNAMIC", paths[i]);
|
|
1617
|
+
this.inputs[i] = value;
|
|
1618
|
+
}
|
|
1619
|
+
this.fillWith(this.scene.$fill, this.inputs);
|
|
1620
|
+
const stage = this.engine.value_view();
|
|
1621
|
+
const { map } = this.plan;
|
|
1622
|
+
const out = this.out;
|
|
1623
|
+
for (let i = 0;i < map.length; i++) {
|
|
1624
|
+
const leaf = map[i];
|
|
1625
|
+
if (leaf >= 0)
|
|
1626
|
+
stage[i] = out[leaf];
|
|
1627
|
+
}
|
|
1628
|
+
for (let i = 0;i < this.sizes.length; i++)
|
|
1629
|
+
stage[CAMERA_SLOTS + i] = this.sizes[i];
|
|
1630
|
+
const bad = this.engine.commit_value_block();
|
|
1631
|
+
if (bad >= 0)
|
|
1632
|
+
throw sceneError("SCENE_VALUE", `${this.pathOf(bad)} is ${stage[bad]}`);
|
|
1633
|
+
this.engine.seek(this.inputs[this.positionAt]);
|
|
1634
|
+
}
|
|
1635
|
+
reset() {
|
|
1636
|
+
this.scene.$reset();
|
|
1637
|
+
}
|
|
1638
|
+
pathOf(slot) {
|
|
1639
|
+
const leaf = this.plan.map[slot];
|
|
1640
|
+
if (leaf >= 0)
|
|
1641
|
+
return this.leaves[leaf];
|
|
1642
|
+
if (slot < CAMERA_SLOTS)
|
|
1643
|
+
return CAMERA_FIELDS[slot];
|
|
1644
|
+
const asset2 = Math.floor((slot - CAMERA_SLOTS) / ASSET_SLOTS);
|
|
1645
|
+
const size = slot % ASSET_SLOTS === 0 ? "width" : "height";
|
|
1646
|
+
return `${this.plan.assets[asset2]}.${size}`;
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
async function loadTrack(trackBytes, sceneBytes, inputs = {}) {
|
|
1650
|
+
let module;
|
|
1651
|
+
try {
|
|
1652
|
+
module = await WebAssembly.compile(sceneBytes);
|
|
1653
|
+
} catch (error) {
|
|
1654
|
+
throw sceneError("SCENE_HOST", error instanceof Error ? error.message : String(error));
|
|
1655
|
+
}
|
|
1656
|
+
const [section] = WebAssembly.Module.customSections(module, HOST_SECTION);
|
|
1657
|
+
if (!section)
|
|
1658
|
+
throw sceneError("SCENE_HOST", "the module has no moveby.host section");
|
|
1659
|
+
const table = readHostTable(new Uint8Array(section));
|
|
1660
|
+
const plan = checkScene(table);
|
|
1661
|
+
const records = bindAssets(plan.assets, inputs.assets);
|
|
1662
|
+
const using = usingValues(table.using, inputs.using);
|
|
1663
|
+
const { exports } = await WebAssembly.instantiate(module, {});
|
|
1664
|
+
const scene = exports;
|
|
1665
|
+
if (!(scene.$memory instanceof WebAssembly.Memory) || typeof scene.$init !== "function" || typeof scene.$fill !== "function" || typeof scene.$reset !== "function") {
|
|
1666
|
+
throw sceneError("SCENE_HOST", "the module does not export $memory, $init, $fill and $reset");
|
|
1667
|
+
}
|
|
1668
|
+
const { byteLength } = scene.$memory.buffer;
|
|
1669
|
+
if (table.outOffset % 4 !== 0 || table.outOffset + 4 * table.leaves.length > byteLength) {
|
|
1670
|
+
throw sceneError("SCENE_HOST", `out[] is not inside the module's memory: it starts at byte ${table.outOffset} of ${byteLength}`);
|
|
1671
|
+
}
|
|
1672
|
+
scene.$init(...using);
|
|
1673
|
+
const words = new Float32Array(scene.$memory.buffer);
|
|
1674
|
+
const { Engine, Rows } = await engineReady();
|
|
1675
|
+
const rows = new Rows;
|
|
1676
|
+
for (const record of records)
|
|
1677
|
+
rows.asset(record.cell, record.cols, record.rows);
|
|
1678
|
+
for (const object of plan.objects)
|
|
1679
|
+
rows.image(words[object.assetSlot]);
|
|
1680
|
+
for (const label of plan.labels)
|
|
1681
|
+
rows.text(label.text);
|
|
1682
|
+
const outside = Engine.first_asset_outside_grid(trackBytes, rows);
|
|
1683
|
+
if (outside >= 0) {
|
|
1684
|
+
const record = records[outside];
|
|
1685
|
+
throw sceneError("SCENE_ASSET", `${record.name}: cell ${record.cell} with a block of ${record.cols} × ${record.rows} is outside the track's atlas`);
|
|
1686
|
+
}
|
|
1687
|
+
const engine = Engine.from_config_bytes_with_rows(trackBytes, rows);
|
|
1688
|
+
const out = new Float32Array(scene.$memory.buffer, table.outOffset, table.leaves.length);
|
|
1689
|
+
return new Track(engine, scene, table, plan, records, out);
|
|
1690
|
+
}
|
|
1691
|
+
function typeLines(node, depth) {
|
|
1692
|
+
const indent = " ".repeat(depth);
|
|
1693
|
+
return Object.entries(node).flatMap(([key, part]) => part === null ? [`${indent}${key}: number;`] : [`${indent}${key}: {`, ...typeLines(part, depth + 1), `${indent}};`]);
|
|
1694
|
+
}
|
|
1695
|
+
function interfaceBody(paths) {
|
|
1696
|
+
const root = {};
|
|
1697
|
+
for (const path of paths) {
|
|
1698
|
+
const keys = path.split(".");
|
|
1699
|
+
let node = root;
|
|
1700
|
+
for (const key of keys.slice(0, -1)) {
|
|
1701
|
+
node[key] ??= {};
|
|
1702
|
+
node = node[key];
|
|
1703
|
+
}
|
|
1704
|
+
node[keys[keys.length - 1]] = null;
|
|
1705
|
+
}
|
|
1706
|
+
return typeLines(root, 1);
|
|
1707
|
+
}
|
|
1708
|
+
function trackTypes(table) {
|
|
1709
|
+
const using = table.using.filter((path) => !path.startsWith(ASSET_GROUP));
|
|
1710
|
+
return [
|
|
1711
|
+
"// Generated by moveby from the scene module. Do not edit: build the scene again.",
|
|
1712
|
+
"",
|
|
1713
|
+
"/** The dynamic inputs, one number each per frame: `scene.draw(dynamic)`. */",
|
|
1714
|
+
"export interface SceneDynamic {",
|
|
1715
|
+
...interfaceBody(table.dynamic),
|
|
1716
|
+
"}",
|
|
1717
|
+
"",
|
|
1718
|
+
"/** The using inputs the page gives once: `loadTrack(trackBytes, sceneBytes, { using })`. An asset is not among them: `asset()` declares it. */",
|
|
1719
|
+
"export interface SceneUsing {",
|
|
1720
|
+
...interfaceBody(using),
|
|
1721
|
+
"}",
|
|
1722
|
+
""
|
|
1723
|
+
].join(`
|
|
1724
|
+
`);
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
// ../engine-binding/src/scene.ts
|
|
1728
|
+
function backdrop({
|
|
1729
|
+
ground = [0, 0, 0],
|
|
1730
|
+
sky: skyColor = [1, 1, 1]
|
|
1731
|
+
} = {}) {
|
|
1732
|
+
return { kind: "backdrop", ground, sky: skyColor };
|
|
1733
|
+
}
|
|
1734
|
+
function road2() {
|
|
1735
|
+
return { kind: "road" };
|
|
1736
|
+
}
|
|
1737
|
+
function field2(inputs) {
|
|
1738
|
+
return { kind: "field", ...inputs };
|
|
1739
|
+
}
|
|
1740
|
+
function sky2() {
|
|
1741
|
+
return { kind: "sky" };
|
|
1742
|
+
}
|
|
1743
|
+
function scenery2({ atlas }) {
|
|
1744
|
+
return { kind: "scenery", atlas };
|
|
1745
|
+
}
|
|
1746
|
+
function text2({ atlas }) {
|
|
1747
|
+
return { kind: "text", atlas };
|
|
1748
|
+
}
|
|
1749
|
+
var SCENE_ERRORS = {
|
|
1750
|
+
LAYER_DUPLICATE: "The scene lists the same layer twice.",
|
|
1751
|
+
LAYER_UNLISTED: "The track declares a layer that the scene does not list.",
|
|
1752
|
+
LAYER_MISSING: "The scene lists a layer that the track does not declare.",
|
|
1753
|
+
WEBGL_UNSUPPORTED: "This browser gave no WebGL context for the canvas.",
|
|
1754
|
+
SCENE_NO_TRACK: "This scene draws an engine the page moves itself, so it takes no dynamic inputs: scene.draw({ … }) needs a track from loadTrack.",
|
|
1755
|
+
SCENE_ATLAS: "An atlas the scene names as a URL could not be fetched or decoded."
|
|
1756
|
+
};
|
|
1757
|
+
var ERROR_MESSAGES = {
|
|
1758
|
+
...CORE_ERRORS,
|
|
1759
|
+
...SCENE_ERRORS,
|
|
1760
|
+
...ROAD_ERRORS,
|
|
1761
|
+
...FIELD_ERRORS,
|
|
1762
|
+
...SCENERY_ERRORS,
|
|
1763
|
+
...TEXT_ERRORS,
|
|
1764
|
+
...SCENE_MODULE_ERRORS
|
|
1765
|
+
};
|
|
1766
|
+
function sceneError2(code, detail) {
|
|
1767
|
+
return new MovebyError(code, `${SCENE_ERRORS[code]} (${detail})`);
|
|
1768
|
+
}
|
|
1769
|
+
function listByKind(layers) {
|
|
1770
|
+
const listed = {};
|
|
1771
|
+
for (const layer of layers) {
|
|
1772
|
+
if (listed[layer.kind])
|
|
1773
|
+
throw sceneError2("LAYER_DUPLICATE", `${layer.kind}()`);
|
|
1774
|
+
listed[layer.kind] = layer;
|
|
1775
|
+
}
|
|
1776
|
+
return listed;
|
|
1777
|
+
}
|
|
1778
|
+
var ROUTE_TAG = 1;
|
|
1779
|
+
var SECTION_LAYER = { 2: "road", 3: "field", 4: "scenery", 5: "text" };
|
|
1780
|
+
function checkDeclared(listed, declared) {
|
|
1781
|
+
for (const tag of declared) {
|
|
1782
|
+
if (tag === ROUTE_TAG)
|
|
1783
|
+
continue;
|
|
1784
|
+
const kind = SECTION_LAYER[tag];
|
|
1785
|
+
if (!kind || !listed[kind]) {
|
|
1786
|
+
throw sceneError2("LAYER_UNLISTED", kind ? `list ${kind}()` : `unknown section ${tag}`);
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
for (const [tag, kind] of Object.entries(SECTION_LAYER)) {
|
|
1790
|
+
if (kind !== "road" && listed[kind] && !declared.includes(Number(tag))) {
|
|
1791
|
+
throw sceneError2("LAYER_MISSING", `${kind}()`);
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
function imageError(code, message, detail) {
|
|
1796
|
+
return new MovebyError(code, `${message} (${detail})`);
|
|
1797
|
+
}
|
|
1798
|
+
function checkImages(listed) {
|
|
1799
|
+
const { field: ground, scenery: sprites, text: labels } = listed;
|
|
1800
|
+
if (ground && !ground.atlas && Object.keys(ground.textures ?? {}).length === 0) {
|
|
1801
|
+
throw imageError("FIELD_IMAGE_MISSING", FIELD_ERRORS.FIELD_IMAGE_MISSING, "field() needs atlas or textures");
|
|
1802
|
+
}
|
|
1803
|
+
if (sprites && !sprites.atlas) {
|
|
1804
|
+
throw imageError("SCENERY_IMAGE_MISSING", SCENERY_ERRORS.SCENERY_IMAGE_MISSING, "scenery() needs atlas");
|
|
1805
|
+
}
|
|
1806
|
+
if (labels && !labels.atlas) {
|
|
1807
|
+
throw imageError("TEXT_IMAGE_MISSING", TEXT_ERRORS.TEXT_IMAGE_MISSING, "text() needs atlas");
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
class LayeredScene {
|
|
1812
|
+
gl;
|
|
1813
|
+
engine;
|
|
1814
|
+
track;
|
|
1815
|
+
backdrop = null;
|
|
1816
|
+
road = null;
|
|
1817
|
+
field = null;
|
|
1818
|
+
sky = null;
|
|
1819
|
+
scenery = null;
|
|
1820
|
+
text = null;
|
|
1821
|
+
camera;
|
|
1822
|
+
ready;
|
|
1823
|
+
constructor(gl, engine, listed, track) {
|
|
1824
|
+
this.gl = gl;
|
|
1825
|
+
this.engine = engine;
|
|
1826
|
+
this.track = track;
|
|
1827
|
+
this.camera = new CameraViews(engine);
|
|
1828
|
+
const late = [];
|
|
1829
|
+
if (listed.backdrop) {
|
|
1830
|
+
this.backdrop = new BackdropPass(gl, listed.backdrop.ground, listed.backdrop.sky);
|
|
1831
|
+
}
|
|
1832
|
+
if (listed.road)
|
|
1833
|
+
this.road = new RoadPass(gl, engine);
|
|
1834
|
+
if (listed.sky)
|
|
1835
|
+
this.sky = new SkyPass(gl);
|
|
1836
|
+
if (listed.field) {
|
|
1837
|
+
const field3 = new FieldPass(gl, engine);
|
|
1838
|
+
this.field = field3;
|
|
1839
|
+
const atlas = listed.field.atlas;
|
|
1840
|
+
if (typeof atlas === "string") {
|
|
1841
|
+
late.push(this.lateAtlas(atlas, (bitmap) => field3.setFieldAtlas(bitmap)));
|
|
1842
|
+
} else if (atlas !== undefined) {
|
|
1843
|
+
field3.setFieldAtlas(atlas);
|
|
1844
|
+
}
|
|
1845
|
+
for (const [id, tile] of Object.entries(listed.field.textures ?? {})) {
|
|
1846
|
+
field3.setFieldTexture(Number(id), tile);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
if (listed.scenery) {
|
|
1850
|
+
const scenery3 = new SceneryPass(gl, engine);
|
|
1851
|
+
this.scenery = scenery3;
|
|
1852
|
+
const atlas = listed.scenery.atlas;
|
|
1853
|
+
if (typeof atlas === "string") {
|
|
1854
|
+
late.push(this.lateAtlas(atlas, (bitmap) => scenery3.setSceneryAtlas(bitmap)));
|
|
1855
|
+
} else {
|
|
1856
|
+
scenery3.setSceneryAtlas(atlas);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
if (listed.text) {
|
|
1860
|
+
const text3 = new TextPass(gl, engine);
|
|
1861
|
+
this.text = text3;
|
|
1862
|
+
const atlas = listed.text.atlas;
|
|
1863
|
+
if (typeof atlas === "string") {
|
|
1864
|
+
late.push(this.lateAtlas(atlas, (bitmap) => text3.setTextAtlas(bitmap)));
|
|
1865
|
+
} else {
|
|
1866
|
+
text3.setTextAtlas(atlas);
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
this.ready = Promise.all(late).then(() => {
|
|
1870
|
+
return;
|
|
1871
|
+
});
|
|
1872
|
+
}
|
|
1873
|
+
lateAtlas(url, upload) {
|
|
1874
|
+
return decodeAtlas(url).then(upload, (reason) => {
|
|
1875
|
+
throw sceneError2("SCENE_ATLAS", `${url}: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
1876
|
+
});
|
|
1877
|
+
}
|
|
1878
|
+
draw(dynamic) {
|
|
1879
|
+
const { gl, engine } = this;
|
|
1880
|
+
const canvas = gl.canvas;
|
|
1881
|
+
if (dynamic !== undefined) {
|
|
1882
|
+
if (!this.track)
|
|
1883
|
+
throw sceneError2("SCENE_NO_TRACK", "scene.draw");
|
|
1884
|
+
this.track.draw(dynamic);
|
|
1885
|
+
}
|
|
1886
|
+
if (canvas.width !== canvas.clientWidth || canvas.height !== canvas.clientHeight) {
|
|
1887
|
+
canvas.width = canvas.clientWidth;
|
|
1888
|
+
canvas.height = canvas.clientHeight;
|
|
1889
|
+
}
|
|
1890
|
+
engine.set_aspect(canvas.width / canvas.height);
|
|
1891
|
+
gl.viewport(0, 0, canvas.width, canvas.height);
|
|
1892
|
+
const horizonRow = Math.max(0, Math.min(canvas.height, Math.round((engine.horizon_ndc_y() + 1) / 2 * canvas.height)));
|
|
1893
|
+
if (this.backdrop)
|
|
1894
|
+
this.backdrop.clearToGround();
|
|
1895
|
+
else
|
|
1896
|
+
gl.clear(gl.DEPTH_BUFFER_BIT);
|
|
1897
|
+
gl.enable(gl.DEPTH_TEST);
|
|
1898
|
+
gl.depthFunc(gl.LEQUAL);
|
|
1899
|
+
engine.fill_camera();
|
|
1900
|
+
this.road?.draw(this.camera);
|
|
1901
|
+
this.field?.draw(this.camera);
|
|
1902
|
+
this.backdrop?.fillSky(horizonRow, canvas.width, canvas.height);
|
|
1903
|
+
this.sky?.draw(engine, horizonRow, canvas.width, canvas.height);
|
|
1904
|
+
this.scenery?.draw(this.camera);
|
|
1905
|
+
this.text?.draw();
|
|
1906
|
+
}
|
|
1907
|
+
reset() {
|
|
1908
|
+
this.track?.reset();
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
function createScene(canvas, source, layers) {
|
|
1912
|
+
const track = source instanceof Track ? source : null;
|
|
1913
|
+
const engine = source instanceof Track ? source.engine : source;
|
|
1914
|
+
const listed = listByKind(layers);
|
|
1915
|
+
checkDeclared(listed, engine.layers());
|
|
1916
|
+
checkImages(listed);
|
|
1917
|
+
const gl = canvas.getContext("webgl", { alpha: false });
|
|
1918
|
+
if (!gl)
|
|
1919
|
+
throw sceneError2("WEBGL_UNSUPPORTED", "getContext('webgl')");
|
|
1920
|
+
return new LayeredScene(gl, engine, listed, track);
|
|
1921
|
+
}
|
|
1922
|
+
export {
|
|
1923
|
+
trackTypes,
|
|
1924
|
+
text2 as text,
|
|
1925
|
+
sky2 as sky,
|
|
1926
|
+
scenery2 as scenery,
|
|
1927
|
+
road2 as road,
|
|
1928
|
+
loadTrack,
|
|
1929
|
+
field2 as field,
|
|
1930
|
+
createScene,
|
|
1931
|
+
backdrop,
|
|
1932
|
+
asset,
|
|
1933
|
+
TEXT_ERRORS,
|
|
1934
|
+
SCENE_MODULE_ERRORS,
|
|
1935
|
+
SCENE_ERRORS,
|
|
1936
|
+
SCENERY_ERRORS,
|
|
1937
|
+
ROAD_ERRORS,
|
|
1938
|
+
MovebyError,
|
|
1939
|
+
FIELD_ERRORS,
|
|
1940
|
+
ERROR_MESSAGES,
|
|
1941
|
+
CORE_ERRORS
|
|
1942
|
+
};
|