lecodes-sdk 2.4.7 → 2.4.9

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/src/gl/Camera.ts CHANGED
@@ -1,20 +1,49 @@
1
- // The scene camera — a Node (so position / lookAt / transform all work) plus projection reads and
2
- // screen↔world ray helpers. Created and attached by Scene. Ported from worker/src/components/Camera.ts.
1
+ // A camera — a Node (so position / lookAt / transform all work) plus its lens. The scene camera is created and attached
2
+ // by Scene (`_attach`: its projection, exposure and the screen↔world ray helpers are the screen's); a SECONDARY camera is
3
+ // `new Camera(options)`, a plain node until `renderToTexture` gives it a render view of its scene (RenderTexture.ts,
4
+ // creator-gl renderview.cpp), started once the node is in a scene (Node.ts awaitScene). Ported from
5
+ // worker/src/components/Camera.ts.
3
6
 
4
7
  import { Vec3 } from "../math/vec"
5
8
  import { Aspect } from "../core/Aspect"
6
- import { Node, type NodeTweenProps } from "./Node"
9
+ import { Node, awaitScene, type NodeTweenProps } from "./Node"
7
10
  import { Ray } from "./Ray"
11
+ import { RenderTexture, makeRenderTexture, startRenderView } from "./RenderTexture"
8
12
  import { DOM_GL_CAMERA, floatValue, type TweenChannel, type TweenMeta } from "../animate/tween/spec"
9
13
  import type { Animation } from "../animate/tween/Animation"
10
14
 
11
- /** Animatable camera props on top of the node transform. */
15
+ /** Animatable camera props on top of the node transform. `fov` / `near` / `far` are the SCENE camera's: on a secondary
16
+ * camera they throw (set them directly — they are live — or from `animate({ onUpdate })`). */
12
17
  export type CameraTweenProps = NodeTweenProps & {
13
18
  fov?: number | number[],
14
19
  near?: number | number[],
15
20
  far?: number | number[],
16
21
  }
17
22
 
23
+ /** `new Camera(options)`: a SECONDARY camera's lens and what its view draws (the scene's own camera is `scene.camera`). */
24
+ export type CameraOptions = {
25
+ /** Vertical field of view in degrees (default 60). Live: `camera.fov`. */
26
+ fov?: number
27
+ /** Near clip distance in metres (default 0.01). Live: `camera.near`. */
28
+ near?: number
29
+ /** Far clip distance in metres (default 1000). Live: `camera.far`. */
30
+ far?: number
31
+ /** The layers its view draws, a bit mask over `Node.layer` (default 0xff = everything): a renderable is drawn when its
32
+ * layers share a bit with these — the player's own body left out of a mirror. Fixed when the view starts. */
33
+ layers?: number
34
+ /** Shadows in its view (default `true`): the view renders shadow maps of its own each time it draws. Fixed when the
35
+ * view starts. */
36
+ shadows?: boolean
37
+ }
38
+
39
+ /** `camera.renderToTexture(options)`: the picture's size. */
40
+ export type RenderToTextureOptions = {
41
+ /** Texels wide, 1..4096 (default 256). */
42
+ width?: number
43
+ /** Texels tall, 1..4096 (default 256). */
44
+ height?: number
45
+ }
46
+
18
47
  /** @internal `camera.follow(node)`: copies the node's world pose onto the camera every LATE frame
19
48
  * (order 1000 — after every other aspect has moved things). One per camera; lives on the target. */
