@opsydyn/effect-three-foldkit 0.6.4 → 1.0.0-next.1

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 (121) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +26 -21
  3. package/dist/boxSelect.d.ts +91 -117
  4. package/dist/boxSelect.d.ts.map +1 -1
  5. package/dist/browser.d.ts +3 -0
  6. package/dist/browser.d.ts.map +1 -0
  7. package/dist/browser.js +32 -0
  8. package/dist/browser.js.map +10 -0
  9. package/dist/element.d.ts +11 -909
  10. package/dist/element.d.ts.map +1 -1
  11. package/dist/index.d.ts +17 -17
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +173 -2565
  14. package/dist/index.js.map +14 -39
  15. package/dist/inspector.d.ts +4 -21
  16. package/dist/inspector.d.ts.map +1 -1
  17. package/dist/measuringTape.d.ts +39 -46
  18. package/dist/measuringTape.d.ts.map +1 -1
  19. package/dist/mount.d.ts +17 -11
  20. package/dist/mount.d.ts.map +1 -1
  21. package/dist/overlayView.d.ts +7 -18
  22. package/dist/overlayView.d.ts.map +1 -1
  23. package/dist/pivotControls.d.ts +64 -76
  24. package/dist/pivotControls.d.ts.map +1 -1
  25. package/dist/transformGizmo.d.ts +113 -125
  26. package/dist/transformGizmo.d.ts.map +1 -1
  27. package/dist/view.d.ts +21 -4
  28. package/dist/view.d.ts.map +1 -1
  29. package/dist/viewportGizmo.d.ts +107 -119
  30. package/dist/viewportGizmo.d.ts.map +1 -1
  31. package/package.json +15 -10
  32. package/src/boxSelect.ts +12 -133
  33. package/src/browser.ts +16 -0
  34. package/src/element.ts +19 -110
  35. package/src/index.ts +32 -16
  36. package/src/inspector.ts +70 -93
  37. package/src/measuringTape.ts +28 -92
  38. package/src/mount.ts +53 -309
  39. package/src/overlayView.ts +36 -57
  40. package/src/pivotControls.ts +8 -94
  41. package/src/transformGizmo.ts +8 -108
  42. package/src/view.ts +73 -54
  43. package/src/viewportGizmo.ts +8 -97
  44. package/dist/assetRegistry.d.ts +0 -49
  45. package/dist/assetRegistry.d.ts.map +0 -1
  46. package/dist/assets.d.ts +0 -66
  47. package/dist/assets.d.ts.map +0 -1
  48. package/dist/dom/animationFrames.d.ts +0 -12
  49. package/dist/dom/animationFrames.d.ts.map +0 -1
  50. package/dist/dom/canvas.d.ts +0 -33
  51. package/dist/dom/canvas.d.ts.map +0 -1
  52. package/dist/dom/latch.d.ts +0 -15
  53. package/dist/dom/latch.d.ts.map +0 -1
  54. package/dist/dom/models.d.ts +0 -10
  55. package/dist/dom/models.d.ts.map +0 -1
  56. package/dist/dom/overlays.d.ts +0 -24
  57. package/dist/dom/overlays.d.ts.map +0 -1
  58. package/dist/dom/pointer.d.ts +0 -49
  59. package/dist/dom/pointer.d.ts.map +0 -1
  60. package/dist/dom/postprocessing.d.ts +0 -22
  61. package/dist/dom/postprocessing.d.ts.map +0 -1
  62. package/dist/dom/property.d.ts +0 -15
  63. package/dist/dom/property.d.ts.map +0 -1
  64. package/dist/dom/reconciled.d.ts +0 -10
  65. package/dist/dom/reconciled.d.ts.map +0 -1
  66. package/dist/dom/renderSettings.d.ts +0 -58
  67. package/dist/dom/renderSettings.d.ts.map +0 -1
  68. package/dist/dom/typedScenes.d.ts +0 -14
  69. package/dist/dom/typedScenes.d.ts.map +0 -1
  70. package/dist/dom/updates.d.ts +0 -8
  71. package/dist/dom/updates.d.ts.map +0 -1
  72. package/dist/dom/viewport.d.ts +0 -40
  73. package/dist/dom/viewport.d.ts.map +0 -1
  74. package/dist/dom/webgl.d.ts +0 -12
  75. package/dist/dom/webgl.d.ts.map +0 -1
  76. package/dist/dom/webgpu.d.ts +0 -24
  77. package/dist/dom/webgpu.d.ts.map +0 -1
  78. package/dist/dom/webgpuPostprocessing.d.ts +0 -4
  79. package/dist/dom/webgpuPostprocessing.d.ts.map +0 -1
  80. package/dist/dom/xr.d.ts +0 -53
  81. package/dist/dom/xr.d.ts.map +0 -1
  82. package/dist/dom/xrGlide.d.ts +0 -49
  83. package/dist/dom/xrGlide.d.ts.map +0 -1
  84. package/dist/dom/xrHub.d.ts +0 -45
  85. package/dist/dom/xrHub.d.ts.map +0 -1
  86. package/dist/dom/xrInputs.d.ts +0 -40
  87. package/dist/dom/xrInputs.d.ts.map +0 -1
  88. package/dist/dom/xrSpaces.d.ts +0 -33
  89. package/dist/dom/xrSpaces.d.ts.map +0 -1
  90. package/dist/dom/xrTarget.d.ts +0 -36
  91. package/dist/dom/xrTarget.d.ts.map +0 -1
  92. package/dist/environment.d.ts +0 -70
  93. package/dist/environment.d.ts.map +0 -1
  94. package/dist/xr.d.ts +0 -34
  95. package/dist/xr.d.ts.map +0 -1
  96. package/src/assetRegistry.ts +0 -218
  97. package/src/assets.ts +0 -208
  98. package/src/dom/animationFrames.ts +0 -32
  99. package/src/dom/canvas.ts +0 -66
  100. package/src/dom/latch.ts +0 -36
  101. package/src/dom/models.ts +0 -37
  102. package/src/dom/overlays.ts +0 -63
  103. package/src/dom/pointer.ts +0 -176
  104. package/src/dom/postprocessing.ts +0 -116
  105. package/src/dom/property.ts +0 -43
  106. package/src/dom/reconciled.ts +0 -51
  107. package/src/dom/renderSettings.ts +0 -117
  108. package/src/dom/typedScenes.ts +0 -21
  109. package/src/dom/updates.ts +0 -14
  110. package/src/dom/viewport.ts +0 -97
  111. package/src/dom/webgl.ts +0 -231
  112. package/src/dom/webgpu.ts +0 -220
  113. package/src/dom/webgpuPostprocessing.ts +0 -102
  114. package/src/dom/xr.ts +0 -211
  115. package/src/dom/xrGlide.ts +0 -114
  116. package/src/dom/xrHub.ts +0 -118
  117. package/src/dom/xrInputs.ts +0 -309
  118. package/src/dom/xrSpaces.ts +0 -287
  119. package/src/dom/xrTarget.ts +0 -71
  120. package/src/environment.ts +0 -83
  121. package/src/xr.ts +0 -36
