@threenative/terrain 0.1.6 → 0.1.8

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 (127) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +160 -5
  3. package/dist/editor/index.js +3783 -1406
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +555 -121
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +444 -110
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +727 -73
  11. package/dist/index.js +2434 -553
  12. package/dist/kit.d.ts +56 -0
  13. package/dist/kit.js +2524 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +3705 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3279 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-C8Ydr_IM.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1030 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-B3DkduPw.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-CPYAc9vo.d.ts} +13 -4
  24. package/dist/world-package-B7KGYIou.d.ts +94 -0
  25. package/package.json +28 -6
  26. package/starter/alpine/README.md +77 -1
  27. package/starter/alpine/bake.mjs +4 -116
  28. package/starter/alpine/biome.data.json +114 -0
  29. package/starter/alpine/heightmap.r16 +0 -0
  30. package/starter/alpine/recipe.json +3 -66051
  31. package/starter/alpine/world.ts +45 -293
  32. package/starter/coastal/README.md +77 -1
  33. package/starter/coastal/bake.mjs +4 -116
  34. package/starter/coastal/biome.data.json +135 -0
  35. package/starter/coastal/heightmap.r16 +0 -0
  36. package/starter/coastal/recipe.json +3 -66051
  37. package/starter/coastal/sea.ts +49 -16
  38. package/starter/coastal/world.ts +53 -318
  39. package/starter/desert/README.md +77 -1
  40. package/starter/desert/bake.mjs +4 -116
  41. package/starter/desert/biome.data.json +114 -0
  42. package/starter/desert/heightmap.r16 +0 -0
  43. package/starter/desert/recipe.json +3 -66051
  44. package/starter/desert/world.ts +45 -293
  45. package/starter/forest/README.md +84 -4
  46. package/starter/forest/assets.json +32 -0
  47. package/starter/forest/bake.mjs +6 -116
  48. package/starter/forest/biome.data.json +150 -0
  49. package/starter/forest/heightmap.r16 +0 -0
  50. package/starter/forest/recipe.json +192 -4428
  51. package/starter/forest/sky.ts +11 -0
  52. package/starter/forest/water.ts +30 -20
  53. package/starter/forest/world.ts +86 -322
  54. package/starter/tundra/README.md +77 -1
  55. package/starter/tundra/bake.mjs +4 -116
  56. package/starter/tundra/biome.data.json +131 -0
  57. package/starter/tundra/heightmap.r16 +0 -0
  58. package/starter/tundra/recipe.json +18 -66066
  59. package/starter/tundra/world.ts +65 -319
  60. package/starter-assets.json +6 -0
  61. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  62. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  63. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  64. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  65. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  66. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  67. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  68. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  69. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  71. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  72. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  74. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  75. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  76. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  79. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  81. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  82. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  85. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  86. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  88. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  89. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  91. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  92. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  93. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  96. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  97. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  99. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  100. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  103. package/starter-assets/needle-atlas.png +0 -0
  104. package/starter-assets/needle-surface.png +0 -0
  105. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  106. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  108. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  109. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  111. package/starter-assets/rocks/boulder-mid.glb +0 -0
  112. package/starter-assets/rocks/boulder-near.glb +0 -0
  113. package/starter-assets/rocks/boulder-prep.json +0 -37
  114. package/starter-assets/rocks/rock01-mid.glb +0 -0
  115. package/starter-assets/rocks/rock01-near.glb +0 -0
  116. package/starter-assets/rocks/rock01-prep.json +0 -37
  117. package/starter-assets/rocks/rock04-mid.glb +0 -0
  118. package/starter-assets/rocks/rock04-near.glb +0 -0
  119. package/starter-assets/rocks/rock04-prep.json +0 -37
  120. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  121. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  122. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  124. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  125. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
@@ -1,30 +1,24 @@
1
- // The desert starter world, as the game that copied it draws and collides with it.
2
- //
3
- // `bake.mjs` wrote a world package into `world/`: heightmap, splat masks, placements and the CC0 boulder.
4
- // The engine's `WorldCells` streams it. `loadTerrainSplat` textures its ground.
5
- // Everything that decides how the world looks, or what stops the player, is in this folder for the game to edit.
6
- import type { IComputeDriven, ICtx } from "@threenative/core";
1
+ import type { ICtx } from "@threenative/core";
7
2
  import {
8
- Heightfield,
9
- type IWorldCellsLoadOptions,
3
+ type ILoadTerrainSplatOptions,
10
4
  type IWorldPackage,
11
- WorldCells,
12
- heightSamplerFromHeightmap,
13
5
  loadTerrainSplat,
14
- loadWorldHeightmap,
15
6
  } from "@threenative/core/world";
