diff --git a/package.json b/package.json index dcfcd92..08bfe9f 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "@nanoforge-dev/utils-eslint-config": "catalog:lint", "@nanoforge-dev/utils-prettier-config": "catalog:lint", "@trivago/prettier-plugin-sort-imports": "catalog:lint", + "@types/three": "catalog:core", "@vitest/coverage-v8": "catalog:test", "eslint": "catalog:lint", "husky": "catalog:ci", diff --git a/packages/graphics-3d/README.md b/packages/graphics-3d/README.md index 59f06ac..2a3128b 100644 --- a/packages/graphics-3d/README.md +++ b/packages/graphics-3d/README.md @@ -13,6 +13,8 @@ peer `three`, and registers `Graphics3DLibrary` in the client's `main.ts`. library's camera at `(0, 0, 5)` looking at the origin. - `Object3DComponent`: any Three.js object you built, such as an `InstancedMesh` for many identical objects. It moves with the transform components like the shapes. +- `Model3D`: a `.glb`/`.gltf` model, loaded in the background. A missing or broken file logs an + error and shows a magenta box. - `draw3D`: gives each component its Three.js object and keeps it up to date. A removed component, or a killed entity, loses its object, and its geometries, materials and textures are disposed. diff --git a/packages/graphics-3d/components/model-3d.ts b/packages/graphics-3d/components/model-3d.ts new file mode 100644 index 0000000..968ea97 --- /dev/null +++ b/packages/graphics-3d/components/model-3d.ts @@ -0,0 +1,25 @@ +import "@nanoforge-dev/graphics-3d/three"; + +/** + * Shows a 3D model from a `.glb` or `.gltf` file. Needs the `draw3D` system. + * + * @remarks + * The model loads in the background: the game starts at once and the model appears when it is + * ready. A missing or broken file logs an error and shows a magenta box instead. Move, turn and + * resize it with `Position3D`, `Rotation3D` and `Scale3D`. + * + * @example + * `new Model3D("/models/duck.glb")` with a `Position3D`, and a `Light3D` to see its colors. + * + * @component + * @side client + * @group Model color=#ff8a3d - The model file. + */ +export class Model3D { + name = "Model3D"; + + constructor( + /** The model file. @group Model @asset .glb .gltf */ + public path = "", + ) {} +} diff --git a/packages/graphics-3d/model-loader.ts b/packages/graphics-3d/model-loader.ts new file mode 100644 index 0000000..ecb9799 --- /dev/null +++ b/packages/graphics-3d/model-loader.ts @@ -0,0 +1,23 @@ +import type { Context } from "@nanoforge-dev/common"; +import { BoxGeometry, type Group, Mesh, MeshBasicMaterial } from "@nanoforge-dev/graphics-3d/three"; +import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; + +import { disposeObject3D } from "./object-3d"; + +/** + * Loads the `.glb`/`.gltf` model at `path` into `group`, in the background: it never blocks and + * never throws. A missing or broken file logs an error and puts a magenta box in the group. + * + * @remarks + * Call it after the group is in the scene: a load that ends once the group has no parent (its + * component was removed) adds nothing and disposes what it loaded. + */ +export const loadModel3D = (group: Group, path: string, assets: Context["assets"]) => + Promise.resolve() + .then(() => new GLTFLoader().loadAsync(assets.getAsset(path).path)) + .then(({ scene }) => (group.parent ? group.add(scene) : disposeObject3D(scene))) + .catch((error: unknown) => { + console.error(`No 3D model at "${path}":`, error); + if (group.parent) + group.add(new Mesh(new BoxGeometry(), new MeshBasicMaterial({ color: "#ff00ff" }))); + }); diff --git a/packages/graphics-3d/nanoforge.manifest.json b/packages/graphics-3d/nanoforge.manifest.json index e4a0bf9..65876d2 100644 --- a/packages/graphics-3d/nanoforge.manifest.json +++ b/packages/graphics-3d/nanoforge.manifest.json @@ -1,8 +1,20 @@ { "type": "package", "name": "@nanoforge/graphics-3d", - "description": "Show entities in 3D without Three.js: boxes, spheres and planes of a color, lights, a camera, or any Three.js object, placed by the 3D transform.", - "keywords": ["graphics", "3d", "three", "box", "sphere", "plane", "light", "camera", "draw"], + "description": "Show entities in 3D without Three.js: boxes, spheres and planes of a color, lights, a camera, glTF models, or any Three.js object, placed by the 3D transform.", + "keywords": [ + "graphics", + "3d", + "three", + "box", + "sphere", + "plane", + "light", + "camera", + "model", + "gltf", + "draw" + ], "license": "MIT", "suggestedPlugins": ["@nanoforge/ecs"], "dependencies": { "@nanoforge/basics-3d": "^1.0.0" }, diff --git a/packages/graphics-3d/object-3d.ts b/packages/graphics-3d/object-3d.ts index 900265c..2d99b02 100644 --- a/packages/graphics-3d/object-3d.ts +++ b/packages/graphics-3d/object-3d.ts @@ -5,6 +5,7 @@ import { type Color, DirectionalLight, DoubleSide, + Group, Light, MathUtils, Mesh, @@ -20,6 +21,7 @@ import { import type { Box3D } from "./components/box-3d"; import type { Camera3D } from "./components/camera-3d"; import type { Light3D } from "./components/light-3d"; +import type { Model3D } from "./components/model-3d"; import type { Object3DComponent } from "./components/object-3d-component"; import type { Plane3D } from "./components/plane-3d"; import type { Sphere3D } from "./components/sphere-3d"; @@ -36,7 +38,8 @@ export type Params3D = | ShapeParams | Params | Params - | Params; + | Params + | Params; /** A point or a vector on three axes, like `Position3D`. */ export interface Xyz { @@ -66,6 +69,10 @@ export const toObject3D = (params: Params3D, previous?: Object3D): Object3D => { return cameraFor(params, previous); case "Object3DComponent": return params.object; + case "Model3D": // an empty group that draw3D fills; a new path gets a new group, so it reloads + return previous?.userData.path === params.path + ? previous + : Object.assign(new Group(), { userData: { path: params.path } }); } }; diff --git a/packages/graphics-3d/systems/draw-3d.ts b/packages/graphics-3d/systems/draw-3d.ts index 6813713..cd3b1d3 100644 --- a/packages/graphics-3d/systems/draw-3d.ts +++ b/packages/graphics-3d/systems/draw-3d.ts @@ -16,9 +16,11 @@ import { Scale3D } from "@nanoforge/basics-3d/components/scale-3d"; import { Box3D } from "../components/box-3d"; import { Camera3D } from "../components/camera-3d"; import { Light3D } from "../components/light-3d"; +import { Model3D } from "../components/model-3d"; import { Object3DComponent } from "../components/object-3d-component"; import { Plane3D } from "../components/plane-3d"; import { Sphere3D } from "../components/sphere-3d"; +import { loadModel3D } from "../model-loader"; import { type Params3D, applyTransform3D, disposeObject3D, toObject3D } from "../object-3d"; /** What `draw3D` added to one app's scene. */ @@ -32,7 +34,7 @@ interface Shown { const shownIn = new WeakMap(); /** The components `draw3D` shows, by the key the ECS gives them in a zipper. */ -const KINDS = { Box3D, Sphere3D, Plane3D, Light3D, Camera3D, Object3DComponent }; +const KINDS = { Box3D, Sphere3D, Plane3D, Light3D, Camera3D, Object3DComponent, Model3D }; const defaultLight = () => { const sun = new DirectionalLight(0xffffff, 2.5); @@ -42,8 +44,8 @@ const defaultLight = () => { /** * Shows the 3D components in the scene of `@nanoforge-dev/graphics-3d`: `Box3D`, `Sphere3D`, - * `Plane3D`, `Light3D`, `Camera3D` and `Object3DComponent`, placed by `Position3D`, `Rotation3D` - * and `Scale3D` (basics-3d). Add it after the systems that move entities. + * `Plane3D`, `Light3D`, `Camera3D`, `Object3DComponent` and `Model3D`, placed by `Position3D`, + * `Rotation3D` and `Scale3D` (basics-3d). Add it after the systems that move entities. * * @remarks * Each component gets its Three.js object the first frame it is seen, which follows its fields @@ -85,6 +87,9 @@ export const draw3D = (registry: Registry, ctx: Context) => { if (object !== previous) { if (previous) disposeObject3D(previous); scene.add(object); + // After `scene.add`: a load that ends once the group has no parent is dropped. + if (component.name === "Model3D") + void loadModel3D(object as Group, component.path, ctx.assets); } applyTransform3D(object, positions.get(row.id), rotations.get(row.id), scales.get(row.id)); objects.set(component, object); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 933234a..a2cc285 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -49,6 +49,9 @@ catalogs: '@nanoforge-dev/sound': specifier: ^3.0.0 version: 3.0.0 + '@types/three': + specifier: ^0.187.0 + version: 0.187.0 three: specifier: ^0.187.0 version: 0.187.0 @@ -132,6 +135,9 @@ importers: '@trivago/prettier-plugin-sort-imports': specifier: catalog:lint version: 6.0.2(prettier@3.10.1) + '@types/three': + specifier: catalog:core + version: 0.187.0 '@vitest/coverage-v8': specifier: catalog:test version: 4.1.12(vitest@4.1.12) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index d37a46f..ef759b1 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -18,6 +18,7 @@ catalogs: '@nanoforge-dev/network': ^3.0.0 '@nanoforge-dev/scene': ^3.0.0 '@nanoforge-dev/sound': ^3.0.0 + '@types/three': ^0.187.0 three: ^0.187.0 typescript: ^6.0.3 lint: diff --git a/test/3d/graphics-3d.spec.ts b/test/3d/graphics-3d.spec.ts index 2dcf227..f5f3fc9 100644 --- a/test/3d/graphics-3d.spec.ts +++ b/test/3d/graphics-3d.spec.ts @@ -23,21 +23,37 @@ import { Scale3D } from "@nanoforge/basics-3d/components/scale-3d"; import { Box3D } from "@nanoforge/graphics-3d/components/box-3d"; import { Camera3D } from "@nanoforge/graphics-3d/components/camera-3d"; import { Light3D } from "@nanoforge/graphics-3d/components/light-3d"; +import { Model3D } from "@nanoforge/graphics-3d/components/model-3d"; import { Object3DComponent } from "@nanoforge/graphics-3d/components/object-3d-component"; import { Plane3D } from "@nanoforge/graphics-3d/components/plane-3d"; import { Sphere3D } from "@nanoforge/graphics-3d/components/sphere-3d"; import { toObject3D } from "@nanoforge/graphics-3d/object-3d"; import { draw3D } from "@nanoforge/graphics-3d/systems/draw-3d"; -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { registry, runOn, spawn, useRegistry } from "../ecs"; +/** `ctx.assets`: a blob URL per path, and no asset at a path starting with `/missing`. */ +const assets = { + getAsset: (path: string) => { + if (path.startsWith("/missing")) throw new Error("not found"); + return { path: `blob:${path}` }; + }, +}; + +const gltf = vi.hoisted(() => ({ loadAsync: vi.fn() })); +vi.mock("three/addons/loaders/GLTFLoader.js", () => ({ + GLTFLoader: class { + loadAsync = gltf.loadAsync; + }, +})); + useRegistry(); /** The part of graphics-3d's `ctx.graphics` that `draw3D` uses: a real scene and camera. */ const graphics3D = () => { const graphics = { scene: new Scene(), camera: new PerspectiveCamera() as Camera }; - return { graphics, ctx: { app: { delta: 16 }, graphics } as unknown as Context }; + return { graphics, ctx: { app: { delta: 16 }, graphics, assets } as unknown as Context }; }; /** What `draw3D` added for its components, without the default light. */ @@ -203,4 +219,113 @@ describe("graphics-3d", () => { expect(same).toBe(box); expect(((same as Mesh).geometry as BoxGeometry).parameters).toMatchObject({ width: 3 }); }); + + describe("Model3D", () => { + /** A loaded glTF scene: one mesh with a textured material, its disposes spied. */ + const model = () => { + const geometry = new SphereGeometry(); + const map = new Texture(); + const material = new MeshStandardMaterial({ map }); + const scene = new Group().add(new Mesh(geometry, material)); + return { scene, spies: [geometry, material, map].map((it) => vi.spyOn(it, "dispose")) }; + }; + /** The groups draw3D made for Model3Ds (the default light is a group too). */ + const models = (scene: Scene) => scene.children.filter((child) => "path" in child.userData); + /** Lets the pending loads end. */ + const settle = () => new Promise((resolve) => setTimeout(resolve)); + + beforeEach(() => { + gltf.loadAsync.mockReset(); + }); + + it("shows the model once loaded, placed by the transform, without blocking the frame", async () => { + const { graphics, ctx } = graphics3D(); + const { scene: loaded } = model(); + gltf.loadAsync.mockResolvedValue({ scene: loaded }); + spawn(new Model3D("/models/duck.glb"), new Position3D(1, 2, 3)); + registry.addSystem(draw3D); + + runOn(ctx); + const [group] = models(graphics.scene); + expect(group?.children).toHaveLength(0); + + await settle(); + expect(gltf.loadAsync).toHaveBeenCalledWith("blob:/models/duck.glb"); + expect(group?.children).toEqual([loaded]); + expect(group?.position).toMatchObject({ x: 1, y: 2, z: 3 }); + }); + + it("logs the path and shows a placeholder box for a missing or broken file", async () => { + const { graphics, ctx } = graphics3D(); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + gltf.loadAsync.mockRejectedValue(new Error("bad glb")); + spawn(new Model3D("/missing.glb")); + spawn(new Model3D("/models/broken.glb")); + registry.addSystem(draw3D); + + expect(() => runOn(ctx)).not.toThrow(); + await settle(); + + const groups = models(graphics.scene); + expect(groups).toHaveLength(2); + for (const group of groups) expect(group.children[0]).toBeInstanceOf(Mesh); + for (const path of ["/missing.glb", "/models/broken.glb"]) + expect(error).toHaveBeenCalledWith(expect.stringContaining(path), expect.anything()); + error.mockRestore(); + }); + + it("disposes the model's geometries, materials and textures when removed", async () => { + const { graphics, ctx } = graphics3D(); + const { scene: loaded, spies } = model(); + gltf.loadAsync.mockResolvedValue({ scene: loaded }); + const entity = spawn(new Model3D("/models/duck.glb")); + registry.addSystem(draw3D); + runOn(ctx); + await settle(); + + registry.killEntity(entity); + runOn(ctx); + + expect(models(graphics.scene)).toHaveLength(0); + for (const spy of spies) expect(spy).toHaveBeenCalled(); + }); + + it("drops and disposes a load that ends after the component was removed", async () => { + const { ctx } = graphics3D(); + const { scene: loaded, spies } = model(); + let finish = (_: unknown) => {}; + gltf.loadAsync.mockReturnValue(new Promise((resolve) => (finish = resolve))); + const entity = spawn(new Model3D("/models/duck.glb")); + registry.addSystem(draw3D); + runOn(ctx); + registry.killEntity(entity); + runOn(ctx); + + finish({ scene: loaded }); + await settle(); + + expect(loaded.parent).toBeNull(); + for (const spy of spies) expect(spy).toHaveBeenCalled(); + }); + + it("loads the new file when the path changes", async () => { + const { graphics, ctx } = graphics3D(); + gltf.loadAsync.mockReturnValue(new Promise(() => {})); + const component = new Model3D("/models/duck.glb"); + spawn(component); + registry.addSystem(draw3D); + runOn(ctx); + const [first] = models(graphics.scene); + + runOn(ctx); + component.path = "/models/fox.glb"; + runOn(ctx); + await settle(); + + expect(models(graphics.scene)).not.toContain(first); + expect(models(graphics.scene)).toHaveLength(1); + expect(gltf.loadAsync).toHaveBeenCalledTimes(2); + expect(gltf.loadAsync).toHaveBeenLastCalledWith("blob:/models/fox.glb"); + }); + }); });