@@ -1,36 +0,0 @@
1
- /**
2
- * A mounted scene as an immersive session target: its frames handed to the session while
3
- * it presents, and the session's start and end dispatched as `scene-xr` events.
4
- *
5
- * @module
6
- */
7
- import type { GatedFrames, SceneEvent, Xr, XrInput } from '@opsydyn/effect-three';
8
- import type { Object3D } from 'three';
9
- import type { Latch } from './latch.ts';
10
- import type { XrMode, XrTarget } from './xrHub.ts';
11
- import type { Follow, LendGeometry } from './xrSpaces.ts';
12
- /**
13
- * The page's frames for a scene: open while it is visible and no session presents it
14
- * (a session brings its own frames, as React Three Fiber's loop stands aside).
15
- */
16
- export declare const createFrameGate: (frames: GatedFrames) => {
17
- setVisible: (next: boolean) => void;
18
- setPresenting: (next: boolean) => void;
19
- };
20
- export type FrameGate = ReturnType<typeof createFrameGate>;
21
- /** The `scene-xr` event: the mode presenting, or `null` when the session ended. */
22
- export declare const dispatchXrSession: (element: Element, live: Latch, mode: XrMode | null) => void;
23
- /** A scene as a target for the page's immersive sessions. */
24
- export declare const xrTarget: (scene: {
25
- readonly element: Element;
26
- readonly canvas: HTMLCanvasElement;
27
- readonly live: Latch;
28
- readonly gate: FrameGate;
29
- readonly settings: () => Xr | null;
30
- readonly draw: () => void;
31
- readonly scene: Object3D;
32
- readonly follow: Follow;
33
- readonly lend: LendGeometry;
34
- readonly input: (input: XrInput) => ReadonlyArray<SceneEvent>;
35
- }) => XrTarget;
36
- //# sourceMappingURL=xrTarget.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"xrTarget.d.ts","sourceRoot":"","sources":["../../src/dom/xrTarget.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAClF,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE1D;;;GAGG;AACH,eAAO,MAAM,eAAe,WAAY,WAAW;IAK/C,UAAU,SAAS,OAAO,KAAG,IAAI;IAIjC,aAAa,SAAS,OAAO,KAAG,IAAI;CAKvC,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;AAE3D,mFAAmF;AACnF,eAAO,MAAM,iBAAiB,YAAa,OAAO,QAAQ,KAAK,QAAQ,MAAM,GAAG,IAAI,KAAG,IAEtF,CAAC;AAEF,6DAA6D;AAC7D,eAAO,MAAM,QAAQ,UAAW;IAC9B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,IAAI,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,aAAa,CAAC,UAAU,CAAC,CAAC;CAC/D,KAAG,QAkBF,CAAC"}
@@ -1,70 +0,0 @@
1
- /**
2
- * App-wide state shared by every scene element: one GPU resource store and one
3
- * animation-frame scheduler. Create it once at the application entry point.
4
- *
5
- * @module
6
- */
7
- import { type Behaviour, type LabelEngine, type PhysicsEngine, type RendererFactory, type ResourceStore } from '@opsydyn/effect-three';
8
- import { type AnimationFrameHost } from './dom/animationFrames.ts';
9
- import { type PixelRatio } from './dom/viewport.ts';
10
- /** The browser APIs the adapter uses; normally `window`. */
11
- export type EnvironmentHost = AnimationFrameHost & Pick<Window, 'matchMedia' | 'devicePixelRatio'> & Partial<Pick<Window, 'navigator'>>;
12
- export type EnvironmentOptions = {
13
- /** Creates each scene's renderer from its canvas. Defaults to WebGL2. */
14
- readonly renderer?: (canvas: HTMLCanvasElement) => RendererFactory;
15
- /** Drawing-buffer pixel ratio: fixed, or `[min, max]` around the device's. Default `[1, 2]`. */
16
- readonly pixelRatio?: PixelRatio;
17
- /** Behaviours scenes may name with `behave(name)`, beside the built-in `float`. */
18
- readonly behaviours?: Readonly<Record<string, Behaviour>>;
19
- /**
20
- * The physics engine for scenes with `physics`, or the promise of one: pass
21
- * `loadRapier()` from `@opsydyn/effect-three-rapier` as it is, and scenes start once it
22
- * has loaded. Without one, bodies stay where they are described.
23
- */
24
- readonly physics?: PhysicsEngine | Promise<PhysicsEngine>;
25
- /**
26
- * Draws `label` nodes: pass `troikaLabels()` from `@opsydyn/effect-three-troika`.
27
- * Without one, labels are empty.
28
- */
29
- readonly labels?: LabelEngine;
30
- };
31
- /** Creates the shared environment for `host`. Call `dispose` when the app shuts down. */
32
- export declare const makeEnvironment: (host: EnvironmentHost, options?: EnvironmentOptions) => {
33
- host: EnvironmentHost;
34
- store: ResourceStore;
35
- frames: import("@opsydyn/effect-three").FrameScheduler;
36
- renderer: (canvas: HTMLCanvasElement) => RendererFactory;
37
- pixelRatio: PixelRatio;
38
- behaviours: Readonly<Record<string, Behaviour>>;
39
- /** The physics engine, once loaded; `undefined` when there is none. */
40
- physics: Promise<PhysicsEngine | undefined>;
41
- /** The label engine; `undefined` when there is none. */
42
- labels: LabelEngine | undefined;
43
- /** Loads textures and glTF models by URL and lends them to the store. */
44
- assets: {
45
- loadTexture: (id: string, url: string) => import("effect/Effect").Effect<string, import("./assets.ts").AssetLoadError, never>;
46
- loadModel: (id: string, url: string) => import("effect/Effect").Effect<import("./assets.ts").ModelInfo, import("./assets.ts").AssetLoadError, never>;
47
- loadEnvironment: (id: string, url: string) => import("effect/Effect").Effect<string, import("./assets.ts").AssetLoadError, never>;
48
- loadFont: (id: string, url: string) => import("effect/Effect").Effect<string, import("./assets.ts").AssetLoadError, never>;
49
- unload: (id: string) => import("effect/Effect").Effect<void, never, never>;
50
- dispose: () => void;
51
- };
52
- /** The assets scenes ask for in their descriptions: loaded, shared, cancelled, freed. */
53
- assetRegistry: {
54
- want: (holder: object, assets: ReadonlyArray<import("@opsydyn/effect-three").Asset>, notify: (notice: import("./assetRegistry.ts").AssetNotice) => void) => void;
55
- release: (holder: object) => void;
56
- dispose: () => void;
57
- };
58
- /** Enters and leaves immersive (WebXR) sessions, from Commands. */
59
- xr: {
60
- supported: (mode: import("./index.ts").XrMode) => import("effect/Effect").Effect<boolean, never, never>;
61
- enter: (mode: import("./index.ts").XrMode) => import("effect/Effect").Effect<void, import("./xr.ts").XrUnavailable, never>;
62
- exit: import("effect/Effect").Effect<void, never, never>;
63
- };
64
- /** The page's presentable scenes and its session; scene mounts register here. */
65
- xrHub: import("./dom/xrHub.ts").XrHub;
66
- /** Disposes every loaded asset and every GPU resource still held. */
67
- dispose: () => void;
68
- };
69
- export type Environment = ReturnType<typeof makeEnvironment>;
70
- //# sourceMappingURL=environment.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../src/environment.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EACL,KAAK,SAAS,EAEd,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,aAAa,EACnB,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAA2B,KAAK,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC5F,OAAO,EAAqB,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAKvE,4DAA4D;AAC5D,MAAM,MAAM,eAAe,GAAG,kBAAkB,GAC9C,IAAI,CAAC,MAAM,EAAE,YAAY,GAAG,kBAAkB,CAAC,GAC/C,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAErC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,yEAAyE;IACzE,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,KAAK,eAAe,CAAC;IACnE,gGAAgG;IAChG,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC,mFAAmF;IACnF,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IAC1D;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAC1D;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B,CAAC;AAEF,yFAAyF;AACzF,eAAO,MAAM,eAAe,SAAU,eAAe,YAAW,kBAAkB;;;;uBAnBnD,iBAAiB,KAAK,eAAe;;;IA+BhE,uEAAuE;;IAEvE,wDAAwD;;IAExD,yEAAyE;;;;;;;;;IAEzE,yFAAyF;;;;;;IAEzF,mEAAmE;;;;;;IAEnE,iFAAiF;;IAEjF,qEAAqE;;CAOxE,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC"}
package/dist/xr.d.ts DELETED
@@ -1,34 +0,0 @@
1
- /**
2
- * Immersive sessions as Effects an application runs from Foldkit Commands: whether a mode
3
- * is supported, entering it from a user gesture, and leaving it. The scene presented is
4
- * the mounted one whose description has `xr`; while presenting, the session drives its
5
- * frames and the view's `onXRSession` reports the session starting and ending.
6
- *
7
- * @module
8
- */
9
- import { Effect } from 'effect';
10
- import type { XrHub, XrMode } from './dom/xrHub.ts';
11
- declare const XrUnavailable_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
12
- readonly _tag: "XrUnavailable";
13
- } & Readonly<A>;
14
- /** A session could not start: no WebXR, no scene describing `xr`, or the request refused. */
15
- export declare class XrUnavailable extends XrUnavailable_base<{
16
- readonly mode: XrMode;
17
- readonly cause: unknown;
18
- }> {
19
- }
20
- /** The immersive session controls for an environment's hub. */
21
- export declare const makeXr: (hub: XrHub) => {
22
- /** Whether the browser can present `mode` (false without WebXR). */
23
- supported: (mode: XrMode) => Effect.Effect<boolean, never, never>;
24
- /**
25
- * Enters `mode`, presenting the mounted scene that describes `xr`. Run it from the
26
- * Command a click (or other user gesture) produces: browsers require one.
27
- */
28
- enter: (mode: XrMode) => Effect.Effect<void, XrUnavailable, never>;
29
- /** Ends the session, if there is one. */
30
- exit: Effect.Effect<void, never, never>;
31
- };
32
- export type XrControls = ReturnType<typeof makeXr>;
33
- export {};
34
- //# sourceMappingURL=xr.d.ts.map
package/dist/xr.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"xr.d.ts","sourceRoot":"","sources":["../src/xr.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAQ,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;;;;AAEpD,6FAA6F;AAC7F,qBAAa,aAAc,SAAQ,mBAAkC;IACnE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB,CAAC;CAAG;AAEL,+DAA+D;AAC/D,eAAO,MAAM,MAAM,QAAS,KAAK;IAC/B,oEAAoE;IACpE,SAAS,SAAS,MAAM;IACxB;;;OAGG;IACH,KAAK,SAAS,MAAM;IAKpB,yCAAyC;IACzC,IAAI;CACJ,CAAC;AAEH,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,MAAM,CAAC,CAAC"}
@@ -1,218 +0,0 @@
1
- /**
2
- * The assets scenes ask for with `scene({ assets })` (ADR-015), held for the environment:
3
- * each loaded once however many scenes ask, lent to the store under its id, its load
4
- * cancelled when no scene asks for it any more, and withdrawn and disposed when the last
5
- * scene stops asking. Each scene hears whether what it asked for loaded or failed.
6
- *
7
- * An asset with coarser `levels` streams in: every level loads at once, each is lent as it
8
- * arrives if it is finer than what is shown (replacing it), and once the finest is shown
9
- * the coarser loads still under way are cancelled. Only the finest failing fails it.
10
- *
11
- * An id names one asset at a time: a scene asking for an id another scene holds as
12
- * something else (another kind or URL) is told it failed, and gets it once the other lets
13
- * go.
14
- *
15
- * @module
16
- */
17
- import { type Asset, assetsEqual } from '@opsydyn/effect-three';
18
-
19
- /** An asset as loaded and lent: what a model offers, and how to withdraw and free it. */
20
- export type Lent = {
21
- readonly parts: ReadonlyArray<string>;
22
- readonly clips: ReadonlyArray<string>;
23
- readonly release: () => void;
24
- };
25
-
26
- /** Loads one asset and lends it under its id; gives up (rejecting) when `signal` aborts. */
27
- export type AssetLoader = (asset: Asset, signal: AbortSignal) => Promise<Lent>;
28
-
29
- /**
30
- * What a scene hears about an asset it asked for: a level of detail shown (0 for the
31
- * coarsest of its levels, `levels.length` for its URL, the finest), or its finest failed.
32
- */
33
- export type AssetNotice =
34
- | ({
35
- readonly _tag: 'Loaded';
36
- readonly level: number;
37
- readonly final: boolean;
38
- } & Asset &
39
- Pick<Lent, 'parts' | 'clips'>)
40
- | ({ readonly _tag: 'Failed'; readonly reason: string } & Asset);
41
-
42
- /** Who asks: a mounted scene, by any object that stands for it. */
43
- type Holder = object;
44
-
45
- type Notify = (notice: AssetNotice) => void;
46
-
47
- type Entry = {
48
- readonly asset: Asset;
49
- readonly holders: Set<Holder>;
50
- /** One a level, coarsest first: aborted once a finer level is shown, or the entry ends. */
51
- readonly controllers: ReadonlyArray<AbortController>;
52
- /** The finest level lent so far. */
53
- shown: { readonly level: number; readonly lent: Lent } | undefined;
54
- /** Why the finest level could not be loaded, once it could not. */
55
- failure: string | undefined;
56
- };
57
-
58
- const sameAsset = (a: Asset, b: Asset): boolean =>
59
- a.kind === b.kind &&
60
- a.url === b.url &&
61
- a.levels.length === b.levels.length &&
62
- a.levels.every((level, i) => level === b.levels[i]);
63
-
64
- /** Every level's URL, coarsest first: the asset's own URL is the last, and finest. */
65
- const urlsOf = (asset: Asset): ReadonlyArray<string> => [...asset.levels, asset.url];
66
-
67
- const reasonOf = (asset: Asset, cause: unknown): string =>
68
- cause instanceof Error && cause.message !== ''
69
- ? `Could not load ${asset.url}: ${cause.message}`
70
- : `Could not load ${asset.url}`;
71
-
72
- const taken = (asset: Asset, holding: Asset): AssetNotice => ({
73
- _tag: 'Failed',
74
- ...asset,
75
- reason: `"${asset.id}" is already ${holding.url} for another scene`,
76
- });
77
-
78
- /** Creates the registry for one environment, loading with `load`. */
79
- export const makeAssetRegistry = (load: AssetLoader) => {
80
- const entries = new Map<string, Entry>();
81
- /** What each scene asks for now, and how to tell it. */
82
- const asking = new Map<
83
- Holder,
84
- { readonly assets: ReadonlyArray<Asset>; readonly notify: Notify }
85
- >();
86
-
87
- const tellAll = (entry: Entry, notice: AssetNotice): void => {
88
- for (const holder of entry.holders) asking.get(holder)?.notify(notice);
89
- };
90
-
91
- const loadedNotice = (entry: Entry, level: number, lent: Lent): AssetNotice => ({
92
- _tag: 'Loaded',
93
- ...entry.asset,
94
- level,
95
- final: level === entry.asset.levels.length,
96
- parts: lent.parts,
97
- clips: lent.clips,
98
- });
99
-
100
- /** What a scene that starts holding an entry hears at once: what is shown, and a failure. */
101
- const noticesOf = (entry: Entry): ReadonlyArray<AssetNotice> => [
102
- ...(entry.shown === undefined
103
- ? []
104
- : [loadedNotice(entry, entry.shown.level, entry.shown.lent)]),
105
- ...(entry.failure === undefined
106
- ? []
107
- : [{ _tag: 'Failed' as const, ...entry.asset, reason: entry.failure }]),
108
- ];
109
-
110
- /** Starts loading every level of `asset`; what comes back too late is freed unseen. */
111
- const start = (asset: Asset): Entry => {
112
- const urls = urlsOf(asset);
113
- const finest = urls.length - 1;
114
- const entry: Entry = {
115
- asset,
116
- holders: new Set(),
117
- controllers: urls.map(() => new AbortController()),
118
- shown: undefined,
119
- failure: undefined,
120
- };
121
- entries.set(asset.id, entry);
122
- function current(level: number): boolean {
123
- return entries.get(asset.id) === entry && entry.controllers[level]?.signal.aborted === false;
124
- }
125
- function loaded(level: number) {
126
- return (lent: Lent): void => {
127
- if (!current(level) || (entry.shown !== undefined && entry.shown.level >= level)) {
128
- lent.release();
129
- return;
130
- }
131
- // Lent first, then the coarser one freed: its withdrawal leaves the new loan.
132
- const before = entry.shown;
133
- entry.shown = { level, lent };
134
- before?.lent.release();
135
- if (level === finest)
136
- for (const coarser of entry.controllers.slice(0, level)) coarser.abort();
137
- tellAll(entry, loadedNotice(entry, level, lent));
138
- };
139
- }
140
- function failed(level: number) {
141
- return (cause: unknown): void => {
142
- // A coarser level that fails is skipped; only the finest failing fails the asset.
143
- if (!current(level) || level !== finest) return;
144
- const reason = reasonOf({ ...asset, url: urls[level] ?? asset.url }, cause);
145
- entry.failure = reason;
146
- tellAll(entry, { _tag: 'Failed', ...asset, reason });
147
- };
148
- }
149
- urls.forEach((url, level) => {
150
- const signal = entry.controllers[level]?.signal ?? AbortSignal.abort();
151
- load({ ...asset, url }, signal).then(loaded(level), failed(level));
152
- });
153
- return entry;
154
- };
155
-
156
- /** Ends an entry: its loads cancelled, and what it lent withdrawn and freed. */
157
- const end = (entry: Entry): void => {
158
- entries.delete(entry.asset.id);
159
- for (const controller of entry.controllers) controller.abort();
160
- entry.shown?.lent.release();
161
- };
162
-
163
- /** `holder` lets go of `id`; the last to let go ends it, and whoever waited on it asks again. */
164
- const letGo = (holder: Holder, id: string): void => {
165
- const entry = entries.get(id);
166
- if (entry === undefined || !entry.holders.delete(holder) || entry.holders.size > 0) return;
167
- end(entry);
168
- for (const [waiting, { assets }] of asking) {
169
- if (assets.some((asset) => asset.id === id)) hold(waiting, assets);
170
- }
171
- };
172
-
173
- /** `holder` takes each of `assets` it does not hold yet. */
174
- const hold = (holder: Holder, assets: ReadonlyArray<Asset>): void => {
175
- for (const asset of assets) {
176
- const entry = entries.get(asset.id) ?? start(asset);
177
- if (!sameAsset(entry.asset, asset)) {
178
- asking.get(holder)?.notify(taken(asset, entry.asset));
179
- continue;
180
- }
181
- if (entry.holders.has(holder)) continue;
182
- entry.holders.add(holder);
183
- for (const notice of noticesOf(entry)) asking.get(holder)?.notify(notice);
184
- }
185
- };
186
-
187
- /**
188
- * What `holder` asks for now: loads what is new, lets go of what it no longer asks for
189
- * (or asks for as something else), and tells it, through `notify`, when each asset it
190
- * holds has loaded or failed (at once, for one loaded already).
191
- */
192
- const want = (holder: Holder, assets: ReadonlyArray<Asset>, notify: Notify): void => {
193
- const before = asking.get(holder);
194
- asking.set(holder, { assets, notify });
195
- if (before !== undefined && assetsEqual(before.assets, assets)) return;
196
- for (const old of before?.assets ?? []) {
197
- const still = assets.find((asset) => asset.id === old.id);
198
- if (still === undefined || !sameAsset(still, old)) letGo(holder, old.id);
199
- }
200
- hold(holder, assets);
201
- };
202
-
203
- /** `holder` (a scene going away) asks for nothing any more. */
204
- const release = (holder: Holder): void => {
205
- want(holder, [], () => undefined);
206
- asking.delete(holder);
207
- };
208
-
209
- /** Ends every load and frees every asset (the environment going away). */
210
- const dispose = (): void => {
211
- asking.clear();
212
- for (const entry of [...entries.values()]) end(entry);
213
- };
214
-
215
- return { want, release, dispose };
216
- };
217
-
218
- export type AssetRegistry = ReturnType<typeof makeAssetRegistry>;
package/src/assets.ts DELETED
@@ -1,208 +0,0 @@
1
- /**
2
- * Loading textures, glTF models, HDR panoramas and typeface fonts by URL. Each asset is
3
- * lent to the shared resource store under an id: materials use a texture with `map: id`,
4
- * a `borrowed({ id })` node shows a model, `environment({ map: id })` a panorama, and
5
- * `text({ font: id })` geometry draws with a font.
6
- *
7
- * Two ways in. A scene can ask for assets in its description (`scene({ assets })`), and
8
- * the environment's registry loads, shares, cancels and frees them as scenes ask
9
- * (`assetLoader` is what it loads with; ADR-015). Or an application loads one with an
10
- * Effect from a Command and settles it into `AsyncData`; the environment owns what it
11
- * loads that way, loading an id again replaces and disposes the earlier asset, and
12
- * `unload` or the environment's `dispose` frees it. Use one way for any one id.
13
- *
14
- * @module
15
- */
16
- import type { Asset, AssetKind, ResourceStore } from '@opsydyn/effect-three';
17
- import { Data, Effect } from 'effect';
18
- import {
19
- EquirectangularReflectionMapping,
20
- LoadingManager,
21
- type Object3D,
22
- SRGBColorSpace,
23
- type Texture,
24
- TextureLoader,
25
- } from 'three';
26
- import { type Font, FontLoader } from 'three/addons/loaders/FontLoader.js';
27
- import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
28
- import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
29
-
30
- import type { AssetLoader, Lent } from './assetRegistry.ts';
31
- import { disposeModel, namesIn } from './dom/models.ts';
32
-
33
- /** An asset could not be fetched or decoded. */
34
- export class AssetLoadError extends Data.TaggedError('AssetLoadError')<{
35
- readonly url: string;
36
- readonly cause: unknown;
37
- }> {}
38
-
39
- /** What a loaded model offers: named parts to match hits against, and animation clips. */
40
- export type ModelInfo = {
41
- readonly id: string;
42
- /** Names of the objects inside the model, as hits report them in `part`. */
43
- readonly parts: ReadonlyArray<string>;
44
- /** Names of the model's animation clips. */
45
- readonly clips: ReadonlyArray<string>;
46
- };
47
-
48
- type Gltf = { readonly scene: Object3D; readonly animations: Object3D['animations'] };
49
-
50
- const nothing: ReadonlyArray<string> = [];
51
-
52
- /** What lending an asset gives back: no parts or clips, and how to withdraw and free it. */
53
- const plain = (release: () => void): Lent => ({ parts: nothing, clips: nothing, release });
54
-
55
- /** Lends a colour texture (sRGB). */
56
- const lentTexture = (store: ResourceStore, id: string, texture: Texture): Lent => {
57
- texture.colorSpace = SRGBColorSpace;
58
- const withdraw = store.lendTexture(id, texture);
59
- return plain(() => {
60
- withdraw();
61
- texture.dispose();
62
- });
63
- };
64
-
65
- /** Lends a model's scene, keeping its clips with it so a borrowed node can play them. */
66
- const lentModel = (store: ResourceStore, id: string, gltf: Gltf): Lent => {
67
- gltf.scene.animations = gltf.animations;
68
- const withdraw = store.lend(id, gltf.scene);
69
- return {
70
- parts: namesIn(gltf.scene),
71
- clips: gltf.animations.map((clip) => clip.name),
72
- release: () => {
73
- withdraw();
74
- disposeModel(gltf.scene);
75
- },
76
- };
77
- };
78
-
79
- /** Lends an HDR panorama for `environment({ map })`: linear, mapped for reflection. */
80
- const lentEnvironment = (store: ResourceStore, id: string, texture: Texture): Lent => {
81
- texture.mapping = EquirectangularReflectionMapping;
82
- const withdraw = store.lendTexture(id, texture);
83
- return plain(() => {
84
- withdraw();
85
- texture.dispose();
86
- });
87
- };
88
-
89
- /** Lends a font; fonts hold no GPU resources, so withdrawing the loan frees them. */
90
- const lentFont = (store: ResourceStore, id: string, font: Font): Lent =>
91
- plain(store.lendFont(id, font));
92
-
93
- type LoadAndLend = (store: ResourceStore, asset: Asset, manager: LoadingManager) => Promise<Lent>;
94
-
95
- /** How each kind of asset loads, with a loading manager of its own, and is lent. */
96
- const loadAndLend = {
97
- model: async (store, { id, url }, manager) =>
98
- lentModel(store, id, await new GLTFLoader(manager).loadAsync(url)),
99
- texture: async (store, { id, url }, manager) =>
100
- lentTexture(store, id, await new TextureLoader(manager).loadAsync(url)),
101
- environment: async (store, { id, url }, manager) =>
102
- lentEnvironment(store, id, await new HDRLoader(manager).loadAsync(url)),
103
- font: async (store, { id, url }, manager) =>
104
- lentFont(store, id, await new FontLoader(manager).loadAsync(url)),
105
- } satisfies Record<AssetKind, LoadAndLend>;
106
-
107
- /**
108
- * What the environment's registry loads scenes' assets with: three's loaders, each load
109
- * with a loading manager of its own, so aborting it cancels its requests (three's file
110
- * and image-bitmap loaders honour the manager's abort).
111
- */
112
- export const assetLoader =
113
- (store: ResourceStore): AssetLoader =>
114
- (asset, signal) => {
115
- const manager = new LoadingManager();
116
- signal.addEventListener('abort', () => manager.abort(), { once: true });
117
- return loadAndLend[asset.kind](store, asset, manager);
118
- };
119
-
120
- /** Creates the asset loader for a store. One per environment. */
121
- export const makeAssets = (store: ResourceStore) => {
122
- const releases = new Map<string, () => void>();
123
-
124
- /** Takes ownership of an asset under `id`, first releasing whatever was there. */
125
- const own = (id: string, release: () => void): void => {
126
- releases.get(id)?.();
127
- releases.set(id, release);
128
- };
129
-
130
- const lendTexture = (id: string) => (texture: Texture) => {
131
- own(id, lentTexture(store, id, texture).release);
132
- return id;
133
- };
134
-
135
- const lendModel = (id: string) => (gltf: Gltf) => {
136
- const lent = lentModel(store, id, gltf);
137
- own(id, lent.release);
138
- const info: ModelInfo = { id, parts: lent.parts, clips: lent.clips };
139
- return info;
140
- };
141
-
142
- const lendEnvironment = (id: string) => (texture: Texture) => {
143
- own(id, lentEnvironment(store, id, texture).release);
144
- return id;
145
- };
146
-
147
- const lendFont = (id: string) => (font: Font) => {
148
- own(id, lentFont(store, id, font).release);
149
- return id;
150
- };
151
-
152
- const releaseAll = (): void => {
153
- for (const release of releases.values()) release();
154
- releases.clear();
155
- };
156
-
157
- return {
158
- /** Loads a colour texture (sRGB) and lends it under `id`. Succeeds with the id. */
159
- loadTexture: (id: string, url: string) => {
160
- const load = Effect.tryPromise({
161
- try: () => new TextureLoader().loadAsync(url),
162
- catch: (cause) => new AssetLoadError({ url, cause }),
163
- });
164
- return Effect.map(load, lendTexture(id));
165
- },
166
- /** Loads a glTF or GLB model and lends its scene under `id`, with its clips. */
167
- loadModel: (id: string, url: string) => {
168
- const load = Effect.tryPromise({
169
- try: () => new GLTFLoader().loadAsync(url),
170
- catch: (cause) => new AssetLoadError({ url, cause }),
171
- });
172
- return Effect.map(load, lendModel(id));
173
- },
174
- /**
175
- * Loads an equirectangular HDR panorama (`.hdr`, three.js's `HDRLoader`) and lends it
176
- * under `id` for `environment({ map: id })`. Succeeds with the id. Image panoramas
177
- * load with `loadTexture`; the scene maps them for reflection.
178
- */
179
- loadEnvironment: (id: string, url: string) => {
180
- const load = Effect.tryPromise({
181
- try: () => new HDRLoader().loadAsync(url),
182
- catch: (cause) => new AssetLoadError({ url, cause }),
183
- });
184
- return Effect.map(load, lendEnvironment(id));
185
- },
186
- /**
187
- * Loads a typeface JSON font (three.js's `FontLoader` format, as Drei's `Text3D` takes)
188
- * and lends it under `id`. Succeeds with the id.
189
- */
190
- loadFont: (id: string, url: string) => {
191
- const load = Effect.tryPromise({
192
- try: () => new FontLoader().loadAsync(url),
193
- catch: (cause) => new AssetLoadError({ url, cause }),
194
- });
195
- return Effect.map(load, lendFont(id));
196
- },
197
- /** Withdraws and disposes the asset loaded under `id`, if any. */
198
- unload: (id: string) =>
199
- Effect.sync(() => {
200
- releases.get(id)?.();
201
- releases.delete(id);
202
- }),
203
- /** Withdraws and disposes every loaded asset. */
204
- dispose: releaseAll,
205
- };
206
- };
207
-
208
- export type Assets = ReturnType<typeof makeAssets>;
@@ -1,32 +0,0 @@
1
- /**
2
- * A `requestAnimationFrame` scheduler shared by every scene on the page: one browser
3
- * callback per frame, running only while at least one scene is subscribed.
4
- *
5
- * @module
6
- */
7
- import type { FrameScheduler } from '@opsydyn/effect-three';
8
-
9
- /** The part of `Window` the scheduler needs. */
10
- export type AnimationFrameHost = Pick<Window, 'requestAnimationFrame' | 'cancelAnimationFrame'>;
11
-
12
- /** Creates a shared animation-frame scheduler for `host` (normally `window`). */
13
- export const animationFrameScheduler = (host: AnimationFrameHost): FrameScheduler => {
14
- const callbacks = new Set<() => void>();
15
- let handle: number | undefined;
16
- const tick = (): void => {
17
- handle = host.requestAnimationFrame(tick);
18
- for (const onFrame of Array.from(callbacks)) onFrame();
19
- };
20
- return {
21
- subscribe: (onFrame) => {
22
- callbacks.add(onFrame);
23
- handle ??= host.requestAnimationFrame(tick);
24
- return () => {
25
- callbacks.delete(onFrame);
26
- if (callbacks.size > 0 || handle === undefined) return;
27
- host.cancelAnimationFrame(handle);
28
- handle = undefined;
29
- };
30
- },
31
- };
32
- };