@geastack/gea3d 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,520 @@
1
+ // SPDX-License-Identifier: GPL-3.0-only
2
+ import { Display, rgb } from '@geastack/core'
3
+
4
+ // Flat-shaded fixed-function pipeline over preallocated typed arrays.
5
+ // View space follows the three.js convention: camera at the origin looking
6
+ // down -Z, right-handed, CCW front faces. Matrices are column-major
7
+ // Float32Array(16) (three.js element order).
8
+ //
9
+ // Depth ordering is painter's (no z-buffer exists in the gea runtime): view
10
+ // depth is bucket-sorted and triangles are emitted back-to-front.
11
+
12
+ export const SHADE_UNLIT = 0
13
+ export const SHADE_LAMBERT = 1
14
+ export const SHADE_NORMAL = 2
15
+
16
+ const MAX_DIR_LIGHTS = 4
17
+ const DEPTH_BUCKETS = 1024
18
+ const COORD_LIMIT = 30000
19
+
20
+ // Emission goes straight to Display.ctx (fetched as a local per frame — the
21
+ // proven canvas-3d pattern). A presenter abstraction (class or interface
22
+ // field) boxes or miscompiles in embedded geatsc today; the Phase-3 native
23
+ // backend swaps the emit loop in endFrame instead.
24
+ export class RasterPipeline {
25
+ readonly capacity: number
26
+
27
+ // Emitted-triangle store (SoA)
28
+ private readonly outX0: Int32Array
29
+ private readonly outY0: Int32Array
30
+ private readonly outX1: Int32Array
31
+ private readonly outY1: Int32Array
32
+ private readonly outX2: Int32Array
33
+ private readonly outY2: Int32Array
34
+ private readonly outDepth: Float32Array
35
+ private readonly outColor: Uint32Array
36
+ private outCount = 0
37
+ droppedTriangles = 0
38
+ // Diagnostic gate counters (reset per frame)
39
+ statSubmitted = 0
40
+ statNearRejected = 0
41
+ statCulled = 0
42
+ statClipDropped = 0
43
+ // TEMP MEASUREMENT (gea3d phase split): remove after profiling.
44
+ perfSortMs = 0
45
+ perfEmitMs = 0
46
+ perfPresentMs = 0
47
+
48
+ // Sort scratch
49
+ private readonly sortKeys: Int32Array
50
+ private readonly sortOrder: Int32Array
51
+ private readonly bucketStarts: Int32Array
52
+
53
+ // Frame state
54
+ private viewportW = 0
55
+ private viewportH = 0
56
+ private near: f32 = 0.1
57
+ private readonly proj: Float32Array
58
+
59
+ // Lights (view space, normalized "toward the light" directions)
60
+ private ambientR: f32 = 1
61
+ private ambientG: f32 = 1
62
+ private ambientB: f32 = 1
63
+ private dirCount = 0
64
+ private readonly dirX: Float32Array
65
+ private readonly dirY: Float32Array
66
+ private readonly dirZ: Float32Array
67
+ private readonly dirR: Float32Array
68
+ private readonly dirG: Float32Array
69
+ private readonly dirB: Float32Array
70
+
71
+ // Near-clip scratch: a triangle clipped against one plane yields <= 4 verts.
72
+ private readonly clipX: Float32Array
73
+ private readonly clipY: Float32Array
74
+ private readonly clipZ: Float32Array
75
+
76
+ // Default matches GeaRenderer's own default triangleCapacity. A real
77
+ // literal default (not "no default") matters for embedded-geatsc: this
78
+ // field is assigned in GeaRenderer's constructor BODY, not its
79
+ // initializer list, so the emitter member-initializes it via a
80
+ // placeholder default construction before the body reassigns it. With no
81
+ // TS default here, the emitter synthesizes an unsafe `gea_cpp_value::
82
+ // missing()` param default for that placeholder call — missing() coerces
83
+ // to NaN, and `static_cast<size_t>(NaN)` silently truncates to 0 under
84
+ // emscripten (harmless empty vectors, invisible in the WASM sim) but is
85
+ // UB on xtensa: it aliased a garbage huge size_t, blew std::vector's
86
+ // max_size() check, and hard-aborted at boot (exceptions are disabled on
87
+ // this embedded target, so the throw becomes an immediate abort()). A
88
+ // real numeric default here removes the need for any unsafe stand-in.
89
+ constructor(capacity: number = 4096) {
90
+ // Hoist to a plain local before typed-array allocation: constructor
91
+ // params arrive boxed in embedded geatsc, and `new Int32Array(<boxed>)`
92
+ // takes the from-value path and throws.
93
+ const cap = capacity < 1 ? 1 : Math.floor(capacity)
94
+ this.capacity = cap
95
+ this.outX0 = new Int32Array(cap)
96
+ this.outY0 = new Int32Array(cap)
97
+ this.outX1 = new Int32Array(cap)
98
+ this.outY1 = new Int32Array(cap)
99
+ this.outX2 = new Int32Array(cap)
100
+ this.outY2 = new Int32Array(cap)
101
+ this.outDepth = new Float32Array(cap)
102
+ this.outColor = new Uint32Array(cap)
103
+ this.sortKeys = new Int32Array(cap)
104
+ this.sortOrder = new Int32Array(cap)
105
+ this.bucketStarts = new Int32Array(DEPTH_BUCKETS + 1)
106
+ this.proj = new Float32Array(16)
107
+ this.dirX = new Float32Array(MAX_DIR_LIGHTS)
108
+ this.dirY = new Float32Array(MAX_DIR_LIGHTS)
109
+ this.dirZ = new Float32Array(MAX_DIR_LIGHTS)
110
+ this.dirR = new Float32Array(MAX_DIR_LIGHTS)
111
+ this.dirG = new Float32Array(MAX_DIR_LIGHTS)
112
+ this.dirB = new Float32Array(MAX_DIR_LIGHTS)
113
+ this.clipX = new Float32Array(4)
114
+ this.clipY = new Float32Array(4)
115
+ this.clipZ = new Float32Array(4)
116
+ }
117
+
118
+ beginFrame(viewportW: number, viewportH: number, projection: Float32Array, near: f32): void {
119
+ this.viewportW = viewportW
120
+ this.viewportH = viewportH
121
+ this.near = near < 0.0001 ? (0.0001 as f32) : near
122
+ for (let i = 0; i < 16; i++) this.proj[i] = projection[i]
123
+ this.outCount = 0
124
+ this.droppedTriangles = 0
125
+ this.statSubmitted = 0
126
+ this.statNearRejected = 0
127
+ this.statCulled = 0
128
+ this.statClipDropped = 0
129
+ this.dirCount = 0
130
+ this.ambientR = 0
131
+ this.ambientG = 0
132
+ this.ambientB = 0
133
+ }
134
+
135
+ // Ambient accumulates (several AmbientLights sum, like three.js).
136
+ addAmbient(r: f32, g: f32, b: f32): void {
137
+ this.ambientR = (this.ambientR + r) as f32
138
+ this.ambientG = (this.ambientG + g) as f32
139
+ this.ambientB = (this.ambientB + b) as f32
140
+ }
141
+
142
+ // dir = vector pointing TOWARD the light, in view space.
143
+ addDirectionalLight(x: f32, y: f32, z: f32, r: f32, g: f32, b: f32): void {
144
+ if (this.dirCount >= MAX_DIR_LIGHTS) return
145
+ const lenSq: f32 = (x * x + y * y + z * z) as f32
146
+ if (lenSq <= 0) return
147
+ const inv: f32 = (1 / Math.sqrt(lenSq)) as f32
148
+ const i = this.dirCount
149
+ this.dirX[i] = x * inv
150
+ this.dirY[i] = y * inv
151
+ this.dirZ[i] = z * inv
152
+ this.dirR[i] = r
153
+ this.dirG[i] = g
154
+ this.dirB[i] = b
155
+ this.dirCount = i + 1
156
+ }
157
+
158
+ // positions: packed xyz Float32Array. indices: 3 per triangle (Uint32Array).
159
+ // modelView: column-major Float32Array(16). base*: material color 0..255.
160
+ // colors: per-vertex rgb (0..1, packed like positions) modulating the base
161
+ // color per face (averaged — flat shading); pass an EMPTY array to disable
162
+ // (a `Float32Array | null` union would box to gea_cpp_value).
163
+ drawTriangles(
164
+ positions: Float32Array,
165
+ indices: Uint32Array,
166
+ triangleCount: number,
167
+ modelView: Float32Array,
168
+ shadeMode: number,
169
+ baseR: number,
170
+ baseG: number,
171
+ baseB: number,
172
+ colors: Float32Array,
173
+ doubleSide: boolean,
174
+ ): void {
175
+ const m0: f32 = modelView[0] as f32
176
+ const m1: f32 = modelView[1] as f32
177
+ const m2: f32 = modelView[2] as f32
178
+ const m4: f32 = modelView[4] as f32
179
+ const m5: f32 = modelView[5] as f32
180
+ const m6: f32 = modelView[6] as f32
181
+ const m8: f32 = modelView[8] as f32
182
+ const m9: f32 = modelView[9] as f32
183
+ const m10: f32 = modelView[10] as f32
184
+ const m12: f32 = modelView[12] as f32
185
+ const m13: f32 = modelView[13] as f32
186
+ const m14: f32 = modelView[14] as f32
187
+
188
+ const nearZ: f32 = (-this.near) as f32
189
+ const hasColors = colors.length > 0
190
+
191
+ this.statSubmitted += triangleCount
192
+ for (let t = 0; t < triangleCount; t++) {
193
+ const i0 = indices[t * 3] * 3
194
+ const i1 = indices[t * 3 + 1] * 3
195
+ const i2 = indices[t * 3 + 2] * 3
196
+
197
+ const p0x: f32 = positions[i0] as f32
198
+ const p0y: f32 = positions[i0 + 1] as f32
199
+ const p0z: f32 = positions[i0 + 2] as f32
200
+ const p1x: f32 = positions[i1] as f32
201
+ const p1y: f32 = positions[i1 + 1] as f32
202
+ const p1z: f32 = positions[i1 + 2] as f32
203
+ const p2x: f32 = positions[i2] as f32
204
+ const p2y: f32 = positions[i2 + 1] as f32
205
+ const p2z: f32 = positions[i2 + 2] as f32
206
+
207
+ // To view space
208
+ const v0x: f32 = (m0 * p0x + m4 * p0y + m8 * p0z + m12) as f32
209
+ const v0y: f32 = (m1 * p0x + m5 * p0y + m9 * p0z + m13) as f32
210
+ const v0z: f32 = (m2 * p0x + m6 * p0y + m10 * p0z + m14) as f32
211
+ const v1x: f32 = (m0 * p1x + m4 * p1y + m8 * p1z + m12) as f32
212
+ const v1y: f32 = (m1 * p1x + m5 * p1y + m9 * p1z + m13) as f32
213
+ const v1z: f32 = (m2 * p1x + m6 * p1y + m10 * p1z + m14) as f32
214
+ const v2x: f32 = (m0 * p2x + m4 * p2y + m8 * p2z + m12) as f32
215
+ const v2y: f32 = (m1 * p2x + m5 * p2y + m9 * p2z + m13) as f32
216
+ const v2z: f32 = (m2 * p2x + m6 * p2y + m10 * p2z + m14) as f32
217
+
218
+ // Trivial reject: fully behind the near plane
219
+ if (v0z > nearZ && v1z > nearZ && v2z > nearZ) {
220
+ this.statNearRejected++
221
+ continue
222
+ }
223
+
224
+ // Face normal (view space, unnormalized)
225
+ const e1x: f32 = (v1x - v0x) as f32
226
+ const e1y: f32 = (v1y - v0y) as f32
227
+ const e1z: f32 = (v1z - v0z) as f32
228
+ const e2x: f32 = (v2x - v0x) as f32
229
+ const e2y: f32 = (v2y - v0y) as f32
230
+ const e2z: f32 = (v2z - v0z) as f32
231
+ let nx: f32 = (e1y * e2z - e1z * e2y) as f32
232
+ let ny: f32 = (e1z * e2x - e1x * e2z) as f32
233
+ let nz: f32 = (e1x * e2y - e1y * e2x) as f32
234
+
235
+ // Backface cull against the view vector to the face (camera at origin).
236
+ // CCW front faces have normals pointing toward the camera: dot < 0.
237
+ const viewDot: f32 = (nx * v0x + ny * v0y + nz * v0z) as f32
238
+ if (viewDot >= 0) {
239
+ if (!doubleSide) {
240
+ this.statCulled++
241
+ continue
242
+ }
243
+ nx = (-nx) as f32
244
+ ny = (-ny) as f32
245
+ nz = (-nz) as f32
246
+ }
247
+
248
+ // Face color
249
+ let fr: f32 = baseR as f32
250
+ let fg: f32 = baseG as f32
251
+ let fb: f32 = baseB as f32
252
+ if (hasColors) {
253
+ const cr: f32 = ((colors[i0] + colors[i1] + colors[i2]) * 0.33333334) as f32
254
+ const cg: f32 = ((colors[i0 + 1] + colors[i1 + 1] + colors[i2 + 1]) * 0.33333334) as f32
255
+ const cb: f32 = ((colors[i0 + 2] + colors[i1 + 2] + colors[i2 + 2]) * 0.33333334) as f32
256
+ fr = (fr * cr) as f32
257
+ fg = (fg * cg) as f32
258
+ fb = (fb * cb) as f32
259
+ }
260
+
261
+ if (shadeMode === SHADE_LAMBERT) {
262
+ const nLenSq: f32 = (nx * nx + ny * ny + nz * nz) as f32
263
+ if (nLenSq > 0) {
264
+ const nInv: f32 = (1 / Math.sqrt(nLenSq)) as f32
265
+ const ux: f32 = (nx * nInv) as f32
266
+ const uy: f32 = (ny * nInv) as f32
267
+ const uz: f32 = (nz * nInv) as f32
268
+ let lr: f32 = this.ambientR
269
+ let lg: f32 = this.ambientG
270
+ let lb: f32 = this.ambientB
271
+ for (let li = 0; li < this.dirCount; li++) {
272
+ const lx: f32 = this.dirX[li] as f32
273
+ const ly: f32 = this.dirY[li] as f32
274
+ const lz: f32 = this.dirZ[li] as f32
275
+ const d: f32 = (ux * lx + uy * ly + uz * lz) as f32
276
+ if (d > 0) {
277
+ const cr: f32 = this.dirR[li] as f32
278
+ const cg: f32 = this.dirG[li] as f32
279
+ const cb: f32 = this.dirB[li] as f32
280
+ lr = (lr + d * cr) as f32
281
+ lg = (lg + d * cg) as f32
282
+ lb = (lb + d * cb) as f32
283
+ }
284
+ }
285
+ fr = (fr * lr) as f32
286
+ fg = (fg * lg) as f32
287
+ fb = (fb * lb) as f32
288
+ }
289
+ } else if (shadeMode === SHADE_NORMAL) {
290
+ const nLenSq: f32 = (nx * nx + ny * ny + nz * nz) as f32
291
+ if (nLenSq > 0) {
292
+ const nInv: f32 = (1 / Math.sqrt(nLenSq)) as f32
293
+ fr = ((nx * nInv * 0.5 + 0.5) * 255) as f32
294
+ fg = ((ny * nInv * 0.5 + 0.5) * 255) as f32
295
+ fb = ((-nz * nInv * 0.5 + 0.5) * 255) as f32
296
+ }
297
+ }
298
+
299
+ let ir = Math.floor(fr)
300
+ let ig = Math.floor(fg)
301
+ let ib = Math.floor(fb)
302
+ if (ir < 0) ir = 0
303
+ if (ir > 255) ir = 255
304
+ if (ig < 0) ig = 0
305
+ if (ig > 255) ig = 255
306
+ if (ib < 0) ib = 0
307
+ if (ib > 255) ib = 255
308
+ const pixel = rgb(ir, ig, ib)
309
+
310
+ // Near-plane clip (keep z <= -near). Builds a 3- or 4-gon.
311
+ const cx = this.clipX
312
+ const cy = this.clipY
313
+ const cz = this.clipZ
314
+ let clipCount = 0
315
+ // Unrolled edge walk v0->v1->v2->v0
316
+ let ax: f32 = v0x
317
+ let ay: f32 = v0y
318
+ let az: f32 = v0z
319
+ let bx: f32 = v1x
320
+ let by: f32 = v1y
321
+ let bz: f32 = v1z
322
+ for (let e = 0; e < 3; e++) {
323
+ const aIn = az <= nearZ
324
+ const bIn = bz <= nearZ
325
+ if (aIn) {
326
+ cx[clipCount] = ax
327
+ cy[clipCount] = ay
328
+ cz[clipCount] = az
329
+ clipCount++
330
+ }
331
+ if (aIn !== bIn) {
332
+ const tt: f32 = ((nearZ - az) / (bz - az)) as f32
333
+ cx[clipCount] = (ax + (bx - ax) * tt) as f32
334
+ cy[clipCount] = (ay + (by - ay) * tt) as f32
335
+ cz[clipCount] = nearZ
336
+ clipCount++
337
+ }
338
+ ax = bx
339
+ ay = by
340
+ az = bz
341
+ if (e === 0) {
342
+ bx = v2x
343
+ by = v2y
344
+ bz = v2z
345
+ } else {
346
+ bx = v0x
347
+ by = v0y
348
+ bz = v0z
349
+ }
350
+ }
351
+ if (clipCount < 3) {
352
+ this.statClipDropped++
353
+ continue
354
+ }
355
+
356
+ // Project the clipped polygon and fan-emit triangles.
357
+ const p = this.proj
358
+ const p0: f32 = p[0] as f32
359
+ const p1: f32 = p[1] as f32
360
+ const p3: f32 = p[3] as f32
361
+ const p4: f32 = p[4] as f32
362
+ const p5: f32 = p[5] as f32
363
+ const p7: f32 = p[7] as f32
364
+ const p8: f32 = p[8] as f32
365
+ const p9: f32 = p[9] as f32
366
+ const p11: f32 = p[11] as f32
367
+ const p12: f32 = p[12] as f32
368
+ const p13: f32 = p[13] as f32
369
+ const p15: f32 = p[15] as f32
370
+ const halfW: f32 = (this.viewportW * 0.5) as f32
371
+ const halfH: f32 = (this.viewportH * 0.5) as f32
372
+ let sx0 = 0
373
+ let sy0 = 0
374
+ let prevX = 0
375
+ let prevY = 0
376
+ // Face sort depth = FARTHEST vertex (Newell's primary key), not the
377
+ // centroid. A large face (a ground plane) spans a wide depth range; its
378
+ // centroid depth sorts it in front of geometry that is beyond the
379
+ // centroid but above the plane, so the plane overdraws it (a floor-
380
+ // colored bite in the torus at the exact screen band where mesh depth
381
+ // crosses the floor's centroid depth). Farthest-vertex sorting draws a
382
+ // ground plane before everything above it — correct for any camera on
383
+ // the visible side — and matches the centroid within a facet's depth
384
+ // span for small compact faces.
385
+ //
386
+ // Computed up front over the clipped vertices (<= 4) so each fan
387
+ // triangle is depth-stamped as it is emitted — single pass, no
388
+ // post-stamp loop over [fanStart, outCount) (that counter's non-literal
389
+ // init resisted int narrowing and ran on soft-double indices on xtensa).
390
+ let depthFar: f32 = cz[0] as f32
391
+ for (let q = 1; q < clipCount; q++) {
392
+ const vq: f32 = cz[q] as f32
393
+ if (vq < depthFar) depthFar = vq
394
+ }
395
+ for (let k = 0; k < clipCount; k++) {
396
+ const vx: f32 = cx[k] as f32
397
+ const vy: f32 = cy[k] as f32
398
+ const vz: f32 = cz[k] as f32
399
+ const clipXk: f32 = (p0 * vx + p4 * vy + p8 * vz + p12) as f32
400
+ const clipYk: f32 = (p1 * vx + p5 * vy + p9 * vz + p13) as f32
401
+ let clipW: f32 = (p3 * vx + p7 * vy + p11 * vz + p15) as f32
402
+ if (clipW < 0.000001 && clipW > -0.000001) clipW = 0.000001 as f32
403
+ const invW: f32 = (1 / clipW) as f32
404
+ let fx: f32 = ((clipXk * invW + 1) * halfW) as f32
405
+ let fy: f32 = ((1 - clipYk * invW) * halfH) as f32
406
+ if (fx < -COORD_LIMIT) fx = -COORD_LIMIT as f32
407
+ if (fx > COORD_LIMIT) fx = COORD_LIMIT as f32
408
+ if (fy < -COORD_LIMIT) fy = -COORD_LIMIT as f32
409
+ if (fy > COORD_LIMIT) fy = COORD_LIMIT as f32
410
+ const sx = Math.floor(fx)
411
+ const sy = Math.floor(fy)
412
+ if (k === 0) {
413
+ sx0 = sx
414
+ sy0 = sy
415
+ } else if (k >= 2) {
416
+ if (this.outCount >= this.capacity) {
417
+ this.droppedTriangles++
418
+ } else {
419
+ const o = this.outCount
420
+ this.outX0[o] = sx0
421
+ this.outY0[o] = sy0
422
+ this.outX1[o] = prevX
423
+ this.outY1[o] = prevY
424
+ this.outX2[o] = sx
425
+ this.outY2[o] = sy
426
+ this.outColor[o] = pixel
427
+ // One depth per source triangle: farthest clipped vertex. All
428
+ // fan triangles share it (one plane-coherent face).
429
+ this.outDepth[o] = depthFar
430
+ this.outCount = o + 1
431
+ }
432
+ }
433
+ prevX = sx
434
+ prevY = sy
435
+ }
436
+ }
437
+ }
438
+
439
+ // Sort back-to-front and emit to the presenter, wrapped in ONE batch on ONE
440
+ // ctx instance. The batch/recording state (batchDepth_, presentCommands_)
441
+ // lives on the CanvasRenderingContext2D VALUE HANDLE, not in shared storage:
442
+ // when the renderer bracketed beginBatch()/endBatch() on ITS ctx and this
443
+ // method fetched Display.ctx AGAIN, the second instance saw batchDepth_=0,
444
+ // recording was off, and every fillTriangleRgb565 rasterized IMMEDIATELY
445
+ // into the PSRAM framebuffer (~83us each, 30ms/frame) while the recorded
446
+ // present frame carried only the background rect — the present path then
447
+ // flushed background-only bands over the JSX-flushed triangles (the
448
+ // inter-frame black flashing). The background fill lives here too so the
449
+ // recorded frame keeps its full-screen opaque base (present()'s
450
+ // frameHasOpaqueBase precondition).
451
+ endFrame(bgStyle: string, viewW: number, viewH: number): number {
452
+ const __perfT0 = Date.now() // TEMP MEASUREMENT (gea3d phase split): remove after profiling.
453
+ const ctx = Display.ctx
454
+ ctx.beginBatch()
455
+ if (bgStyle !== '') {
456
+ ctx.fillStyle = bgStyle
457
+ ctx.fillRect(0, 0, viewW, viewH)
458
+ }
459
+ const n = this.outCount
460
+ if (n === 0) {
461
+ ctx.endBatch()
462
+ return 0
463
+ }
464
+
465
+ // Depth range (distance in front of camera; view z is negative)
466
+ let dMin: f32 = (-this.outDepth[0]) as f32
467
+ let dMax: f32 = dMin
468
+ for (let i = 1; i < n; i++) {
469
+ const d: f32 = (-this.outDepth[i]) as f32
470
+ if (d < dMin) dMin = d
471
+ if (d > dMax) dMax = d
472
+ }
473
+ const range: f32 = (dMax - dMin) as f32
474
+ const scale: f32 = range > 0.000001 ? ((DEPTH_BUCKETS - 1) / range) as f32 : (0 as f32)
475
+
476
+ // Counting sort, key ascending == far-to-near
477
+ const keys = this.sortKeys
478
+ const starts = this.bucketStarts
479
+ for (let b = 0; b <= DEPTH_BUCKETS; b++) starts[b] = 0
480
+ for (let i = 0; i < n; i++) {
481
+ const d: f32 = (-this.outDepth[i]) as f32
482
+ let k = Math.floor((dMax - d) * scale)
483
+ if (k < 0) k = 0
484
+ if (k >= DEPTH_BUCKETS) k = DEPTH_BUCKETS - 1
485
+ keys[i] = k
486
+ starts[k + 1]++
487
+ }
488
+ for (let b = 1; b <= DEPTH_BUCKETS; b++) starts[b] += starts[b - 1]
489
+ const order = this.sortOrder
490
+ for (let i = 0; i < n; i++) {
491
+ const k = keys[i]
492
+ order[starts[k]] = i
493
+ starts[k]++
494
+ }
495
+
496
+ const __perfT1 = Date.now() // TEMP MEASUREMENT (gea3d phase split): remove after profiling.
497
+ // ONE recorded present command for the whole depth-sorted frame — the
498
+ // per-triangle fillTriangleRgb565 loop paid command record + replay
499
+ // dispatch per triangle, which dominated at a few hundred triangles.
500
+ ctx.fillTrianglesRgb565Sorted(
501
+ this.outX0,
502
+ this.outY0,
503
+ this.outX1,
504
+ this.outY1,
505
+ this.outX2,
506
+ this.outY2,
507
+ this.outColor,
508
+ order,
509
+ n,
510
+ )
511
+ const __perfT2 = Date.now() // TEMP MEASUREMENT (gea3d phase split): remove after profiling.
512
+ ctx.endBatch()
513
+ // TEMP MEASUREMENT (gea3d phase split): remove after profiling.
514
+ const __perfT3 = Date.now()
515
+ this.perfSortMs = __perfT1 - __perfT0
516
+ this.perfEmitMs = __perfT2 - __perfT1
517
+ this.perfPresentMs = __perfT3 - __perfT2
518
+ return n
519
+ }
520
+ }
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: GPL-3.0-only
2
+ // The presenter is the seam between the fixed-function pipeline and whatever
3
+ // actually puts pixels on screen. Today the only implementation records
4
+ // flat-color triangles into the gea present-command stream. A future native
5
+ // backend (banded z-buffer, gouraud, PIE/SIMD spans) implements the same
6
+ // interface via `gea.nativeSources` + `declare function __gea3d_*` bindings
7
+ // without touching the pipeline above it.
8
+
9
+ import type { CanvasRenderingContext2D } from '@geastack/core'
10
+
11
+ export interface TrianglePresenter {
12
+ fillTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, color: number): void
13
+ }
14
+
15
+ export class CtxPresenter implements TrianglePresenter {
16
+ private readonly ctx: CanvasRenderingContext2D
17
+
18
+ constructor(ctx: CanvasRenderingContext2D) {
19
+ this.ctx = ctx
20
+ }
21
+
22
+ fillTriangle(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, color: number): void {
23
+ this.ctx.fillTriangleRgb565(x0, y0, x1, y1, x2, y2, color)
24
+ }
25
+ }
@@ -0,0 +1,128 @@
1
+ // SPDX-License-Identifier: GPL-3.0-only
2
+ // GeaRenderer — draws a three-style scene through gea3d's native engine
3
+ // (gea3d/src/native/gea3d_native.cpp, compiled into the firmware via the
4
+ // app's `gea.nativeSources`). Each frame writes what changed in the TS scene
5
+ // graph to its native mirror, then ONE drawScene call culls, transforms,
6
+ // lights, sorts and rasterizes natively.
7
+ //
8
+ // With a retained UI mounted (on an engine that supports the underlay hook)
9
+ // the frame is composited UNDER the UI nodes in the engine's own flush, so
10
+ // HUD text and buttons stay on top without flicker. Elsewhere the frame is
11
+ // presented straight to the display, or into an image surface
12
+ // (setImageTarget) that a <canvas> node draws.
13
+
14
+ import { Camera } from '../three/camera'
15
+ import { advanceNativeFrame } from '../three/cache'
16
+ import { Object3D, Scene } from '../three/core'
17
+ import {
18
+ createSurface,
19
+ drawScene,
20
+ renderOptions,
21
+ renderTarget,
22
+ stat,
23
+ STAT_CLIP_DROPPED,
24
+ STAT_CULLED,
25
+ STAT_DROPPED,
26
+ STAT_MESHES_CULLED,
27
+ STAT_MESHES_DRAWN,
28
+ STAT_NEAR_REJECTED,
29
+ STAT_SUBMITTED,
30
+ } from '../native/api'
31
+
32
+ export interface GeaRendererOptions {
33
+ // Primitives per frame (default 4096).
34
+ triangleCapacity?: number
35
+ // Per-pixel depth test for opaque geometry (exact intersections). Off:
36
+ // nearest-first coverage, each pixel written once.
37
+ depthBuffer?: boolean
38
+ }
39
+
40
+ export class GeaRenderer {
41
+ width: number
42
+ height: number
43
+ autoClear: boolean
44
+ // Render stats for the last frame
45
+ trianglesDrawn: number
46
+ trianglesDropped: number
47
+ statLine: string
48
+
49
+ private statFrames: number
50
+ private imageTarget: number
51
+
52
+ constructor(options?: GeaRendererOptions) {
53
+ this.width = 0
54
+ this.height = 0
55
+ this.autoClear = true
56
+ this.trianglesDrawn = 0
57
+ this.trianglesDropped = 0
58
+ this.statLine = ''
59
+ this.statFrames = 0
60
+ this.imageTarget = -1
61
+
62
+ let capacity = 4096
63
+ let depthBuffer = false
64
+ if (options !== undefined) {
65
+ const requested = options.triangleCapacity
66
+ if (requested !== undefined) capacity = requested
67
+ const depth = options.depthBuffer
68
+ if (depth !== undefined) depthBuffer = depth
69
+ }
70
+ renderOptions(depthBuffer ? 1 : 0, capacity)
71
+ }
72
+
73
+ setSize(width: number, height: number): void {
74
+ this.width = Math.floor(width)
75
+ this.height = Math.floor(height)
76
+ }
77
+
78
+ // Renders into a native image surface instead of the display and returns
79
+ // its image id: draw it with ctx.drawImage(imageFromId(id), x, y) on a
80
+ // <canvas> node. The fallback for engines without the UI underlay.
81
+ setImageTarget(width: number, height: number): number {
82
+ if (this.imageTarget < 0) this.imageTarget = createSurface(width, height)
83
+ renderTarget(this.imageTarget)
84
+ this.setSize(width, height)
85
+ return this.imageTarget
86
+ }
87
+
88
+ render(scene: Scene, camera: Camera): void {
89
+ if (this.width <= 0 || this.height <= 0) {
90
+ // Use window.* rather than Display.width/height: both are host
91
+ // property→method bridges, but the emitter lowers window.innerWidth
92
+ // reliably, whereas Display.width intermittently emits as a member ref
93
+ // (uncalled method) on larger programs. App code always calls setSize
94
+ // first, so this is only a safety net.
95
+ this.setSize(window.innerWidth, window.innerHeight)
96
+ }
97
+
98
+ advanceNativeFrame()
99
+ scene.syncNative(-1)
100
+ scene.syncEnvironment(this.autoClear)
101
+ syncCameraGraph(scene, camera)
102
+
103
+ const drawn = drawScene(scene.nativeNode.id, camera.nativeNode.id, this.width, this.height)
104
+ this.trianglesDrawn = drawn < 0 ? 0 : drawn
105
+ this.trianglesDropped = stat(STAT_DROPPED)
106
+ // The stat line refreshes every 120 frames rather than per frame: it is
107
+ // a string build, and nothing needs it fresher.
108
+ this.statFrames++
109
+ if (this.statFrames >= 120) {
110
+ this.statLine =
111
+ 'submitted=' + stat(STAT_SUBMITTED) +
112
+ ' near=' + stat(STAT_NEAR_REJECTED) +
113
+ ' culled=' + stat(STAT_CULLED) +
114
+ ' clip=' + stat(STAT_CLIP_DROPPED) +
115
+ ' drawn=' + this.trianglesDrawn +
116
+ ' meshes=' + stat(STAT_MESHES_DRAWN) +
117
+ ' offscreen=' + stat(STAT_MESHES_CULLED)
118
+ this.statFrames = 0
119
+ }
120
+ }
121
+ }
122
+
123
+ // A camera outside the scene graph (the common three.js setup) syncs its
124
+ // own graph; one inside it was synced with the scene.
125
+ function syncCameraGraph(scene: Scene, camera: Camera): void {
126
+ const root: Object3D = camera.root()
127
+ if (root.id !== scene.id) root.syncNative(-1)
128
+ }