@solidrt/3d 0.0.56 → 0.0.57

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.
Files changed (40) hide show
  1. package/AGENTS.md +199 -117
  2. package/README.md +2 -1
  3. package/examples/README.md +13 -8
  4. package/examples/collision.tsx +17 -4
  5. package/examples/first-person.tsx +20 -10
  6. package/examples/fleet.tsx +11 -5
  7. package/examples/model.tsx +3 -3
  8. package/examples/pick.tsx +144 -34
  9. package/examples/probe.tsx +10 -4
  10. package/examples/scene-views.tsx +49 -58
  11. package/examples/sky-lit.tsx +10 -4
  12. package/examples/skybox.tsx +10 -4
  13. package/examples/standard.tsx +10 -4
  14. package/package.json +2 -2
  15. package/src/collision.ts +14 -193
  16. package/src/components/context.tsx +35 -0
  17. package/src/components/directional-light.tsx +48 -0
  18. package/src/components/first-person-camera.tsx +72 -0
  19. package/src/components/group.tsx +18 -0
  20. package/src/components/hemisphere-light.tsx +24 -0
  21. package/src/components/index.ts +46 -0
  22. package/src/components/instanced-mesh.tsx +105 -0
  23. package/src/components/mesh.tsx +92 -0
  24. package/src/components/node-props.ts +90 -0
  25. package/src/components/orbit-camera.tsx +75 -0
  26. package/src/components/perspective-camera.tsx +32 -0
  27. package/src/components/point-light.tsx +52 -0
  28. package/src/components/record-mesh.tsx +68 -0
  29. package/src/components/scene.tsx +281 -0
  30. package/src/components/spot-light.tsx +65 -0
  31. package/src/components/sprite.tsx +38 -0
  32. package/src/components/view3d.tsx +152 -0
  33. package/src/first-person.ts +140 -188
  34. package/src/index.ts +13 -9
  35. package/src/input.ts +70 -0
  36. package/src/node.ts +98 -25
  37. package/src/orbit.ts +266 -235
  38. package/src/scene-pointer.ts +229 -101
  39. package/src/scene.ts +250 -76
  40. package/src/components.tsx +0 -1101