20
49
  export class CameraFollowRig extends Aspect<"__cameraFollow"> {
@@ -31,16 +60,33 @@ export class CameraFollowRig extends Aspect<"__cameraFollow"> {
31
60
  /** Projection every host starts a scene with (creator-gl scene.cpp / the lite core agree on these). */
32
61
  export const CAMERA_DEFAULTS = { fov: 60, near: 0.01, far: 1000 }
33
62
 
63
+ /** A texture side: a whole number, 1 at least (the host refuses more than 4096). */
64
+ const side = (n: number): number => Math.max(1, Math.floor(n))
65
+
66
+ /**
67
+ * A camera: a Node (position, `lookAt`, parenting — it looks down its −Z) with a lens, `fov` / `near` / `far`. Two kinds:
68
+ * - THE SCENE CAMERA, `scene.camera`: made by the Scene, it draws the screen. Its exposure, `projectionMatrix` and the
69
+ * ray helpers (`getRay`, `getViewDirection`) are the screen's, and its projection tweens (`animateTo({ fov })`).
70
+ * - A SECONDARY camera, `new Camera({ fov, layers, shadows })`: a plain node until `renderToTexture({ width, height })`
71
+ * gives it a second view of its scene, drawn into a texture every frame the scene is on show — a rear-view mirror, a
72
+ * monitor, a security camera. Place it like any node (`car.add(mirrorCam)`); its lens is live (`mirrorCam.fov = 50`),
73
+ * its view's schedule is `enabled` / `everyNth`. A cube of light for reflections is a `ReflectionProbe`.
74
+ */
34
75
  export class Camera extends Node {
76
+ /** The scene this camera draws the screen of (Scene `_attach`); -1 = a secondary camera. */
35
77
  private _sceneId = -1
36
78
 
37
- /** Tween `fov` / `near` / `far` (a zoom, a dolly) and the transform — see {@link Node.animateTo}. */
79
+ /** Tween `fov` / `near` / `far` (a zoom, a dolly — the scene camera's) and the transform — see {@link Node.animateTo}. */
38
80
  override animateTo(props: CameraTweenProps & TweenMeta): Animation { return super.animateTo(props) }
39
81
  override animateFrom(props: CameraTweenProps & TweenMeta): Animation { return super.animateFrom(props) }
40
- /** @internal The projection channels address the SCENE (one camera per scene on the host). */
82
+ /** @internal The projection channels address the SCENE (one camera per scene on the host): a render view's
83
+ * projection has no tween writer, so a secondary camera's throw. */
41
84
  override _tweenChannel(prop: string): TweenChannel | null {
42
85
  if (prop === "fov" || prop === "near" || prop === "far") {
43
- const id = () => (this._sceneId < 0 ? 0 : this._sceneId + 1) // scene ids start at 0; 0 = unaddressable
86
+ if (this._sceneId < 0) {
87
+ throw new Error(`Camera: a secondary camera's "${prop}" is not animatable (the tween core drives the scene camera's projection only) — set camera.${prop} directly, it is live: per frame, or animate({ from, to, onUpdate: (v) => { camera.${prop} = v } })`)
88
+ }
89
+ const id = () => this._sceneId + 1 // scene ids start at 0; 0 = unaddressable
44
90
  const commit = (v: unknown) => {
45
91
  if (prop === "fov") this._fov = v as number
46
92
  else if (prop === "near") this._near = v as number
@@ -51,11 +97,12 @@ export class Camera extends Node {
51
97
  }
52
98
  return super._tweenChannel(prop)
53
99
  }
54
- /** Live projection matrix (updated by the host when the viewport/fov changes). */
100
+ /** The scene camera's live projection matrix (updated by the host when the viewport / fov changes). A secondary
101
+ * camera's stays zero: its projection is `fov` / `near` / `far` at its texture's aspect. */
55
102
  readonly projectionMatrix = new Float32Array(16)
56
103
 
57
- // Projection the app asked for (host defaults until it does). The host owns the aspect and
58
- // re-applies these on every viewport change, so they are set, not maintained.
104
+ // Projection the app asked for (host defaults until it does). The scene camera's host owns the aspect and re-applies
105
+ // these on every viewport change, so they are set, not maintained; a secondary camera's are its view's.
59
106
  private _fov = CAMERA_DEFAULTS.fov
60
107
  private _near = CAMERA_DEFAULTS.near
61
108
  private _far = CAMERA_DEFAULTS.far
@@ -69,7 +116,29 @@ export class Camera extends Node {
69
116
  private _ev = 0
70
117
  private _exposureSet = false
71
118
 
72
- /** @internal — Scene wires the camera to its native scene id + projection callback. */
119
+ // A secondary camera's view (renderToTexture): what it draws with, fixed when it starts, and its schedule.
120
+ private readonly _layers: number
121
+ private readonly _shadows: boolean
122
+ private _enabled = true
123
+ private _everyNth = 1
124
+ /** @internal The texture `renderToTexture` made (held: it lives as long as the camera does). */
125
+ _texture: RenderTexture | null = null
126
+ /** @internal The render view's owned handle (`_view.id` = the engine's view id), null until the view starts: it lives
127
+ * exactly as long as this camera holds it. */
128
+ _view: Handle | null = null
129
+
130
+ /** A SECONDARY camera (`scene.camera` is the scene's own): a plain node until `renderToTexture`. `options`: its lens
131
+ * (live after, through `fov` / `near` / `far`) and what its view draws (`layers`, `shadows` — fixed). */
132
+ constructor(options: CameraOptions = {}) {
133
+ super()
134
+ if (options.fov !== undefined) this._fov = options.fov
135
+ if (options.near !== undefined) this._near = options.near
136
+ if (options.far !== undefined) this._far = options.far
137
+ this._layers = (options.layers ?? 0xff) & 0xff
138
+ this._shadows = options.shadows !== false
139
+ }
140
+
141
+ /** @internal — Scene wires the camera to its native scene id + projection callback: the SCENE camera. */
73
142
  _attach(sceneId: number): void {
74
143
  this._sceneId = sceneId
75
144
  _creator.attachCameraToAR(sceneId, this.id, (mat) => {
@@ -79,11 +148,90 @@ export class Camera extends Node {
79
148
  if (this._exposureSet) this._applyExposure()
80
149
  }
81
150
 
151
+ /** @internal What only the scene camera has (the screen's ray helpers): a clear throw on a secondary camera. */
152
+ private _sceneOnly(what: string): void {
153
+ if (this._sceneId < 0) throw new Error(`camera.${what}: the scene camera's (scene.camera) — a secondary camera has no screen to pick through`)
154
+ }
155
+ /** @internal What only a secondary camera has (a render view): a clear throw on the scene camera. */
156
+ private _secondaryOnly(what: string): void {
157
+ if (this._sceneId >= 0) throw new Error(`camera.${what}: the scene camera draws the screen, every frame its scene is on show — a second view is a new Camera() with renderToTexture`)
158
+ }
159
+
160
+ /**
161
+ * Draw this camera's view of its scene into a new 2D texture of `width × height` texels (default 256 × 256): the
162
+ * tone-mapped picture as the screen would show it (LDR) — `screen.material.map = cam.renderToTexture({ ... })`. The
163
+ * camera holds it (`camera.texture`).
164
+ *
165
+ * THE VIEW starts once the camera is in a scene (added to one, or under a node that is — at once if it already is)
166
+ * and draws every frame that scene is on show, after the frame's update passes (aspects, physics, animation: this
167
+ * frame's poses) and before the scene's own picture. It sees the scene's renderables, lights, environment and sky (not
168
+ * its overlays) from the camera's WORLD pose (scale ignored) through `fov` / `near` / `far` at the texture's aspect,
169
+ * with the `layers` and `shadows` the camera was made with, at the scene camera's exposure; its post-processing is the
170
+ * engine's default tone mapping (the scene's grading, bloom and the rest are not mirrored). Moving the camera to
171
+ * another scene later does not move the view.
172
+ *
173
+ * COST: every render is another pass over the scene — with `shadows`, its own shadow maps too. Keep the texture small,
174
+ * draw less often (`everyNth`), leave out what the view does not need (`layers`), and turn it off out of sight
175
+ * (`enabled = false`).
176
+ *
177
+ * Calling it again REPLACES the texture and the view: the previous view stops at once, its texture keeps its last
178
+ * picture while something still shows it. Throws on the scene camera, and on a host without render textures (the web
179
+ * hosts, for now).
180
+ */
181
+ renderToTexture(options: RenderToTextureOptions = {}): RenderTexture {
182
+ this._secondaryOnly("renderToTexture")
183
+ const texture = makeRenderTexture("camera.renderToTexture", side(options.width ?? 256), side(options.height ?? 256), 0)
184
+ if (this._view) { // replaced: the old view stops now; its handle goes with this reference
185
+ _creator.setRenderViewOptions?.(this._view.id, false, 1, 6)
186
+ this._view = null
187
+ }
188
+ this._texture = texture
189
+ awaitScene(this)
190
+ return texture
191
+ }
192
+
193
+ /** @internal Node.ts awaitScene: the camera is in scene `sceneId` — start its view into its texture. */
194
+ _bindView(sceneId: number): void {
195
+ const texture = this._texture
196
+ if (this._view || !texture) return
197
+ this._view = startRenderView("camera", sceneId, texture, this.id, this._layers, this._fov, this._near, this._far, this._shadows)
198
+ if (this._view && (!this._enabled || this._everyNth !== 1)) this._sendSchedule()
199
+ }
200
+
201
+ /** The texture `renderToTexture` made — the latest, null before one. */
202
+ get texture(): RenderTexture | null { return this._texture }
203
+
204
+ /** Whether this secondary camera's view draws (default `true`). Off keeps the last picture in its texture and costs
205
+ * nothing — a mirror out of sight; back on, it renders on the next frame drawn. The scene camera always draws (reads
206
+ * `true`; setting it throws). */
207
+ get enabled(): boolean { return this._enabled }
208
+ set enabled(on: boolean) {
209
+ this._secondaryOnly("enabled")
210
+ this._enabled = on
211
+ this._sendSchedule()
212
+ }
213
+ /** Render this secondary camera's view once every N frames DRAWN (default 1 = every frame). The count restarts with
214
+ * each change: the next frame drawn renders, then one in every N. The scene camera draws every frame (reads 1;
215
+ * setting it throws). */
216
+ get everyNth(): number { return this._everyNth }
217
+ set everyNth(n: number) {
218
+ this._secondaryOnly("everyNth")
219
+ this._everyNth = Math.max(1, Math.floor(n))
220
+ this._sendSchedule()
221
+ }
222
+
223
+ /** @internal Send the whole schedule (`setRenderViewOptions` restarts the count, so the next frame drawn renders). */
224
+ private _sendSchedule(): void {
225
+ if (this._view) _creator.setRenderViewOptions?.(this._view.id, this._enabled, this._everyNth, 6)
226
+ }
227
+
82
228
  /** Exposure compensation in stops (default 0): +1 doubles how bright the scene renders, −2
83
229
  * quarters it. The one exposure knob most games need — a dark interior, a flash of white, or eye
84
230
  * adaptation when the sun swings into view (drop it, and the sun stays at the display's peak
85
231
  * while everything else darkens). Scene light follows it; particle `emissive` is post-exposure
86
- * and does not, so a fireball keeps its on-screen brightness. Cheap to animate every frame. */
232
+ * and does not, so a fireball keeps its on-screen brightness. Cheap to animate every frame. The
233
+ * scene camera's: a secondary camera's view renders at its scene camera's exposure (what is set on
234
+ * a secondary camera is kept, unused). */
87
235
  /** The camera's EV100 with the compensation in: log2(aperture² / shutterSpeed x 100 / iso) - compensation. Sunny 16 is
88
236
  * ~15; a lit surface of luminance L lands on screen at L / (1.2 x 2^ev100). */
89
237
  get ev100(): number {
@@ -99,7 +247,7 @@ export class Camera extends Node {
99
247
 
100
248
  /** The physical camera: `aperture` in f-stops, `shutterSpeed` in seconds, `iso`, plus the same
101
249
  * `compensation` in stops — any subset, one call. `camera.setExposure({ iso: 400 })` is two stops
102
- * brighter than the default f/16 · 1/125 · ISO 100. */
250
+ * brighter than the default f/16 · 1/125 · ISO 100. The scene camera's (as `exposureCompensation`). */
103
251
  setExposure(exposure: { aperture?: number, shutterSpeed?: number, iso?: number, compensation?: number }): this {
104
252
  if (exposure.aperture !== undefined) this._exposure.aperture = exposure.aperture
105
253
  if (exposure.shutterSpeed !== undefined) this._exposure.shutterSpeed = exposure.shutterSpeed
@@ -117,17 +265,25 @@ export class Camera extends Node {
117
265
  _creator.setCameraExposure?.(this._sceneId, e.aperture, e.shutterSpeed, e.iso * 2 ** this._ev)
118
266
  }
119
267
 
120
- /** Vertical field of view in degrees (default 60) — a smaller angle is a longer lens. */
121
- get fov(): number { return _creator.getCameraFov(this._sceneId, 0) }
268
+ /** Vertical field of view in degrees (default 60) — a smaller angle is a longer lens. Live on both kinds: a
269
+ * secondary camera's reaches its view at the next render (before `renderToTexture`, the view's starting value). */
270
+ get fov(): number { return this._sceneId >= 0 ? _creator.getCameraFov(this._sceneId, 0) : this._fov }
122
271
  set fov(degrees: number) { this._fov = degrees; this._projSet = true; this._applyProjection() }
123
- get horizontalFov(): number { return _creator.getCameraFov(this._sceneId, 1) }
272
+ /** The horizontal field of view in degrees: the scene camera's at the screen's aspect, a secondary camera's at its
273
+ * texture's (square before `renderToTexture`). */
274
+ get horizontalFov(): number {
275
+ if (this._sceneId >= 0) return _creator.getCameraFov(this._sceneId, 1)
276
+ const t = this._texture
277
+ const aspect = t ? t.width / t.height : 1
278
+ return Math.atan(Math.tan(this._fov * Math.PI / 360) * aspect) * 360 / Math.PI
279
+ }
124
280
 
125
- /** Near clip distance (default 0.01) — nothing closer than this draws. */
281
+ /** Near clip distance (default 0.01) — nothing closer than this draws. Live, as `fov`. */
126
282
  get near(): number { return this._near }
127
283
  set near(distance: number) { this._near = distance; this._projSet = true; this._applyProjection() }
128
284
 
129
285
  /** Far clip distance / view range (default 1000) — geometry past it is culled. Shadows keep
130
- * their own (shorter) range, so a long view distance doesn't cost shadow sharpness. */
286
+ * their own (shorter) range, so a long view distance doesn't cost shadow sharpness. Live, as `fov`. */
131
287
  get far(): number { return this._far }
132
288
  set far(distance: number) { this._far = distance; this._projSet = true; this._applyProjection() }
133
289
 
@@ -141,11 +297,22 @@ export class Camera extends Node {
141
297
  return this
142
298
  }
143
299
 
144
- /** Hosts that predate the call keep the fixed defaults (older wasm / native builds). */
300
+ /** Hosts that predate the call keep the fixed defaults (older wasm / native builds); a secondary camera's view keeps
301
+ * the projection it started with (warned once). */
145
302
  private _applyProjection(): void {
146
- if (this._sceneId < 0 || typeof _creator.setCameraProjection !== "function") return
303
+ if (this._sceneId < 0) {
304
+ if (!this._view) return // remembered: the view starts with it
305
+ if (_creator.setRenderViewProjection) _creator.setRenderViewProjection(this._view.id, this._fov, this._near, this._far)
306
+ else if (!Camera._warnedViewProjection) {
307
+ Camera._warnedViewProjection = true
308
+ console.warn("[camera] this host has no setRenderViewProjection — a secondary camera keeps the projection its view started with")
309
+ }
310
+ return
311
+ }
312
+ if (typeof _creator.setCameraProjection !== "function") return
147
313
  _creator.setCameraProjection(this._sceneId, this._fov, this._near, this._far)
148
314
  }
315
+ private static _warnedViewProjection = false
149
316
  private _following: Node | null = null
150
317
  /** The node the camera currently follows (`follow()`), or null. */
151
318
  get following(): Node | null { return this._following }
@@ -155,7 +322,9 @@ export class Camera extends Node {
155
322
  * view direction), so movement aspects / animation on that node are camera moves — dolly shots,
156
323
  * a cutscene path, a `CameraPlace` in a scene file. A node carrying a `CameraPlace` also hands
157
324
  * over its projection (fov / near / far). `follow(null)` releases the camera where it is.
158
- * One camera per scene: following a new node stops following the previous one.
325
+ * Following a new node stops following the previous one, and a node leads one camera at a time.
326
+ * Either kind: the pose is written as the camera's own transform, so a following secondary
327
+ * camera is a scene root, not a child.
159
328
  */
160
329
  follow(target: Node | { node: Node, applyTo(camera: Camera): void } | null): this {
161
330
  const node = target === null ? null : target instanceof Node ? target : target.node
@@ -175,22 +344,26 @@ export class Camera extends Node {
175
344
 
176
345
  /** The scene view's [width, height] in logical units — the units of the scene's touches
177
346
  * (`clientX` / `clientY`) and of `getRay`, on every host; × `device.pixelRatio` for device px.
178
- * [0, 0] before the scene has a viewport. */
347
+ * [0, 0] before the scene has a viewport. The screen's, whichever camera reads it. */
179
348
  get displaySize(): [number, number] {
180
349
  const s = _creator.getDisplaySize()
181
350
  return [ s[0], s[1] ]
182
351
  }
183
352
 
184
- /** World-space ray direction through a point of the scene view (logical units, as a touch's). */
353
+ /** World-space ray direction through a point of the scene view (logical units, as a touch's). The scene camera's
354
+ * (a secondary camera throws). */
185
355
  getViewDirection(screenX: number, screenY: number): Vec3 {
186
- if (this._sceneId < 0) throw new Error("Camera is not attached to a scene")
356
+ this._sceneOnly("getViewDirection")
187
357
  const v = new Float32Array(3)
188
358
  _creator.getCameraViewDirection(this._sceneId, screenX, screenY, v)
189
359
  return new Vec3(v[0], v[1], v[2])
190
360
  }
191
361
 
192
- /** A pick ray from the camera through a point of the scene view (logical units, as a touch's). */
362
+ /** A pick ray from the camera through a point of the scene view (logical units, as a touch's). The scene camera's
363
+ * (a secondary camera throws). */
193
364
  getRay(screenX: number, screenY: number): Ray {
365
+ this._sceneOnly("getRay")
194
366
  return new Ray(this.worldPosition, this.getViewDirection(screenX, screenY))
195
367
  }
196
368
  }
369
+