16
- import { CollisionShape3D, type IPhysicsContext, RigidBody3D } from "@threenative/physics";
7
+ import type { IPhysicsContext } from "@threenative/physics";
8
+ import {
9
+ type IStarterWorld,
10
+ type IStarterWorldSpec,
11
+ PropColliders as StarterPropColliders,
12
+ addStarterWorld,
13
+ } from "@threenative/terrain/starter";
17
14
  import {
18
15
  EquirectangularReflectionMapping,
19
- type Material,
20
16
  type Mesh,
21
17
  type MeshStandardMaterial,
22
- Object3D,
18
+ type Object3D,
23
19
  type Texture,
24
- Vector3,
25
20
  } from "three";
26
- import { HDRLoader } from "three/addons/loaders/HDRLoader.js";
27
-
21
+ import surface from "./surface.json" with { type: "json" };
28
22
  /** Where the game's asset source holds the baked `world/` folder. */
29
23
  export const DESERT_URL = "terrain/desert/world.json";
30
24
 
@@ -42,294 +36,52 @@ export const PROP_SKY_LIGHT = 0.5;
42
36
  /** Metres around `follow` within which props collide. Beyond that, props only draw. */
43
37
  export const PROP_COLLIDER_REACH = 60;
44
38
 
45
- export interface IDesertWorld {
46
- readonly world: WorldCells;
47
- /** One heightfield for the whole world, in place before `addDesert` resolves. */
48
- readonly ground: RigidBody3D;
49
- /** The prop colliders near `follow`. They stream with it (see `PROP_COLLIDER_REACH`). */
50
- readonly colliders: PropColliders;
51
- /** The heightfield the ground stands on: `heightAt(x, z)` reads the terrain under any point. */
52
- readonly field: Heightfield;
53
- /** Every placed prop's record, eight floats each, as the bake wrote it. */
54
- readonly placements: Float32Array;
55
- /** The world's extent in metres, as the bake wrote it. */
56
- readonly extent: IWorldPackage["extent"];
39
+ export interface IDesertWorld extends IStarterWorld {}
40
+ const spec: IStarterWorldSpec<{ dispose(): void }> = {
41
+ name: "Desert",
42
+ url: DESERT_URL,
43
+ colliders: COLLIDERS,
44
+ colliderReach: PROP_COLLIDER_REACH,
45
+ loadSurface: (ctx, url) =>
46
+ loadTerrainSplat({
47
+ assets: ctx.assets,
48
+ url,
49
+ table: surface as unknown as ILoadTerrainSplatOptions["table"],
50
+ }),
51
+ lighting: { sky: "sky.hdr", lods: false, dress: dressProp },
52
+ streaming: {
53
+ ring: 5,
54
+ impostors: false,
55
+ gpuScene: false,
56
+ shadows: { cast: true, receive: true },
57
+ budgets: { residentCells: 64, instances: 40_000, bytes: 64_000_000 },
58
+ terrain: { streamRadius: 6 },
59
+ },
60
+ };
61
+ export class PropColliders extends StarterPropColliders {
62
+ constructor(
63
+ ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
64
+ follow: Object3D,
65
+ manifest: IWorldPackage,
66
+ records: Float32Array,
67
+ ) {
68
+ super(ctx, follow, manifest, records, COLLIDERS, PROP_COLLIDER_REACH, "Desert");
69
+ }
57
70
  }
58
-
59
- /**
60
- * Stream the desert world around `follow` (usually the player or the camera) and give it collision.
61
- * `whileCurrent` stops a departed scene's async load from attaching anything. Its resources are
62
- * released on cancellation, failure and when the game's entity registry ends this scene.
63
- */
64
71
  export async function addDesert(
65
72
  ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
66
73
  follow: Object3D,
67
74
  url = DESERT_URL,
68
75
  whileCurrent: () => boolean = () => true,
69
76
  ): Promise<IDesertWorld> {
70
- const assertCurrent = () => {
71
- if (whileCurrent()) return;
72
- const error = new Error("Desert world: its scene is no longer current.");
73
- error.name = "AbortError";
74
- throw error;
75
- };
76
- let surface: Material | undefined;
77
- let releaseLighting: (() => void) | undefined;
78
- let world: WorldCells | undefined;
79
- let ground: RigidBody3D | undefined;
80
- let colliders: PropColliders | undefined;
81
- let released = false;
82
- const dispose = () => {
83
- if (released) return;
84
- released = true;
85
- colliders?.detach();
86
- colliders?.removeFromParent();
87
- ground?.dispose();
88
- ground?.object?.removeFromParent();
89
- world?.dispose();
90
- surface?.dispose();
91
- releaseLighting?.();
92
- };
93
- try {
94
- assertCurrent();
95
- const manifest = (await (await fetchAsset(ctx, url, assertCurrent)).json()) as IWorldPackage;
96
- assertCurrent();
97
- const base = url.slice(0, url.lastIndexOf("/") + 1);
98
- const records = await (
99
- await fetchAsset(ctx, base + manifest.placements, assertCurrent)
100
- ).arrayBuffer();
101
- assertCurrent();
102
- const [heightmapUrl] = await ctx.assets.resolve(base + manifest.terrain.heightmap);
103
- assertCurrent();
104
- if (heightmapUrl === undefined) throw new Error("Desert world: its heightmap is not served.");
105
- const heightmap = await loadWorldHeightmap(heightmapUrl);
106
- assertCurrent();
107
- surface = await loadTerrainSplat({ assets: ctx.assets, url });
108
- assertCurrent();
109
- releaseLighting = await lightProps(ctx, url, manifest, assertCurrent);
110
- assertCurrent();
111
- const options: IWorldCellsLoadOptions = {
112
- url,
113
- assets: ctx.assets,
114
- data: { manifest, placements: records, heightmap },
115
- surface,
116
- follow,
117
- ring: 5,
118
- impostors: false,
119
- gpuScene: false,
120
- shadows: { cast: true, receive: true },
121
- budgets: { residentCells: 64, instances: 40_000, bytes: 64_000_000 },
122
- terrain: { streamRadius: 6 },
123
- };
124
- world = await WorldCells.load(options);
125
- assertCurrent();
126
- const field = desertField(manifest, heightmap);
127
- ground = groundCollider(ctx, manifest, field);
128
- const props = new Float32Array(records);
129
- colliders = new PropColliders(ctx, follow, manifest, props);
130
- ctx.add(world);
131
- if (ground.object !== undefined) ctx.add(ground.object);
132
- ctx.add(colliders);
133
- ctx.entities.add(`desert-world.${world.uuid}`, { dispose });
134
- return { world, ground, colliders, field, placements: props, extent: manifest.extent };
135
- } catch (error) {
136
- dispose();
137
- throw error;
138
- }
77
+ const result = await addStarterWorld(ctx, follow, spec, url, whileCurrent);
78
+ return result;
139
79
  }
140
-
141
- // Every prop gets the sky as its own envMap before WorldCells adopts the shared cached models.
142
- // Without it, a boulder lit by the sun alone draws flat.
143
- async function lightProps(
144
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
145
- url: string,
146
- manifest: IWorldPackage,
147
- assertCurrent: () => void,
148
- ): Promise<() => void> {
149
- const base = url.slice(0, url.lastIndexOf("/") + 1);
150
- const [skyUrl] = await ctx.assets.resolve(`${base}sky.hdr`);
151
- assertCurrent();
152
- if (skyUrl === undefined) throw new Error("Desert world: 'sky.hdr' is not served.");
153
- const sky = await new HDRLoader().loadAsync(skyUrl);
154
- const originals = new Map<MeshStandardMaterial, { envMap: Texture | null; intensity: number }>();
155
- const dispose = () => {
156
- for (const [material, original] of originals) {
157
- if (material.envMap !== sky) continue;
158
- material.envMap = original.envMap;
159
- material.envMapIntensity = original.intensity;
160
- }
161
- sky.dispose();
162
- };
163
- try {
164
- assertCurrent();
165
- sky.mapping = EquirectangularReflectionMapping;
166
- for (const asset of Object.values(manifest.assets)) {
167
- const model = await ctx.assets.model<{ scene: Object3D }>(base + asset.glb);
168
- assertCurrent();
169
- model.scene.traverse((object) => {
170
- const mesh = object as Mesh;
171
- for (const material of [mesh.material ?? []].flat() as MeshStandardMaterial[])
172
- if (!originals.has(material))
173
- originals.set(material, {
174
- envMap: material.envMap,
175
- intensity: material.envMapIntensity,
176
- });
177
- dressProp(mesh, sky);
178
- });
179
- }
180
- return dispose;
181
- } catch (error) {
182
- dispose();
183
- throw error;
184
- }
185
- }
186
-
187
80
  /** One prop mesh: the sky as its envMap. */
188
81
  function dressProp(mesh: Mesh, sky: Texture): void {
189
82
  for (const material of [mesh.material ?? []].flat() as MeshStandardMaterial[]) {
83
+ sky.mapping = EquirectangularReflectionMapping;
190
84
  material.envMap = sky;
191
85
  material.envMapIntensity = PROP_SKY_LIGHT;
192
86
  }
193
87
  }
194
-
195
- // The streamed terrain tiles arrive over several frames. A player spawned before its tile would
196
- // fall through. One heightfield for the whole package avoids that, at a few hundred kilobytes.
197
- /** The kit's one heightfield: the collider stands on it. */
198
- function desertField(manifest: IWorldPackage, heightmap: Uint16Array): Heightfield {
199
- const { extent, terrain } = manifest;
200
- return Heightfield.fromSampler({
201
- columns: terrain.columns,
202
- rows: terrain.rows,
203
- width: extent.sizeX,
204
- depth: extent.sizeZ,
205
- origin: { x: extent.minX + extent.sizeX / 2, z: extent.minZ + extent.sizeZ / 2 },
206
- sampleHeight: heightSamplerFromHeightmap(terrain, extent, heightmap),
207
- });
208
- }
209
-
210
- function groundCollider(
211
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
212
- manifest: IWorldPackage,
213
- field: Heightfield,
214
- ): RigidBody3D {
215
- const { extent } = manifest;
216
- const anchor = new Object3D();
217
- anchor.position.set(extent.minX + extent.sizeX / 2, 0, extent.minZ + extent.sizeZ / 2);
218
- return new RigidBody3D({
219
- object: anchor,
220
- physics: ctx.physics,
221
- type: "fixed",
222
- entity: "terrain",
223
- shape: CollisionShape3D.heightfield(field.rows, field.columns, field.toColliderHeights(), {
224
- x: extent.sizeX,
225
- y: 1,
226
- z: extent.sizeZ,
227
- }),
228
- });
229
- }
230
-
231
- /**
232
- * Fixed bodies for the props within `PROP_COLLIDER_REACH` of `follow`, rebuilt when it has moved a few
233
- * metres. Thousands of resident bodies cost Rapier about 0.5 s per 8 s (measured). A hundred do not.
234
- */
235
- export class PropColliders extends Object3D implements IComputeDriven {
236
- readonly warmupNodes: readonly unknown[] = [];
237
- readonly processCadence = "render" as const;
238
- readonly #live = new Map<number, RigidBody3D>();
239
- readonly #runs: { asset: string; offset: number; count: number }[] = [];
240
- readonly #at = { x: Number.NaN, z: Number.NaN };
241
- readonly #followPosition = new Vector3();
242
- #released = false;
243
-
244
- constructor(
245
- private readonly ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
246
- private readonly follow: Object3D,
247
- manifest: IWorldPackage,
248
- private readonly records: Float32Array,
249
- ) {
250
- super();
251
- this.name = "desert-prop-colliders";
252
- for (const cell of manifest.cells)
253
- for (const run of cell.runs) if (COLLIDERS[run.asset]) this.#runs.push(run);
254
- try {
255
- this.#rebuild();
256
- } catch (error) {
257
- this.detach();
258
- throw error;
259
- }
260
- }
261
-
262
- /** How many prop bodies exist right now. */
263
- get active(): number {
264
- return this.#live.size;
265
- }
266
-
267
- get released(): boolean {
268
- return this.#released;
269
- }
270
-
271
- attachRenderer(): void {}
272
-
273
- process(): void {
274
- if (this.#released) return;
275
- const p = this.follow.getWorldPosition(this.#followPosition);
276
- if (Math.hypot(p.x - this.#at.x, p.z - this.#at.z) > 4 || Number.isNaN(this.#at.x))
277
- this.#rebuild();
278
- }
279
-
280
- detach(): void {
281
- for (const body of this.#live.values()) body.dispose();
282
- this.#live.clear();
283
- this.#released = true;
284
- }
285
-
286
- #rebuild(): void {
287
- const { x: fx, z: fz } = this.follow.getWorldPosition(this.#followPosition);
288
- this.#at.x = fx;
289
- this.#at.z = fz;
290
- const keep = new Set<number>();
291
- for (const run of this.#runs) {
292
- const shape = COLLIDERS[run.asset];
293
- if (!shape) continue;
294
- for (let i = run.offset; i < run.offset + run.count; i++) {
295
- const x = this.records[i * 8] as number;
296
- const z = this.records[i * 8 + 2] as number;
297
- if (Math.hypot(x - fx, z - fz) > PROP_COLLIDER_REACH) continue;
298
- keep.add(i);
299
- if (this.#live.has(i)) continue;
300
- const collider = CollisionShape3D.sphere(
301
- shape.sphere * (this.records[i * 8 + 7] as number),
302
- );
303
- this.#live.set(
304
- i,
305
- new RigidBody3D({
306
- physics: this.ctx.physics,
307
- type: "fixed",
308
- entity: `${run.asset}.${String(i)}`,
309
- position: { x, y: this.records[i * 8 + 1] as number, z },
310
- shape: collider,
311
- }),
312
- );
313
- }
314
- }
315
- for (const [i, body] of this.#live)
316
- if (!keep.has(i)) {
317
- body.dispose();
318
- this.#live.delete(i);
319
- }
320
- }
321
- }
322
-
323
- async function fetchAsset(
324
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
325
- url: string,
326
- assertCurrent: () => void,
327
- ): Promise<Response> {
328
- const [resolved] = await ctx.assets.resolve(url);
329
- assertCurrent();
330
- if (resolved === undefined) throw new Error(`Desert world: '${url}' is not served.`);
331
- const response = await fetch(resolved);
332
- assertCurrent();
333
- if (!response.ok) throw new Error(`Desert world: '${url}' answered ${String(response.status)}.`);
334
- return response;
335
- }
@@ -13,13 +13,16 @@ stands, young firs and boulder fields. It is game source: once copied, every fil
13
13
  | `water.ts` | `addForestWater(ctx, water, field)`: the lake's surface (`WaterSurface3D`) and the river's ribbon, from `water.json`. |
14
14
  | `sky.ts` | `forestDaylight(follow)`: sun, sky, fill, haze, exposure and tone curve. |
15
15
 
16
- Art is CC0 (Poly Haven); provenance is in `@threenative/terrain/starter-assets/credits.json`.
16
+ Art is CC0 (Poly Haven); provenance is in `@threenative/terrain/starter-credits.json`.
17
17
 
18
18
  ## Three steps
19
19
 
20
20
  1. Copy `node_modules/@threenative/terrain/starter/forest` to `src/terrain/forest`.
21
- 2. Run `node src/terrain/forest/bake.mjs --out assets/terrain/forest` (needs `@threenative/terrain`
22
- as a devDependency). The same recipe always writes the same bytes.
21
+ 2. Run `node src/terrain/forest/bake.mjs --out assets/terrain/forest`. The bake imports both
22
+ `@threenative/terrain` and `@threenative/assets`, so install them as devDependencies
23
+ (`npm install --save-dev @threenative/terrain @threenative/assets`); `three` must be installed
24
+ too, because `@threenative/terrain` declares it as a peer dependency. The same recipe always
25
+ writes the same bytes.
23
26
  3. Add it to a scene:
24
27
 
25
28
  ```ts
@@ -43,4 +46,81 @@ world before it returns. Set the camera's `far` to at least the sky size in `sky
43
46
  - **The water:** the recipe's `lake-bed`, `river` and `lake` layers set where it lies and how deep;
44
47
  `water.ts` sets how it looks.
45
48
  - **The look:** `surface.json` for the ground, `sky.ts` for the light, `PROP_SKY_LIGHT` in
46
- `world.ts` for how strongly the sky lights the props.
49
+ `world.ts` for how strongly the sky lights the props and `GROUND_SPECULAR` for the sheen on the
50
+ ground (0 is matte; three's default is 1).
51
+
52
+ ## Edit at startup, without rebaking
53
+
54
+ The copied `world.ts` loads its own `surface.json` as the ground table on every startup.
55
+ Edit tints, tiling and blend thresholds there, or the material graph and prop dressing in
56
+ `world.ts`, then reload. The package's `terrain-table.json` remains the baked default for
57
+ package-only consumers; its splat masks and texture descriptors still supply the ground data.
58
+ A source table cannot name a mask that the bake did not produce.
59
+
60
+ Add `edits` to the existing `spec` in your copied `world.ts`. Read real stable IDs from the
61
+ package's `placement-ids.json` (named by `world.json.placementIds`); these example IDs are placeholders:
62
+
63
+ ```ts
64
+ edits: {
65
+ assets: {
66
+ accent: { glb: "props/accent.glb", bounds: { min: [-1, -1, -1], max: [1, 1, 1] } },
67
+ },
68
+ remove: ["promote-id"],
69
+ clear: [{ center: [40, 18], radius: 6 }], // Optional assets: ["fir"] filter.
70
+ overrides: {
71
+ "move-id": { position: [12, 0, -30], quaternion: [0, 0, 0, 1], scale: [1, 1, 1] },
72
+ },
73
+ add: [{ id: "camp-accent", asset: "accent", position: [44, 0, 20],
74
+ quaternion: [0, 0, 0, 1], scale: [1, 1, 1], grounding: true }],
75
+ },
76
+ ```
77
+
78
+ `assets` replaces or adds a kind; copy the GLB into the served package directory first.
79
+ GLB and LOD paths are package-relative, with no URL scheme, leading slash or `..` segment;
80
+ provide accurate model-local `bounds`. The existing `COLLIDERS` table and dress function still
81
+ choose each kind's collision and appearance. Positions must lie inside the world's extent,
82
+ quaternions must be nonzero, values finite and scale uniform. Grounding defaults on and sets
83
+ the origin Y to `field.heightAt(x, z)`; `grounding: false` preserves the authored Y.
84
+
85
+ Edits run in the order shown: assets, remove, clear, overrides, add. A clear skips IDs named
86
+ by overrides. Removing and overriding the same ID throws; additions need new IDs. Unmatched
87
+ removal/override IDs warn and appear in `editReport.unmatched`. Old packages work without a
88
+ sidecar for assets, clear and add; ID edits need one re-bake to write the sidecar. Without
89
+ `edits`, the decoded manifest and placement bytes pass through unchanged.
90
+
91
+ Promote only a few props to ordinary Three objects: remove their IDs from the instances,
92
+ then use the returned `editReport.removed` in the scene. This example replaces each with a
93
+ game-owned glowing box; use your own geometry, material, light and collision shape:
94
+
95
+ ```ts
96
+ import { CollisionShape3D, RigidBody3D } from "@threenative/physics";
97
+ import { BoxGeometry, Mesh, MeshStandardMaterial, PointLight } from "three";
98
+
99
+ const loaded = await addForest(ctx, player);
100
+ for (const p of loaded.editReport.removed) {
101
+ const mesh = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: 0xffbb66 }));
102
+ mesh.position.set(p.position[0], loaded.field.heightAt(p.position[0], p.position[2]), p.position[2]);
103
+ mesh.quaternion.fromArray(p.quaternion);
104
+ mesh.scale.setScalar(p.scale);
105
+ mesh.castShadow = mesh.receiveShadow = true;
106
+ mesh.add(new PointLight(0xffaa55, 12, 6));
107
+ ctx.add(mesh);
108
+ const body = new RigidBody3D({ object: mesh, physics: ctx.physics, type: "fixed",
109
+ shape: CollisionShape3D.box(p.scale, p.scale, p.scale) });
110
+ ctx.entities.add(`promoted.${p.id}`, { dispose() {
111
+ body.dispose(); mesh.removeFromParent(); mesh.geometry.dispose(); mesh.material.dispose();
112
+ } });
113
+ }
114
+ ```
115
+
116
+ Rendering, nearby prop collision, dressing and returned `manifest`, `placements` and
117
+ `placementIds` all use the edited records. `clear` removals are not in the promotion report.
118
+ The separate `editWorldPlacements` helper and its types are exported from
119
+ `@threenative/terrain/starter` for callers that already own decoded package data.
120
+
121
+ Shape, topology, erosion, mask painting, distribution rules and water still require regeneration.
122
+ Changing cooked ground images requires the bake/cook texture normalization step; editing the
123
+ game table cannot replace baked texture descriptors or introduce new channels. To replace the
124
+ props' environment image at runtime, copy an HDR into the served package, change
125
+ `spec.lighting.sky` in `world.ts` to its package-relative path, then reload. The daylight and
126
+ background remain game choices in `sky.ts`. Package-only exports do not run these source edits.
@@ -28,5 +28,37 @@
28
28
  },
29
29
  "mid": "fir_tree_01/fir-c-lod2.glb",
30
30
  "midDistance": 45
31
+ },
32
+ "fern-a": {
33
+ "near": "fern_02/fern-a.glb",
34
+ "maxDistance": 50,
35
+ "bounds": {
36
+ "min": [-0.699, 0, -0.744],
37
+ "max": [0.764, 0.62, 0.802]
38
+ }
39
+ },
40
+ "fern-b": {
41
+ "near": "fern_02/fern-b.glb",
42
+ "maxDistance": 50,
43
+ "bounds": {
44
+ "min": [-0.758, 0, -0.879],
45
+ "max": [0.655, 0.687, 0.643]
46
+ }
47
+ },
48
+ "boulder-small-a": {
49
+ "near": "rock_moss_set_01/pebble-a.glb",
50
+ "maxDistance": 80,
51
+ "bounds": {
52
+ "min": [-1.029, 0, -1.712],
53
+ "max": [1.137, 1.462, 1.683]
54
+ }
55
+ },
56
+ "boulder-small-b": {
57
+ "near": "rock_moss_set_01/pebble-b.glb",
58
+ "maxDistance": 80,
59
+ "bounds": {
60
+ "min": [-0.955, 0, -0.784],
61
+ "max": [1.128, 1.736, 1.09]
62
+ }
31
63
  }
32
64
  }
@@ -1,118 +1,8 @@
1
- // Bakes this folder's recipe into a self-contained world package. Run it once from your game
2
- // project, then serve the folder it writes:
3
- // node src/terrain/forest/bake.mjs [--assets <dir>] [--out <dir>]
4
- // The engine's `WorldCells` streams `world/world.json` and `loadTerrainSplat` textures its ground;
5
- // the game never evaluates terrain at runtime.
6
- import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
7
- import { dirname, join, resolve } from "node:path";
8
- import { fileURLToPath } from "node:url";
9
- import { Terrain, applyPlacementOverrides, bakeWorldPackage } from "@threenative/terrain";
1
+ // Run with [--assets <dir>] [--out <dir>]; defaults to installed assets and ./world.
2
+ import { cookTerrainWorld } from "@threenative/assets";
3
+ import { bakeKit } from "@threenative/terrain/kit";
10
4
 
11
- const here = dirname(fileURLToPath(import.meta.url));
12
-
13
- /** `--key value` after the script; `--assets` and `--out` default as noted below. */
14
- function flag(name, fallback) {
15
- const at = process.argv.indexOf(`--${name}`);
16
- return at === -1 ? fallback : resolve(process.argv[at + 1] ?? "");
17
- }
18
-
19
- // The installed kit ships its models and textures beside the package manifest, so a copied kit
20
- // finds them without asking the game for a path. `--assets` overrides that for a local checkout.
21
- const installed = dirname(fileURLToPath(import.meta.resolve("@threenative/terrain/package.json")));
22
- const assetsDir = flag("assets", join(installed, "starter-assets"));
23
- const outDir = flag("out", join(here, "world"));
24
-
25
- const recipe = JSON.parse(await readFile(join(here, "recipe.json"), "utf8"));
26
- const assetTable = JSON.parse(await readFile(join(here, "assets.json"), "utf8"));
27
- const surface = JSON.parse(await readFile(join(here, "surface.json"), "utf8"));
28
-
29
- const state = applyPlacementOverrides(
30
- Terrain.fromJSON(recipe.recipe).evaluate(),
31
- recipe.placementOverrides ?? {},
32
- );
33
-
34
- const assets = Object.fromEntries(
35
- Object.entries(assetTable).map(([id, spec]) => [
36
- id,
37
- {
38
- bounds: spec.bounds,
39
- glb: `models/${spec.near.split("/").at(-1)}`,
40
- ...(spec.mid
41
- ? { lods: [{ distance: spec.midDistance, glb: `models/${spec.mid.split("/").at(-1)}` }] }
42
- : {}),
43
- maxDistance: spec.maxDistance,
44
- },
45
- ]),
46
- );
47
-
48
- const started = performance.now();
49
- const { manifest, splat, files } = bakeWorldPackage(state, {
50
- assets,
51
- layers: { table: "terrain-table.json" },
5
+ await bakeKit(import.meta.url, {
6
+ sky: "hdri/kloofendal_48d_partly_cloudy_1k.hdr",
7
+ cookTerrainWorld,
52
8
  });
53
- const written = new Map();
54
-
55
- async function write(relative, bytes) {
56
- await mkdir(join(outDir, dirname(relative)), { recursive: true });
57
- await writeFile(join(outDir, relative), bytes);
58
- written.set(relative, bytes.length ?? bytes.byteLength);
59
- }
60
-
61
- async function copy(from, to) {
62
- await mkdir(join(outDir, dirname(to)), { recursive: true });
63
- await copyFile(join(assetsDir, from), join(outDir, to));
64
- written.set(to, (await readFile(join(outDir, to))).byteLength);
65
- }
66
-
67
- await write("world.json", `${JSON.stringify(manifest, null, 2)}\n`);
68
- // The lake and river the generator evaluated, so the game draws the water the bake shaped.
69
- const round = (value) => Math.round(value * 1_000) / 1_000;
70
- await write(
71
- "water.json",
72
- `${JSON.stringify(
73
- {
74
- lakes: state.waters.map((lake) => ({
75
- id: lake.id,
76
- at: lake.at,
77
- radius: lake.radius,
78
- level: lake.level,
79
- })),
80
- rivers: state.rivers.map((river) => ({
81
- id: river.id,
82
- width: round(river.width),
83
- points: river.points.map((point) => point.map(round)),
84
- })),
85
- },
86
- null,
87
- 2,
88
- )}\n`,
89
- );
90
- for (const [name, bytes] of Object.entries(files)) await write(name, bytes);
91
- for (const spec of Object.values(assetTable)) {
92
- await copy(spec.near, `models/${spec.near.split("/").at(-1)}`);
93
- if (spec.mid) await copy(spec.mid, `models/${spec.mid.split("/").at(-1)}`);
94
- }
95
- // The sky the props are lit by (CC0 Poly Haven Kloofendal); world.ts gives it to their materials.
96
- await copy("hdri/kloofendal_48d_partly_cloudy_1k.hdr", "sky.hdr");
97
- for (const layer of [surface.base, ...surface.layers]) {
98
- const source = surface.sources[layer.id];
99
- await copy(source.diff, `${surface.textures}/${layer.id}_diff.jpg`);
100
- await copy(source.nrm, `${surface.textures}/${layer.id}_nrm.jpg`);
101
- }
102
- // `sources` is the bake's own lookup: the runtime reads only base/layers/splat/textures.
103
- await write(
104
- "terrain-table.json",
105
- `${JSON.stringify({ ...surface, splat, textures: "textures" }, null, 2)}\n`,
106
- );
107
-
108
- const perAsset = {};
109
- for (const cell of manifest.cells)
110
- for (const run of cell.runs) perAsset[run.asset] = (perAsset[run.asset] ?? 0) + run.count;
111
- const total = [...written.values()].reduce((sum, bytes) => sum + bytes, 0);
112
- console.log(
113
- `${Object.entries(perAsset)
114
- .map(([asset, count]) => `${asset} ${String(count)}`)
115
- .join(", ")} placements; ${[...written]
116
- .map(([name, bytes]) => `${name} ${String(bytes)} B`)
117
- .join(", ")}; ${String(total)} B total; ${Math.round(performance.now() - started)} ms`,
118
- );