@@ -0,0 +1,90 @@
1
+ import { createEffect } from "@solidrt/core"
2
+ import { setTransform, setTransition, setVisible } from "../node.ts"
3
+ import type { NodePointerEvent, NodeTapEvent, NodeWheelEvent, SceneNode, TransitionEndEvent } from "../node.ts"
4
+ import type { NodeTransition } from "flux:spatial"
5
+ import type { Quat, Vec3 } from "../math.ts"
6
+
7
+ export type TransformProps = {
8
+ position?: Vec3
9
+ /** Euler radians in XYZ order (x first), Three's `Euler` default. */
10
+ rotation?: Vec3
11
+ /** The rotation as a quaternion - what the node stores. Pass this or
12
+ * `rotation`, not both. */
13
+ quaternion?: Quat
14
+ scale?: Vec3 | number
15
+ visible?: boolean
16
+ /** How transform-prop changes animate (see setTransition); the mount
17
+ * transform always snaps. */
18
+ transition?: NodeTransition | string | null
19
+ /** A declared transition settled on one component. */
20
+ onTransitionEnd?: (event: TransitionEndEvent) => void
21
+ }
22
+
23
+ /**
24
+ * Node pointer events, the element vocabulary one tree deeper: the nearest
25
+ * hit (the struck instance, else the mesh) receives the event,
26
+ * down/move/up/wheel/tap bubble to ancestor Groups and end at the
27
+ * `<Scene>`'s own handlers (stopPropagation stops the walk; a stopped
28
+ * down claims the whole press, so a mesh that drags itself keeps an
29
+ * `<OrbitCamera>` still), enter/leave pair on the struck node alone.
30
+ * Events flow while the element showing the scene carries scene.handlers -
31
+ * the built-in <Scene> leaf does (opt out with events={false}); an `output`
32
+ * leaf spreads them itself.
33
+ */
34
+ export type PointerEventProps = {
35
+ onPointerDown?: (event: NodePointerEvent) => void
36
+ onPointerMove?: (event: NodePointerEvent) => void
37
+ onPointerUp?: (event: NodePointerEvent) => void
38
+ /** Meshes and instances only: a Group never receives enter/leave. */
39
+ onPointerEnter?: (event: NodePointerEvent) => void
40
+ onPointerLeave?: (event: NodePointerEvent) => void
41
+ /** The wheel over the node: `deltaX`/`deltaY`. */
42
+ onWheel?: (event: NodeWheelEvent) => void
43
+ /** A press released on the node within the slop, alone for its whole
44
+ * press: DOM's click, with `tapCount` for repeats. */
45
+ onTap?: (event: NodeTapEvent) => void
46
+ }
47
+
48
+ export function syncNode(node: SceneNode, props: TransformProps & PointerEventProps): void {
49
+ // One effect for the transform and the handlers: re-assigning eight
50
+ // handler fields on a transform write is free, an effect of its own is
51
+ // not (a node component's mount cost is mostly its effects and its
52
+ // context provider, see probes/3d-instance-mount-bench.tsx).
53
+ createEffect(
54
+ () =>
55
+ [
56
+ props.position,
57
+ props.rotation,
58
+ props.quaternion,
59
+ props.scale,
60
+ props.visible,
61
+ props.onPointerDown,
62
+ props.onPointerMove,
63
+ props.onPointerUp,
64
+ props.onPointerEnter,
65
+ props.onPointerLeave,
66
+ props.onWheel,
67
+ props.onTap,
68
+ props.onTransitionEnd,
69
+ ] as const,
70
+ ([position, rotation, quaternion, scale, visible, down, move, up, enter, leave, wheel, tap, end]) => {
71
+ setTransform(node, { position, rotation, quaternion, scale })
72
+ setVisible(node, visible !== false)
73
+ node.onPointerDown = down
74
+ node.onPointerMove = move
75
+ node.onPointerUp = up
76
+ node.onPointerEnter = enter
77
+ node.onPointerLeave = leave
78
+ node.onWheel = wheel
79
+ node.onTap = tap
80
+ node.onTransitionEnd = end
81
+ },
82
+ )
83
+ // After the transform effect, so the mount transform snaps before writes
84
+ // animate. Its own effect: merged above, every transform write would
85
+ // re-send the config to the core.
86
+ createEffect(
87
+ () => props.transition,
88
+ transition => setTransition(node, transition ?? null),
89
+ )
90
+ }
@@ -0,0 +1,75 @@
1
+ import { createEffect, merge, onFrame, untrack, useContext } from "@solidrt/core"
2
+ import type { InputMap, VoidComponent } from "@solidrt/core"
3
+ import { SceneContext } from "./context.tsx"
4
+ import { createOrbitCamera } from "../orbit.ts"
5
+ import type { OrbitAxes, OrbitCamera as OrbitCameraHandle, OrbitCameraOptions } from "../orbit.ts"
6
+
7
+ // Cap on the frame loop's per-frame dt in seconds, so the first tick after
8
+ // a suspended stretch (a resumed app, a reload) cannot leap the pose.
9
+ const MAX_ORBIT_DT = 0.1
10
+
11
+ export type OrbitCameraProps = OrbitCameraOptions & {
12
+ /** The input map driving the control (InputMap.drive): its `rotate`,
13
+ * `zoom` and `pan` actions, or the ones `actions` names. Live: a new
14
+ * map reconnects. Without one the control moves only through `ref`. */
15
+ input?: InputMap<any>
16
+ /** Action names per axis when the map's differ (null skips an axis). */
17
+ actions?: Partial<Record<keyof OrbitAxes, string | null>>
18
+ /** The control's handle (pose()/set()/eye()/orbiting()/active(), the
19
+ * verbs, `axes` - also the debug command shape). */
20
+ ref?: (orbit: OrbitCameraHandle) => void
21
+ }
22
+
23
+ /**
24
+ * createOrbitCamera as a Scene (or View3d) child: drives the enclosing
25
+ * camera - the scene's, or inside a `<View3d>` that view's - through
26
+ * context, and takes its input from the map in `input`, nothing else
27
+ * (ARCHITECTURE.md: no device wiring in a component; the app binds a
28
+ * pointer feed, a pad or anything else to the map). The pose props
29
+ * (target, azimuth, elevation, distance) are initial values - change the
30
+ * pose at runtime through `ref`'s set() or the verbs; every other prop is
31
+ * live, forwarded to the control as a getter and read where it applies,
32
+ * so a clamp, a rate or an anchor callback follows its prop, and a clamp
33
+ * change re-clamps the pose at once. The frame loop runs only while
34
+ * `active()` (auto-orbit on, or an axis rate driving); a camera moved
35
+ * by drags alone leaves the app demand-driven idle.
36
+ */
37
+ export let OrbitCamera: VoidComponent<OrbitCameraProps> = props => {
38
+ let ctx = useContext(SceneContext)
39
+ // The control keeps this object and reads each option where it applies,
40
+ // so the props go through as getters (merge), never a spread: a spread
41
+ // would snapshot every prop once and a change could only remount.
42
+ let options: OrbitCameraOptions = merge(props, {})
43
+ let orbit = untrack(() => createOrbitCamera(ctx.viewport, options))
44
+ createEffect(
45
+ () => props.input,
46
+ input => (input ? input.drive(orbit.axes, untrack(() => props.actions)) : undefined),
47
+ )
48
+ createEffect(
49
+ () => orbit.active(),
50
+ on => {
51
+ if (!on) return
52
+ let last: number | null = null
53
+ return onFrame(tick => {
54
+ let now = tick / 1000
55
+ let dt = last === null ? 0 : Math.min(now - last, MAX_ORBIT_DT)
56
+ last = now
57
+ orbit.update(dt)
58
+ })
59
+ },
60
+ )
61
+ // A clamp prop change re-clamps the pose at once (set({}) applies the
62
+ // clamps and pushes) - the update() call a Three OrbitControls app
63
+ // makes after setting minDistance, done by the prop. Deferred: the
64
+ // creation already clamped and pushed the initial pose. Untracked: the
65
+ // control reads the clamps through the getters while it applies them,
66
+ // and the apply wants the values of that moment (the compute above is
67
+ // what tracks them).
68
+ createEffect(
69
+ () => [options.minDistance, options.maxDistance, options.minElevation, options.maxElevation],
70
+ () => untrack(() => orbit.set({})),
71
+ { defer: true },
72
+ )
73
+ untrack(() => props.ref)?.(orbit)
74
+ return null
75
+ }
@@ -0,0 +1,32 @@
1
+ import { createEffect, useContext } from "@solidrt/core"
2
+ import type { VoidComponent } from "@solidrt/core"
3
+ import { SceneContext } from "./context.tsx"
4
+ import type { Vec3 } from "../math.ts"
5
+
6
+ export type PerspectiveCameraProps = {
7
+ /** Vertical field of view in DEGREES (default 60). */
8
+ fov?: number
9
+ near?: number
10
+ far?: number
11
+ position?: Vec3
12
+ lookAt?: Vec3
13
+ up?: Vec3
14
+ }
15
+
16
+ /**
17
+ * Drives the enclosing camera from props - the scene's, or inside a
18
+ * `<View3d>` that view's (both have a default camera, so this component is
19
+ * optional). The camera is target state, not a tree node: to orbit it,
20
+ * update `position`/`lookAt`. The Scene and View3d `camera` props drive the
21
+ * same state (a partial CameraUpdate, ortho included) - use one form, not
22
+ * both.
23
+ */
24
+ export let PerspectiveCamera: VoidComponent<PerspectiveCameraProps> = props => {
25
+ let ctx = useContext(SceneContext)
26
+ createEffect(
27
+ () => [props.fov, props.near, props.far, props.position, props.lookAt, props.up] as const,
28
+ ([fov, near, far, position, lookAt, up]) =>
29
+ ctx.viewport.setCamera({ fov, near, far, position, target: lookAt, up }),
30
+ )
31
+ return null
32
+ }
@@ -0,0 +1,52 @@
1
+ import { createEffect, onCleanup, untrack, useContext } from "@solidrt/core"
2
+ import type { VoidComponent } from "@solidrt/core"
3
+ import { SceneContext } from "./context.tsx"
4
+ import { syncNode } from "./node-props.ts"
5
+ import type { TransformProps } from "./node-props.ts"
6
+ import { add, remove } from "../node.ts"
7
+ import { createPointLight, setLight } from "../light.ts"
8
+ import type { PointLight as PointLightNode, SpotShadowOptions } from "../light.ts"
9
+ import type { Vec3 } from "../math.ts"
10
+
11
+ export type PointLightProps = TransformProps & {
12
+ color?: Vec3
13
+ intensity?: number
14
+ /** Falloff cutoff in world units (0 = no cutoff). */
15
+ distance?: number
16
+ /** Falloff exponent; default 2 (inverse square). */
17
+ decay?: number
18
+ /** Render shadow maps from this light (six 90-degree face maps, one
19
+ * per cube face; six shadow slots). Far = `distance`, so give a
20
+ * casting bulb one. */
21
+ castShadow?: boolean
22
+ /** Shadow-map options (mapSize, bias, normalBias, near), merged key
23
+ * by key. */
24
+ shadow?: SpotShadowOptions
25
+ ref?: (light: PointLightNode) => void
26
+ }
27
+
28
+ /** A point light node (createPointLight): light in every direction from
29
+ * the node's world position - give it a `position`; rotation does not
30
+ * matter. Counts against MAX_LIGHTS with the other non-ambient lights. */
31
+ export let PointLight: VoidComponent<PointLightProps> = props => {
32
+ let ctx = useContext(SceneContext)
33
+ let light = untrack(() =>
34
+ createPointLight({
35
+ color: props.color,
36
+ intensity: props.intensity,
37
+ distance: props.distance,
38
+ decay: props.decay,
39
+ castShadow: props.castShadow,
40
+ shadow: props.shadow,
41
+ }),
42
+ )
43
+ add(ctx.parent, light)
44
+ syncNode(light, props)
45
+ createEffect(
46
+ () => [props.color, props.intensity, props.distance, props.decay, props.castShadow, props.shadow] as const,
47
+ ([color, intensity, distance, decay, castShadow, shadow]) => setLight(light, { color, intensity, distance, decay, castShadow, shadow }),
48
+ )
49
+ untrack(() => props.ref)?.(light)
50
+ onCleanup(() => remove(light))
51
+ return null
52
+ }
@@ -0,0 +1,68 @@
1
+ import { createEffect, onCleanup, untrack, useContext } from "@solidrt/core"
2
+ import type { VoidComponent } from "@solidrt/core"
3
+ import { SceneContext } from "./context.tsx"
4
+ import { syncMesh } from "./mesh.tsx"
5
+ import type { PopulatedMeshProps } from "./mesh.tsx"
6
+ import { add } from "../node.ts"
7
+ import { createRecordMesh, disposeInstances, setCastShadow, setGeometry, setRecordCount, setRecords } from "../mesh.ts"
8
+ import type { RecordMesh as RecordMeshNode } from "../mesh.ts"
9
+ import type { Geometry } from "../geometry.ts"
10
+ import type { Material } from "../material.ts"
11
+
12
+ export type RecordMeshProps = PopulatedMeshProps & {
13
+ geometry: Geometry
14
+ /** Must declare instanceAttributes (shaderMaterialClass), slot 0 only. */
15
+ material: Material
16
+ /** Interleaved per-instance records (stride = the material's instance
17
+ * attributes summed). Reactive; a later array larger than the buffer
18
+ * grows it (capacity doubles into a replacement buffer). */
19
+ records: Float32Array
20
+ /** How many records draw; default all of the latest `records`. */
21
+ count?: number
22
+ /** LOCAL bounds covering every instance ([minX..maxZ]), fixed at
23
+ * creation. Without them the mesh has no picking leaf, so pointer events
24
+ * never target it. */
25
+ bounds?: ArrayLike<number>
26
+ /** Draw into the scene's shadow map (setCastShadow as a prop); default
27
+ * false. Needs a `castShadow` light AND a material class declaring
28
+ * `shadowVertex` (the depth pass with the instance placement) - the
29
+ * shadow views skip a populated mesh without one. */
30
+ castShadow?: boolean
31
+ ref?: (mesh: RecordMeshNode) => void
32
+ }
33
+
34
+ /** One draw entry covering N records: geometry repeated per record of
35
+ * `records` (createRecordMesh as a component, the JS-written population).
36
+ * The record buffer is component-owned and freed on unmount. */
37
+ export let RecordMesh: VoidComponent<RecordMeshProps> = props => {
38
+ let ctx = useContext(SceneContext)
39
+ let mesh = untrack(() =>
40
+ createRecordMesh(props.geometry, props.material, props.records, props.count, { bounds: props.bounds }),
41
+ )
42
+ add(ctx.parent, mesh)
43
+ createEffect(
44
+ () => props.records,
45
+ r => setRecords(mesh, r, untrack(() => props.count)),
46
+ { defer: true },
47
+ )
48
+ createEffect(
49
+ () => props.count,
50
+ c => {
51
+ if (c !== undefined) setRecordCount(mesh, c)
52
+ },
53
+ { defer: true },
54
+ )
55
+ createEffect(
56
+ () => props.geometry,
57
+ g => setGeometry(mesh, g),
58
+ { defer: true },
59
+ )
60
+ createEffect(
61
+ () => props.castShadow,
62
+ c => setCastShadow(mesh, c === true),
63
+ )
64
+ syncMesh(mesh, props)
65
+ untrack(() => props.ref)?.(mesh)
66
+ onCleanup(() => disposeInstances(mesh))
67
+ return null
68
+ }
@@ -0,0 +1,281 @@
1
+ import { createEffect, displayScale, getBoundingBoxViewport, getLayoutBox, onCleanup, onLayout, untrack } from "@solidrt/core"
2
+ import type { Element, ParentComponent, PointerFeed, TextureId } from "@solidrt/core"
3
+ import { SceneContext } from "./context.tsx"
4
+ import { createScene } from "../scene.ts"
5
+ import { feedPointer } from "../scene-pointer.ts"
6
+ import type { EnvironmentOptions, FogOptions, Scene as SceneHandle, SkyboxOptions, ToneMapping } from "../scene.ts"
7
+ import type { ScenePointerEvent, SceneTapEvent, SceneWheelEvent } from "../node.ts"
8
+ import type { CameraUpdate } from "../camera.ts"
9
+
10
+ /**
11
+ * The scene's own pointer events, the root of the walk: every event the
12
+ * nodes let through arrives here last - `event.mesh` is the hit it
13
+ * bubbled from, or null over empty space (a tap there with `mesh` null is
14
+ * "deselect"), `x`/`y` scene pixels. scene.listen as props; an
15
+ * `<OrbitCamera>` child's feed listens at the same root.
16
+ */
17
+ export type ScenePointerProps = {
18
+ onPointerDown?: (event: ScenePointerEvent) => void
19
+ onPointerMove?: (event: ScenePointerEvent) => void
20
+ onPointerUp?: (event: ScenePointerEvent) => void
21
+ onWheel?: (event: SceneWheelEvent) => void
22
+ onTap?: (event: SceneTapEvent) => void
23
+ }
24
+
25
+ export type SceneProps = ScenePointerProps & {
26
+ /**
27
+ * Target pixels - give both, or neither. Omitted, the scene FILLS: the
28
+ * built-in leaf is laid out at 100% of its parent's box (give it a sized
29
+ * parent, as on the web) and the target tracks the leaf's on-screen size
30
+ * in device pixels - display scale, designSize fits and ancestor
31
+ * transforms included - so a bare `<Scene>` renders at native density on
32
+ * any display, and viewport-relative camera controls scale with the box.
33
+ * Fill or fixed is decided at mount. `output` needs explicit sizes (the
34
+ * target cannot follow a leaf it does not own); the leaf's own
35
+ * width/height are then layout, so render size and display size separate
36
+ * (supersampling).
37
+ */
38
+ width?: number
39
+ height?: number
40
+ clearColor?: [number, number, number, number]
41
+ /**
42
+ * Drive the scene camera declaratively (scene.setCamera as a prop): a
43
+ * partial CameraUpdate, absent keys keep their values - `ortho` included,
44
+ * which `<PerspectiveCamera>` by its name never sets. The prop and the
45
+ * `<PerspectiveCamera>` child write the same scene state, so use one
46
+ * form, not both (last write wins). The 2d layers' `camera` prop, one
47
+ * dimension up.
48
+ */
49
+ camera?: CameraUpdate
50
+ /** The background drawn behind the meshes, inside the scene's own pass
51
+ * (scene.setBackground): fragment GLSL (vUV/iResolution/fragColor plus
52
+ * the vRay view ray, so a createShaderTexture backdrop ports verbatim
53
+ * and a directional sky is a few lines) or a skybox `{ cube, intensity?,
54
+ * rotation? }`. Reactive - swapping the source replaces the background,
55
+ * a skybox's knobs update in place; undefined removes it. Three's
56
+ * `scene.background = color` is `clearColor` here. */
57
+ background?: string | SkyboxOptions
58
+ /** The cube map reflective `lit` materials mirror (scene.setEnvironment):
59
+ * `{ cube, intensity?, rotation? }`, typically the skybox's own cube
60
+ * turned with it. Reactive; undefined removes it. */
61
+ environment?: EnvironmentOptions
62
+ /** Scene-wide fog (scene.setFog): linear `{ color, near, far }` or exp2
63
+ * `{ color, density }`, optionally thinning above `height` by
64
+ * `heightFalloff`; every standard material fades toward `color` by
65
+ * distance from the camera. Reactive; undefined removes it. Match
66
+ * `color` to clearColor or the background, which is not fogged. */
67
+ fog?: FogOptions
68
+ /** Output tone mapping (scene.setToneMapping): "none" (default) or
69
+ * "aces". Reactive. */
70
+ toneMapping?: ToneMapping
71
+ /** Output exposure (scene.setExposure), default 1. Reactive. */
72
+ exposure?: number
73
+ /** The scene target's layer mask (scene.setLayers as a prop; default 1):
74
+ * the scene draws the meshes whose `layers` intersect it. Reactive. */
75
+ layers?: number
76
+ /** `"texture"` exposes the target's depth as `scene.depthTexture` (a
77
+ * depth-reading post effect's input). Fixed at creation; not with
78
+ * `samples`. */
79
+ depth?: true | "texture"
80
+ label?: string
81
+ /** Multisample count (1, 2, 4 or 8; default 1): anti-aliased mesh edges.
82
+ * Fixed at creation. */
83
+ samples?: 1 | 2 | 4 | 8
84
+ ref?: (scene: SceneHandle) => void
85
+ /**
86
+ * Compose the output yourself: called once (untracked) with the scene's
87
+ * texture id, and its return renders in place of the built-in `<texture>`
88
+ * leaf - a `<d-texture>`, a leaf carrying paint/pointer/layout props, or
89
+ * a post-effect chain (a shader target sampling the id; created in the
90
+ * callback it disposes with the Scene). Return null to render no leaf.
91
+ * Pointer events then need the scene's handlers on your leaf:
92
+ * `<texture src={texture} {...useScene().scene.handlers} />` - one
93
+ * spread carries the node events, the scene's own and the pointer
94
+ * feed, which listens at the scene's root.
95
+ */
96
+ output?: (texture: TextureId) => Element
97
+ /**
98
+ * Pointer events (default on): the built-in leaf carries scene.handlers,
99
+ * so nodes, the scene's own handlers and a camera control's feed
100
+ * receive input. `false` detaches them - the leaf then costs no pointer
101
+ * routing at all.
102
+ */
103
+ events?: boolean
104
+ /**
105
+ * The pointer feed of the scene's leaf (createPointerFeed), fed from
106
+ * the scene's root - the events the nodes let through: a mesh that
107
+ * claims its press (stopPropagation on its down) keeps a camera control
108
+ * bound to the feed out of that drag. The feed's gestures - drag,
109
+ * pinch, two-finger pan, wheel, mouse motion under lock - come from
110
+ * this scene, and an input map binds them to the camera controls
111
+ * inside; `useScene().pointer` is this feed. Fixed at creation. Without
112
+ * one the leaf feeds no gestures and the controls move only through
113
+ * their handles.
114
+ */
115
+ pointer?: PointerFeed
116
+ }
117
+
118
+ /**
119
+ * Owns a draw target and composites it as an ordinary `<texture>` leaf, so
120
+ * the output takes layout, transforms, blendMode, and pointer events like
121
+ * any element - or hand `output` the texture id and compose it yourself.
122
+ * Children (Mesh/Group/PerspectiveCamera) render nothing themselves - they
123
+ * populate the retained scene through context.
124
+ */
125
+ // Creation size of a fill-mode target: the first onLayout replaces it
126
+ // before the first paint, so it only has to be a valid texture size.
127
+ const FILL_INITIAL_SIZE = 1
128
+
129
+ export let Scene: ParentComponent<SceneProps> = props => {
130
+ // Fill vs fixed target is decided at mount, like `output`: both
131
+ // width and height (fixed pixels) or neither (fill).
132
+ let fill = untrack(() => {
133
+ if ((props.width === undefined) !== (props.height === undefined)) {
134
+ throw new Error("Scene: width and height come together - give both (fixed target) or neither (fill)")
135
+ }
136
+ if (props.width === undefined && props.output) {
137
+ throw new Error("Scene: fill needs the built-in leaf - with output, give width and height")
138
+ }
139
+ return props.width === undefined
140
+ })
141
+ // The initial props seed createScene, so `ref` (below) hands out a
142
+ // configured scene and the first frame draws it whole; the effects
143
+ // after this follow changes only (`defer`).
144
+ let scene = untrack(() => {
145
+ let s = createScene(props.width ?? FILL_INITIAL_SIZE, props.height ?? FILL_INITIAL_SIZE, {
146
+ clearColor: props.clearColor,
147
+ label: props.label,
148
+ samples: props.samples,
149
+ depth: props.depth,
150
+ background: props.background,
151
+ environment: props.environment,
152
+ fog: props.fog,
153
+ toneMapping: props.toneMapping,
154
+ exposure: props.exposure,
155
+ layers: props.layers,
156
+ })
157
+ if (props.camera) s.setCamera(props.camera)
158
+ return s
159
+ })
160
+ createEffect(
161
+ () => [props.width, props.height] as const,
162
+ ([w, h]) => {
163
+ if ((w === undefined) !== (h === undefined) || (w === undefined) !== fill) {
164
+ throw new Error("Scene: fill/fixed is mount-fixed - width/height cannot appear or disappear")
165
+ }
166
+ if (!fill) scene.setSize(w!, h!)
167
+ },
168
+ )
169
+ createEffect(
170
+ () => props.camera,
171
+ camera => {
172
+ if (camera) scene.setCamera(camera)
173
+ },
174
+ { defer: true },
175
+ )
176
+ createEffect(
177
+ () => props.background,
178
+ b => scene.setBackground(b ?? null),
179
+ { defer: true },
180
+ )
181
+ createEffect(
182
+ () => props.environment,
183
+ e => scene.setEnvironment(e ?? null),
184
+ { defer: true },
185
+ )
186
+ createEffect(
187
+ () => props.fog,
188
+ f => scene.setFog(f ?? null),
189
+ { defer: true },
190
+ )
191
+ createEffect(
192
+ () => props.toneMapping,
193
+ t => scene.setToneMapping(t ?? "none"),
194
+ { defer: true },
195
+ )
196
+ createEffect(
197
+ () => props.exposure,
198
+ e => scene.setExposure(e ?? 1),
199
+ { defer: true },
200
+ )
201
+ createEffect(
202
+ () => props.layers,
203
+ l => scene.setLayers(l ?? 1),
204
+ { defer: true },
205
+ )
206
+ untrack(() => props.ref)?.(scene)
207
+ // The pointer feed the app handed in listens at the scene's root, and
208
+ // children reach it through useScene().pointer. Fixed at creation, like
209
+ // output.
210
+ let pointer = untrack(() => props.pointer) ?? null
211
+ if (pointer) onCleanup(feedPointer(scene, pointer))
212
+ // The scene's own handlers at the root of the walk; the props are read
213
+ // per event, so a handler prop may change without re-registering.
214
+ onCleanup(
215
+ scene.listen({
216
+ onPointerDown: e => props.onPointerDown?.(e),
217
+ onPointerMove: e => props.onPointerMove?.(e),
218
+ onPointerUp: e => props.onPointerUp?.(e),
219
+ onWheel: e => props.onWheel?.(e),
220
+ onTap: e => props.onTap?.(e),
221
+ }),
222
+ )
223
+ let output = untrack(() => props.output)
224
+ let events = untrack(() => props.events) !== false
225
+ let leafNode: { id: number } | undefined
226
+ // The built-in leaf's laid-out box in ITS units - what pointer
227
+ // localX/localY report in and every handlersFor scales against. Fixed
228
+ // mode lays the leaf out at the target size; fill mode reads the box
229
+ // back (getLayoutBox, the untransformed read, so a designSize fit or
230
+ // ancestor transform never skews events). Zero before the first layout:
231
+ // no event can arrive before one, and a degenerate layout passes
232
+ // coordinates through unscaled. A custom output leaf registers its own
233
+ // layout via handlersFor.
234
+ let builtinLayout = fill
235
+ ? () => (leafNode && getLayoutBox(leafNode)) || { width: 0, height: 0 }
236
+ : () => ({ width: props.width!, height: props.height! })
237
+ if (fill) {
238
+ // Fill sizing: after every layout (and on display-scale changes, which
239
+ // lay nothing out) the target follows the leaf's on-screen box in
240
+ // device pixels - getBoundingBoxViewport composes designSize fits and
241
+ // ancestor transforms, so the scene renders at true density wherever
242
+ // it sits. onLayout runs before paint (no frame draws at a stale
243
+ // size); setSize no-ops when nothing changed. apply runs as an
244
+ // onLayout handler and as an effect apply, both untracked scopes, so
245
+ // its scale read is wrapped in an explicit untrack (the effect's
246
+ // compute is what tracks it).
247
+ let apply = () =>
248
+ untrack(() => {
249
+ if (!leafNode) return
250
+ let box = getBoundingBoxViewport(leafNode)
251
+ if (!box) return
252
+ let scale = displayScale()
253
+ scene.setSize(Math.max(1, Math.round(box.width * scale)), Math.max(1, Math.round(box.height * scale)))
254
+ })
255
+ onLayout(apply)
256
+ createEffect(() => displayScale(), apply)
257
+ }
258
+ // Pointer events on the built-in leaf: at target size the plain
259
+ // handlers, in fill mode scaled from the laid-out box.
260
+ let sceneHandlers = fill ? scene.handlersFor(builtinLayout) : scene.handlers
261
+ return (
262
+ <SceneContext value={{ scene, parent: scene.root, viewport: scene, pointer }}>
263
+ {output ? (
264
+ untrack(() => output(scene.texture))
265
+ ) : (
266
+ <texture
267
+ ref={(n: { id: number }) => (leafNode = n)}
268
+ src={scene.texture}
269
+ width={fill ? "100%" : props.width}
270
+ height={fill ? "100%" : props.height}
271
+ onPointerDown={events ? sceneHandlers.onPointerDown : undefined}
272
+ onPointerMove={events ? sceneHandlers.onPointerMove : undefined}
273
+ onPointerUp={events ? sceneHandlers.onPointerUp : undefined}
274
+ onPointerLeave={events ? sceneHandlers.onPointerLeave : undefined}
275
+ onWheel={events ? sceneHandlers.onWheel : undefined}
276
+ />
277
+ )}
278
+ {props.children}
279
+ </SceneContext>
280
+ )
281
+ }
@@ -0,0 +1,65 @@
1
+ import { createEffect, onCleanup, untrack, useContext } from "@solidrt/core"
2
+ import type { VoidComponent } from "@solidrt/core"
3
+ import { SceneContext } from "./context.tsx"
4
+ import { syncNode } from "./node-props.ts"
5
+ import type { TransformProps } from "./node-props.ts"
6
+ import { add, remove } from "../node.ts"
7
+ import { createSpotLight, setLight } from "../light.ts"
8
+ import type { SpotLight as SpotLightNode, SpotShadowOptions } from "../light.ts"
9
+ import type { Vec3 } from "../math.ts"
10
+
11
+ export type SpotLightProps = TransformProps & {
12
+ /** Aim direction in the node's local space; default [0, -1, 0], a
13
+ * lamp pointing straight down. */
14
+ direction?: Vec3
15
+ color?: Vec3
16
+ intensity?: number
17
+ /** Falloff cutoff in world units (0 = no cutoff). */
18
+ distance?: number
19
+ /** Cone half-angle in DEGREES, (0, 90]; default 60 (degrees like
20
+ * camera fov; Three's radians convert as `angle * 180 / PI`). */
21
+ angle?: number
22
+ /** 0..1 fraction of the cone fading to the rim; default 0. */
23
+ penumbra?: number
24
+ /** Falloff exponent; default 2 (inverse square). */
25
+ decay?: number
26
+ /** Render a shadow map from this light (a perspective map of its
27
+ * cone; one shadow slot). */
28
+ castShadow?: boolean
29
+ /** Shadow-map options (mapSize, bias, normalBias, near), merged key
30
+ * by key. */
31
+ shadow?: SpotShadowOptions
32
+ ref?: (light: SpotLightNode) => void
33
+ }
34
+
35
+ /** A spot light node (createSpotLight): a cone from the node's world
36
+ * position along its local `direction` - give it a `position`, and aim
37
+ * it with `direction` or a parent's rotation. Counts against MAX_LIGHTS
38
+ * with the other non-ambient lights. */
39
+ export let SpotLight: VoidComponent<SpotLightProps> = props => {
40
+ let ctx = useContext(SceneContext)
41
+ let light = untrack(() =>
42
+ createSpotLight({
43
+ direction: props.direction,
44
+ color: props.color,
45
+ intensity: props.intensity,
46
+ distance: props.distance,
47
+ angle: props.angle,
48
+ penumbra: props.penumbra,
49
+ decay: props.decay,
50
+ castShadow: props.castShadow,
51
+ shadow: props.shadow,
52
+ }),
53
+ )
54
+ add(ctx.parent, light)
55
+ syncNode(light, props)
56
+ createEffect(
57
+ () =>
58
+ [props.direction, props.color, props.intensity, props.distance, props.angle, props.penumbra, props.decay, props.castShadow, props.shadow] as const,
59
+ ([direction, color, intensity, distance, angle, penumbra, decay, castShadow, shadow]) =>
60
+ setLight(light, { direction, color, intensity, distance, angle, penumbra, decay, castShadow, shadow }),
61
+ )
62
+ untrack(() => props.ref)?.(light)
63
+ onCleanup(() => remove(light))
64
+ return null
65
+ }