roamwright 0.61.27 → 0.61.29

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 (45) hide show
  1. package/README.md +2 -1
  2. package/examples/set-pieces.html +52 -0
  3. package/examples/set-pieces.js +284 -0
  4. package/geometry/builder.js +7 -12
  5. package/geometry/camp-layout.js +150 -0
  6. package/geometry/cavern-rock.js +309 -0
  7. package/geometry/cliff-sheets.js +457 -0
  8. package/geometry/creased-sheet.js +39 -0
  9. package/geometry/curtain-sheets.js +67 -0
  10. package/geometry/ice-cliff.js +339 -0
  11. package/geometry/ice-shards.js +247 -0
  12. package/geometry/index.js +35 -3
  13. package/geometry/instances.js +50 -1
  14. package/geometry/part-ops.js +152 -0
  15. package/geometry/plant-roots.js +115 -0
  16. package/geometry/primitives.js +4 -0
  17. package/geometry/rock-sheets.js +259 -0
  18. package/geometry/strata-rocks.js +4 -3
  19. package/math/index.js +1 -0
  20. package/math/scalar.js +3 -1
  21. package/package.json +1 -1
  22. package/rendering/camp-layout.js +55 -0
  23. package/rendering/curtain-sheets.js +271 -0
  24. package/rendering/flame-sources.js +105 -0
  25. package/rendering/flier-long-body-company.js +2 -0
  26. package/rendering/flocks.js +27 -22
  27. package/rendering/height-probe.js +7 -4
  28. package/rendering/house-kit-meshes.js +15 -10
  29. package/rendering/ice-material.js +143 -0
  30. package/rendering/index.js +24 -1
  31. package/rendering/lamp-wash.js +2 -0
  32. package/rendering/material-lod.js +50 -26
  33. package/rendering/rock-materials.js +27 -0
  34. package/rendering/ruins-fittings.js +110 -17
  35. package/rendering/scene-projectiles.js +3 -0
  36. package/rendering/settlement-town.js +6 -1
  37. package/rendering/ship-meshes.js +10 -7
  38. package/rendering/street-lamps.js +4 -1
  39. package/rendering/surface-material.js +60 -24
  40. package/rendering/surface-snippets.js +83 -45
  41. package/rendering/vehicle-train.js +1 -0
  42. package/rendering/water-material.js +9 -0
  43. package/runtime/index.js +1 -1
  44. package/runtime/lazy-sets.js +24 -0
  45. package/scripts/build.py +5 -3
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Procedural weathered glacial ice material (`MeshStandardMaterial` patched via `onBeforeCompile`):
3
+ * refracted internal crack layers, milky cloud, surface rime, dirt/stain vertex-colour channels,
4
+ * derivative micro-relief cups, internal blue-cyan glow, optional height-based mist fade, and a
5
+ * transparent clear-ice variant.
6
+ * @module
7
+ */
8
+
9
+ import * as THREE from 'three';
10
+ import { createNoise } from '../math/noise.js';
11
+ import { createHash } from '../math/random.js';
12
+ import { createSurfaceTextures, fillPixels } from '../math/surface-textures.js';
13
+
14
+ /** Raw GLSL shader snippets injected by {@link createIceMaterial}. */
15
+ export const ICE_SHADER_PARTS = Object.freeze({
16
+ varying: 'varying vec3 vIceAt; varying vec3 vIceFace;',
17
+ pattern: `/* glsl */
18
+ uniform sampler2D uIceSheet; uniform float uIceGlow; uniform float uIceThin; uniform vec3 uIceMist;
19
+ // the sheet of cracks, cloud and grain (engine/texture-fills.js, 'ice') laid on a plane that no face of a cliff lies along
20
+ vec2 icePlane(vec3 p) { return vec2(p.x + 0.4 * p.z, p.y * 0.8 + 0.25 * p.z); }
21
+ vec3 iceSkin = vec3(0.0); float iceWhite = 0.0, iceHeld = 0.0, iceRelief = 0.0, iceCloud = 0.0;`,
22
+ surface: `/* glsl */
23
+ {
24
+ vec3 toEye = normalize(cameraPosition - vIceAt), face = normalize(vIceFace);
25
+ float square = clamp(dot(toEye, face), 0.0, 1.0), graze = pow(1.0 - square, 3.0);
26
+ float far = length(vViewPosition), fine = 1.0 - smoothstep(14.0, 70.0, far);
27
+ vec3 into = refract(-toEye, face, 0.763);
28
+ float thin = 0.012 + 0.0022 * far;
29
+ float cracks = 0.0, cloud = 0.0;
30
+ for (int k = 0; k < 3; k++) {
31
+ float deep = float(k);
32
+ vec4 sheet = texture2D(uIceSheet, icePlane(vIceAt + into * (0.15 + 0.65 * deep)) * (0.04 + 0.012 * deep) + 0.37 * deep);
33
+ cracks += smoothstep(1.0 - thin, 1.0 - 0.35 * thin, sheet.r) * (0.1 + 0.9 * smoothstep(0.45, 0.62, sheet.a)) * (1.0 - 0.3 * deep);
34
+ cloud += sheet.g * (0.5 - 0.12 * deep);
35
+ }
36
+ cracks = min(1.0, cracks);
37
+ vec4 frost = texture2D(uIceSheet, icePlane(vIceAt) * 0.29 + 0.5);
38
+ vec4 run = texture2D(uIceSheet, vec2(vIceAt.x + 0.4 * vIceAt.z, vIceAt.y * 0.08) * 0.13);
39
+ float grain = frost.b, cups = frost.g;
40
+ float rime = smoothstep(0.42, 0.78, face.y * 0.9 + grain * 0.55);
41
+ float skin = clamp(vColor.r * (0.55 + 0.9 * grain) + rime * 0.8, 0.0, 1.0);
42
+ float dirt = vColor.g * smoothstep(0.25, 0.7, run.a + 0.3 * grain);
43
+ float stain = vColor.b * smoothstep(0.3, 0.75, run.g + 0.25 * grain);
44
+ vec3 depths = mix(vec3(0.012, 0.075, 0.15), vec3(0.08, 0.34, 0.5), clamp(cloud * 1.5 - 0.3 + 0.3 * square, 0.0, 1.0));
45
+ vec3 ice = mix(depths, vec3(0.5, 0.74, 0.86), cracks * 0.75);
46
+ ice = mix(ice, vec3(0.74, 0.82, 0.86), max(skin, graze * 0.55));
47
+ ice = mix(ice, vec3(0.2, 0.165, 0.13), dirt * 0.8);
48
+ ice = mix(ice, vec3(0.17, 0.035, 0.03), stain * 0.85);
49
+ diffuseColor.rgb = ice;
50
+ iceWhite = max(skin, max(dirt, stain));
51
+ iceHeld = (1.0 - 0.8 * iceWhite) * (0.35 + 0.65 * square);
52
+ iceSkin = mix(vec3(0.1, 0.4, 0.62), vec3(0.42, 0.72, 0.86), min(1.0, cloud + cracks * 0.6));
53
+ iceRelief = (cups * 0.05 + grain * 0.02 * fine) * (0.4 + 0.6 * skin);
54
+ iceCloud = cloud;
55
+ #ifndef OPAQUE
56
+ diffuseColor.a = clamp(uIceThin + 0.9 * max(iceWhite, cracks * 0.8) + min(1.0, uIceThin * 3.3) * (0.45 * graze + 0.22 * cloud), 0.0, 1.0);
57
+ #endif
58
+ }`,
59
+ relief: `/* glsl */
60
+ {
61
+ vec3 sx = dFdx(-vViewPosition), sy = dFdy(-vViewPosition);
62
+ float hx = dFdx(iceRelief), hy = dFdy(iceRelief);
63
+ vec3 r1 = cross(sy, normal), r2 = cross(normal, sx);
64
+ float det = dot(sx, r1);
65
+ normal = normalize(abs(det) * normal - sign(det) * (hx * r1 + hy * r2));
66
+ }`,
67
+ mist: `/* glsl */
68
+ #ifdef USE_FOG
69
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, fogColor * 1.25 + vec3(0.03, 0.04, 0.055), uIceMist.z * smoothstep(uIceMist.x, uIceMist.y, vIceAt.y + 6.0 * iceCloud));
70
+ #endif`,
71
+ });
72
+
73
+ let fallbackIceTexture = null;
74
+
75
+ /**
76
+ * Create a default 256×256 tileable cracked-ice `THREE.DataTexture` backed by Roamwright's
77
+ * procedural `createSurfaceTextures().crackedIce` generator.
78
+ *
79
+ * @param {object} [options]
80
+ * @param {number} [options.size=256] - Texture width and height in pixels.
81
+ * @param {number} [options.seed=0] - Seed for default noise and hash.
82
+ * @returns {THREE.DataTexture}
83
+ */
84
+ export function createIceSheetTexture({ size = 256, seed = 0 } = {}) {
85
+ const { tfbm, tnoise } = createNoise(seed);
86
+ const hash2 = createHash(seed);
87
+ const surfaces = createSurfaceTextures({ noise: { tfbm, tnoise }, hash2 });
88
+ const data = fillPixels({ size, make: surfaces.crackedIce });
89
+ const tex = new THREE.DataTexture(data, size, size);
90
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
91
+ tex.colorSpace = THREE.NoColorSpace;
92
+ tex.magFilter = THREE.LinearFilter;
93
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
94
+ tex.generateMipmaps = true;
95
+ tex.needsUpdate = true;
96
+ return tex;
97
+ }
98
+
99
+ /**
100
+ * Create a weathered glacial ice `MeshStandardMaterial`. Vertex colours encode `[whiteSkin, dirt, stain]`
101
+ * in RGB. Pass `sheet` (either a `THREE.Texture` or a `{ texture }` handle from `createTextureFills`)
102
+ * to share a worker-filled ice sheet; when omitted, a procedural default texture is created once.
103
+ *
104
+ * @param {object} [options]
105
+ * @param {THREE.Texture | { texture: THREE.Texture }} [options.sheet] - Repeating RGBA crack/cloud/grain data texture.
106
+ * @param {number} [options.glow=0.3] - Internal blue-cyan glow multiplier (`0` for none).
107
+ * @param {boolean} [options.clear=false] - Transparent clear-ice variant (`depthWrite = false`).
108
+ * @param {number} [options.thin=0.3] - Minimum alpha of the clear variant where cracks and frost are absent.
109
+ * @param {[number, number, number]} [options.mist=[0, 1, 0]] - Height-mist fade `[fromY, toY, strength]` in metres.
110
+ * @param {string} [options.cacheKey='ice'] - `customProgramCacheKey` value.
111
+ * @returns {THREE.MeshStandardMaterial}
112
+ */
113
+ export function createIceMaterial({ sheet, glow = 0.3, clear = false, thin = 0.3, mist = [0, 1, 0], cacheKey = 'ice' } = {}) {
114
+ const texture = sheet ? (sheet.texture ?? sheet) : (fallbackIceTexture ??= createIceSheetTexture());
115
+ const material = new THREE.MeshStandardMaterial({
116
+ vertexColors: true,
117
+ roughness: 0.5,
118
+ metalness: 0,
119
+ transparent: clear,
120
+ depthWrite: !clear,
121
+ });
122
+ material.customProgramCacheKey = () => cacheKey;
123
+ material.onBeforeCompile = sh => {
124
+ sh.uniforms.uIceSheet = { value: texture };
125
+ sh.uniforms.uIceGlow = { value: glow };
126
+ sh.uniforms.uIceThin = { value: thin };
127
+ sh.uniforms.uIceMist = { value: new THREE.Vector3(...mist) };
128
+ sh.vertexShader = sh.vertexShader
129
+ .replace('#include <common>', '#include <common>\n' + ICE_SHADER_PARTS.varying)
130
+ .replace(
131
+ '#include <begin_vertex>',
132
+ '#include <begin_vertex>\nvIceAt = (modelMatrix * vec4(position, 1.0)).xyz; vIceFace = normalize(mat3(modelMatrix) * normal);',
133
+ );
134
+ sh.fragmentShader = sh.fragmentShader
135
+ .replace('#include <common>', '#include <common>\n' + ICE_SHADER_PARTS.varying + ICE_SHADER_PARTS.pattern)
136
+ .replace('#include <color_fragment>', ICE_SHADER_PARTS.surface)
137
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = mix(0.1, 0.82, iceWhite);')
138
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + ICE_SHADER_PARTS.relief)
139
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\ntotalEmissiveRadiance += uIceGlow * iceHeld * iceSkin;')
140
+ .replace('#include <fog_fragment>', '#include <fog_fragment>\n' + ICE_SHADER_PARTS.mist);
141
+ };
142
+ return material;
143
+ }
@@ -24,10 +24,21 @@ export { createStainMaterial } from './stain-material.js';
24
24
 
25
25
  // ── Terrain & land baking ────────────────────────────────────────────────
26
26
  export { createSimpleWater } from './water-simple.js';
27
+ export { createCrystalMaterial } from './rock-materials.js';
28
+ export { ICE_SHADER_PARTS, createIceMaterial, createIceSheetTexture } from './ice-material.js';
27
29
  export { createStrataCliffs } from './strata-cliffs.js';
28
30
  export { meshTalusStones } from './strata-talus.js';
29
31
  export { MOUND_RUINS_LOD, raiseMoundRuins, registerMoundRuins } from './ruins-mound.js';
30
- export { LIGHT_POOL, addLampStand, addLightPool, addStillPool, addWallLantern, createLightPoolTexture } from './ruins-fittings.js';
32
+ export {
33
+ FLAME_DEFAULTS,
34
+ LIGHT_POOL,
35
+ addFlame,
36
+ addLampStand,
37
+ addLightPool,
38
+ addStillPool,
39
+ addWallLantern,
40
+ createLightPoolTexture,
41
+ } from './ruins-fittings.js';
31
42
  export { GROUND_DRAPE_FRAGMENT, createGroundDrape, createGroundDrapeMaterial } from './ground-drape.js';
32
43
  export { meshStreamBanks } from './stream-banks.js';
33
44
  export { meshSprings } from './stream-springs.js';
@@ -119,10 +130,22 @@ export { createTroopDirector } from './troop-director.js';
119
130
 
120
131
  // ── Effects, audio, pacing & runtime ─────────────────────────────────────
121
132
  export { DEFAULT_PARTICLE_LOOK, createParticleNoiseTexture, createParticleSystem } from './particles.js';
133
+ export { FLAME_KINDS, addFireSites, createFireSite, createFlameSources, createSmokeSite } from './flame-sources.js';
122
134
  export { createFireLightWatch } from './fire-light-watch.js';
123
135
  export { createEffectsFrame, syncEffectsUniforms } from './effects-frame.js';
124
136
  export { createRippleRingMaterial, createWaterRises, fishGeometry } from './effects-water-rises.js';
125
137
  export { STORM_WALL_COLORS, createStormWall, stormWallGeometry, stormWallNoise } from './storm-wall.js';
138
+ export {
139
+ DUST_CURTAIN_DEFAULTS,
140
+ FALLING_WATER_DEFAULTS,
141
+ VALUE_NOISE_3D_GLSL,
142
+ createDustCurtain,
143
+ createDustCurtainMaterial,
144
+ createFallingWaterMaterial,
145
+ createFallingWaterSheets,
146
+ dustCurtainGeometry,
147
+ } from './curtain-sheets.js';
148
+ export { FALLEN_BEAST_DEFAULTS, placeFallenBeasts } from './camp-layout.js';
126
149
  export { createPracticalFlame, createSceneLights } from './scene-lights.js';
127
150
  export { createPerfBox } from './perf-box.js';
128
151
  export { PERF_BOX_DEFAULTS, attachPerfBoxWorker, createPerfBoxRenderer } from './perf-box-worker.js';
@@ -18,6 +18,8 @@ export function createLampWashMaterial({ night, cacheKey = 'lamp-wash' }) {
18
18
  depthWrite: false,
19
19
  fog: false,
20
20
  side: THREE.DoubleSide, // the fans wind either way, as the wall faces
21
+ // Additive blending is commutative regardless of face order, so one pass avoids a duplicate FLIP_SIDED compile.
22
+ forceSinglePass: true,
21
23
  polygonOffset: true,
22
24
  polygonOffsetFactor: -2,
23
25
  polygonOffsetUnits: -2,
@@ -8,27 +8,30 @@ const SCATTER = 'fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056,
8
8
  // A copy of a material that draws only a share of its pixels (share.value, from 0 to 1), scattered evenly: a house built in detail dissolves in over its far version instead of jumping into place, and out again
9
9
  // when it is let go. One copy to a material and share (a land's own stone has its own); all share one program.
10
10
  const fadings = new WeakMap();
11
+ const rawFading = new WeakMap();
11
12
  export function fadingOf(base, share) {
12
- let variants = fadings.get(base);
13
- if (!variants) fadings.set(base, (variants = new Map()));
13
+ const raw = rawFading.get(base) ?? base;
14
+ let variants = fadings.get(raw);
15
+ if (!variants) fadings.set(raw, (variants = new Map()));
14
16
  let variant = variants.get(share);
15
17
  if (variant) return variant;
16
- variants.set(share, (variant = base.clone()));
18
+ variants.set(share, (variant = raw.clone()));
19
+ rawFading.set(variant, raw);
17
20
  variant.onBeforeCompile = (shader, renderer) => {
18
- base.onBeforeCompile(shader, renderer);
21
+ raw.onBeforeCompile(shader, renderer);
19
22
  shader.uniforms.uShare = share;
20
23
  shader.fragmentShader = shader.fragmentShader
21
24
  .replace('#include <common>', '#include <common>\nuniform float uShare;')
22
25
  .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\nif (${SCATTER} > uShare) discard;`);
23
26
  };
24
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':dissolving';
27
+ variant.customProgramCacheKey = () => raw.customProgramCacheKey() + ':dissolving';
25
28
  return variant;
26
29
  }
27
30
  // A copy of a material that draws only what lies nearer the eye than `reach.value` metres or, with `beyond`, only what lies
28
31
  // further: a thing's near version and its far one hand over pixel by pixel across a band `band` metres deep about that distance,
29
32
  // each drawing the pixels of the screen-fixed scatter (SCATTER) the other leaves, a share that follows the pixel's distance. No
30
33
  // pixel is drawn by both, none by neither, and no stretch of the thing changes all at once. One copy to a material, reach, side
31
- // and band; the two sides share one program each.
34
+ // and band; both sides and all bands share one program via `uBeyond` and `uHalfBand`.
32
35
  const reaching = new WeakMap();
33
36
  export function reachOf(base, reach, beyond = false, band = 1) {
34
37
  let variants = reaching.get(base);
@@ -37,59 +40,64 @@ export function reachOf(base, reach, beyond = false, band = 1) {
37
40
  let sides = variants.get(reach);
38
41
  if (!sides) variants.set(reach, (sides = {}));
39
42
  if (sides[key]) return sides[key];
40
- const variant = (sides[key] = base.clone());
43
+ const variant = (sides[key] = base.clone()),
44
+ beyondUniform = { value: beyond ? 1 : 0 },
45
+ halfBandUniform = { value: band * 0.5 };
41
46
  variant.onBeforeCompile = (shader, renderer) => {
42
47
  base.onBeforeCompile(shader, renderer);
43
48
  shader.uniforms.uReach = reach;
49
+ shader.uniforms.uBeyond = beyondUniform;
50
+ shader.uniforms.uHalfBand = halfBandUniform;
44
51
  shader.fragmentShader = shader.fragmentShader
45
- .replace('#include <common>', '#include <common>\nuniform float uReach;')
52
+ .replace('#include <common>', '#include <common>\nuniform float uReach;\nuniform float uBeyond;\nuniform float uHalfBand;')
46
53
  .replace(
47
54
  '#include <clipping_planes_fragment>',
48
- `#include <clipping_planes_fragment>\n${handedOver(beyond, nearShare('length(vViewPosition)', band))}`,
55
+ `#include <clipping_planes_fragment>\n{ float rwNear = 1.0 - smoothstep(uReach - uHalfBand, uReach + uHalfBand, length(vViewPosition));\n${handedOver('rwNear')} }`,
49
56
  );
50
57
  };
51
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + (beyond ? ':beyond-reach:' : ':within-reach:') + band;
58
+ variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':reach';
52
59
  return variant;
53
60
  }
54
61
  // The same for the instances of an InstancedMesh, each handed over whole and in its own time, using its geometry's `aNear` (an instanced attribute, 0 to 1) is the near version's share of the instance's
55
62
  // pixels, which its builder moves from the one end to the other over a moment once the viewer comes within or goes beyond its
56
63
  // reach. An instance its version does not draw at all has its vertices put out of sight. handOverShadow gives the near or far
57
64
  // version's shadow body, which casts wherever its version draws anything: while an instance is handed over both cast, and their
58
- // shadows, of one shape in two levels of detail, lie over each other.
65
+ // shadows, of one shape in two levels of detail, lie over each other. Both sides share one colour and one shadow program via `uBeyond`.
59
66
  const handing = new WeakMap();
60
67
  export function handOverOf(base, beyond = false) {
61
68
  let variants = handing.get(base);
62
69
  if (!variants) handing.set(base, (variants = {}));
63
70
  if (variants[beyond]) return variants[beyond];
64
- const variant = (variants[beyond] = base.clone());
71
+ const variant = (variants[beyond] = base.clone()),
72
+ beyondUniform = { value: beyond ? 1 : 0 };
65
73
  variant.onBeforeCompile = (shader, renderer) => {
66
74
  base.onBeforeCompile(shader, renderer);
67
- handOverVertices(shader, beyond);
75
+ handOverVertices(shader, beyondUniform);
68
76
  shader.fragmentShader = shader.fragmentShader
69
- .replace('#include <common>', '#include <common>\nvarying float vNearShare;')
70
- .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\n${handedOver(beyond, 'vNearShare')}`);
77
+ .replace('#include <common>', '#include <common>\nvarying float vNearShare;\nuniform float uBeyond;')
78
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\n${handedOver('vNearShare')}`);
71
79
  };
72
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + (beyond ? ':handed-far' : ':handed-near');
80
+ variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':handed';
73
81
  return variant;
74
82
  }
75
83
  export function handOverShadow(beyond = false) {
76
- const variant = new THREE.MeshDepthMaterial();
77
- variant.onBeforeCompile = shader => handOverVertices(shader, beyond);
78
- variant.customProgramCacheKey = () => (beyond ? 'handed-far-depth' : 'handed-near-depth');
84
+ const variant = new THREE.MeshDepthMaterial(),
85
+ beyondUniform = { value: beyond ? 1 : 0 };
86
+ variant.onBeforeCompile = shader => handOverVertices(shader, beyondUniform);
87
+ variant.customProgramCacheKey = () => 'handed-depth';
79
88
  return variant;
80
89
  }
81
- // The near version's share, 1 short of the band about uReach and 0 past it, at a distance (a GLSL expression) from the eye
82
- const nearShare = (distance, band) => `1.0 - smoothstep(uReach - ${(band / 2).toFixed(2)}, uReach + ${(band / 2).toFixed(2)}, ${distance})`;
83
- // The fragment's test: the near version keeps the scatter's pixels under its share, the far version the rest
84
- const handedOver = (beyond, share) => `if (${SCATTER} ${beyond ? '<' : '>='} ${share}) discard;`;
90
+ // The fragment's test: the near version (`uBeyond <= 0.5`) keeps the scatter's pixels under its share, the far version the rest
91
+ const handedOver = share => `if (uBeyond > 0.5 ? (${SCATTER} < ${share}) : (${SCATTER} >= ${share})) discard;`;
85
92
  // Hands an instance's share (aNear) to the fragments (vNearShare), and puts the vertices of an instance its version does not draw
86
93
  // at all out of sight.
87
- function handOverVertices(shader, beyond) {
94
+ function handOverVertices(shader, beyondUniform) {
95
+ shader.uniforms.uBeyond = beyondUniform;
88
96
  shader.vertexShader = shader.vertexShader
89
- .replace('#include <common>', '#include <common>\nattribute float aNear;\nvarying float vNearShare;')
97
+ .replace('#include <common>', '#include <common>\nattribute float aNear;\nvarying float vNearShare;\nuniform float uBeyond;')
90
98
  .replace(
91
99
  '#include <project_vertex>',
92
- `#include <project_vertex>\nvNearShare = aNear;\nif (aNear ${beyond ? '>= 1.0' : '<= 0.0'}) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
100
+ `#include <project_vertex>\nvNearShare = aNear;\nif (uBeyond > 0.5 ? (aNear >= 1.0) : (aNear <= 0.0)) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
93
101
  );
94
102
  }
95
103
  // The same material for meshes of another kind (kind: 'plain', 'instanced', or 'tinted' for instances with a colour each), drawn as
@@ -107,3 +115,19 @@ export function twinMaterial(base, kind) {
107
115
  }
108
116
  return variants[kind];
109
117
  }
118
+
119
+ /**
120
+ * Attach a unit-white `instanceColor` buffer `(1, 1, 1)` to an `InstancedMesh` so untinted instanced meshes
121
+ * share `USE_INSTANCING_COLOR` WebGL programs with tinted batches of the same material without changing shading.
122
+ *
123
+ * @template {THREE.InstancedMesh} T
124
+ * @param {T} mesh
125
+ * @returns {T}
126
+ */
127
+ export function whiteInstanceColor(mesh) {
128
+ if (!mesh.instanceColor) {
129
+ const count = mesh.instanceMatrix.count;
130
+ mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(count * 3).fill(1), 3);
131
+ }
132
+ return mesh;
133
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Specialized rock and mineral materials for subterranean and geological sets.
3
+ * @module
4
+ */
5
+
6
+ import * as THREE from 'three';
7
+
8
+ /**
9
+ * Create a glossy, flat-shaded, softly self-lit `MeshStandardMaterial` for faceted cavern crystals.
10
+ *
11
+ * @param {object} [options]
12
+ * @param {number} [options.roughness=0.12] - Surface roughness.
13
+ * @param {number} [options.metalness=0] - Metallic factor.
14
+ * @param {number} [options.emissive=0x2a2838] - Faint inner mineral glow sRGB hex colour.
15
+ * @param {boolean} [options.flatShading=true] - Keep crystal facets crisp.
16
+ * @param {boolean} [options.vertexColors=true] - Read per-prism tints from vertex colours.
17
+ * @returns {THREE.MeshStandardMaterial}
18
+ */
19
+ export function createCrystalMaterial({
20
+ roughness = 0.12,
21
+ metalness = 0,
22
+ emissive = 0x2a2838,
23
+ flatShading = true,
24
+ vertexColors = true,
25
+ } = {}) {
26
+ return new THREE.MeshStandardMaterial({ vertexColors, roughness, metalness, emissive, flatShading });
27
+ }
@@ -86,22 +86,32 @@ export function addLightPool(group, x, y, z, radius, options = {}) {
86
86
  }
87
87
 
88
88
  /**
89
- * Add a dark, glossy oval or circular pool of still water lying in a courtyard basin or hollow.
89
+ * Add a glossy oval or circular pool of still water (or liquid decal) lying flat in a basin, spring
90
+ * or hollow. Pass `material` to share an existing water/liquid material, or omit it to create a
91
+ * `MeshStandardMaterial` from `color`, `roughness`, `metalness`, `transparent` and `opacity`.
92
+ * Pass `radius` (with optional `scaleX`/`scaleZ`) to size the `CircleGeometry` directly, or omit it
93
+ * to scale a unit-diameter disc by `(width, depth)`.
90
94
  *
91
- * @param {THREE.Object3D} group - Destination scene or group.
92
- * @param {object} options
95
+ * @param {THREE.Object3D | null} group - Destination scene or group.
96
+ * @param {object} [options]
93
97
  * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin.
94
98
  * @param {number} [options.x=0] - Local X position in metres.
95
- * @param {number} [options.y=0] - Water surface elevation in metres.
99
+ * @param {number} [options.y=0] - Surface elevation in metres.
96
100
  * @param {number} [options.z=0] - Local Z position in metres.
97
- * @param {number} [options.width=2] - Pool width in metres.
98
- * @param {number} [options.depth=2] - Pool depth in metres.
101
+ * @param {number} [options.width=2] - Pool width in metres (when `radius` is omitted).
102
+ * @param {number} [options.depth=2] - Pool depth in metres (when `radius` is omitted).
103
+ * @param {number | null} [options.radius=null] - Explicit `CircleGeometry` radius in metres.
104
+ * @param {number} [options.scaleX=1] - X scale multiplier when `radius` is set.
105
+ * @param {number} [options.scaleZ=1] - Z scale multiplier when `radius` is set.
99
106
  * @param {number} [options.yaw=0] - Rotation around Y in radians.
100
- * @param {number} [options.color=0x1c2a2a] - Water base sRGB colour.
101
- * @param {number} [options.roughness=0.05] - Surface roughness.
102
- * @param {number} [options.metalness=0.4] - Surface reflectivity factor.
103
- * @param {number} [options.opacity=0.88] - Water opacity.
107
+ * @param {number} [options.color=0x1c2a2a] - Base sRGB colour when `material` is omitted.
108
+ * @param {number} [options.roughness=0.05] - Surface roughness when `material` is omitted.
109
+ * @param {number} [options.metalness=0.4] - Surface reflectivity factor when `material` is omitted.
110
+ * @param {boolean} [options.transparent=true] - Whether the default material is transparent.
111
+ * @param {number} [options.opacity=0.88] - Opacity when `material` is omitted and `transparent` is true.
112
+ * @param {THREE.Material | null} [options.material=null] - Optional shared material to reuse.
104
113
  * @param {number} [options.segments=20] - Perimeter circle segments.
114
+ * @param {number | null} [options.renderOrder=null] - Optional Three.js `renderOrder`.
105
115
  * @returns {THREE.Mesh}
106
116
  */
107
117
  export function addStillPool(group, options = {}) {
@@ -112,24 +122,107 @@ export function addStillPool(group, options = {}) {
112
122
  z = 0,
113
123
  width = 2,
114
124
  depth = 2,
125
+ radius = null,
126
+ scaleX = 1,
127
+ scaleZ = 1,
115
128
  yaw = 0,
116
129
  color = 0x1c2a2a,
117
130
  roughness = 0.05,
118
131
  metalness = 0.4,
132
+ transparent = true,
119
133
  opacity = 0.88,
134
+ material = null,
120
135
  segments = 20,
136
+ renderOrder = null,
121
137
  } = options;
122
- const water = new THREE.Mesh(
123
- new THREE.CircleGeometry(0.5, segments).rotateX(-Math.PI / 2),
124
- new THREE.MeshStandardMaterial({ color, roughness, metalness, transparent: true, opacity }),
125
- );
138
+ const mat =
139
+ material ??
140
+ new THREE.MeshStandardMaterial(
141
+ transparent ? { color, roughness, metalness, transparent: true, opacity } : { color, roughness, metalness },
142
+ );
143
+ const geo = new THREE.CircleGeometry(radius ?? 0.5, segments).rotateX(-Math.PI / 2);
144
+ const water = new THREE.Mesh(geo, mat);
126
145
  water.position.set(origin.x + x, y, origin.z + z);
127
- water.scale.set(width, 1, depth);
128
- water.rotation.y = yaw;
129
- group.add(water);
146
+ if (radius === null) water.scale.set(width, 1, depth);
147
+ else if (scaleX !== 1 || scaleZ !== 1) water.scale.set(scaleX, 1, scaleZ);
148
+ if (yaw) water.rotation.y = yaw;
149
+ if (renderOrder !== null) water.renderOrder = renderOrder;
150
+ if (group) group.add(water);
130
151
  return water;
131
152
  }
132
153
 
154
+ /** Default emissive core and lamp-threshold settings for {@link addFlame}. */
155
+ export const FLAME_DEFAULTS = Object.freeze({
156
+ color: 0xffb24a,
157
+ boost: 1.5,
158
+ lampSize: 0.2,
159
+ lampLight: Object.freeze({ lift: 0.25, light: 0.14 }),
160
+ });
161
+
162
+ /**
163
+ * Place a glowing flame core at `(x, y, z)` in local coordinates offset by `origin` and invoke an
164
+ * optional `onSite` callback with the fire-site parameters (attaching `lampLight` overrides when
165
+ * `size < lampSize` so small lamp wicks keep low, tight lighting).
166
+ *
167
+ * @param {THREE.Object3D | null} group - Destination group receiving the glowing flame core.
168
+ * @param {object} options
169
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin.
170
+ * @param {number} [options.x=0] - Local X in metres.
171
+ * @param {number} [options.y=0] - World Y in metres.
172
+ * @param {number} [options.z=0] - Local Z in metres.
173
+ * @param {number} [options.size=0.3] - Flame size in metres.
174
+ * @param {number} [options.color=FLAME_DEFAULTS.color] - Emissive core sRGB hex colour.
175
+ * @param {number} [options.boost=FLAME_DEFAULTS.boost] - Emissive intensity multiplier.
176
+ * @param {number} [options.lampSize=FLAME_DEFAULTS.lampSize] - Threshold below which `lampLight` is applied.
177
+ * @param {{ lift: number, light: number }} [options.lampLight=FLAME_DEFAULTS.lampLight] - Light override for small wicks.
178
+ * @param {object} [options.shapes] - Unit shapes containing `sph`.
179
+ * @param {((geo: THREE.BufferGeometry, hex: number, boost: number, group: THREE.Object3D | null) => THREE.Mesh) | null} [options.makeGlowMesh=null] - Custom emissive mesh factory.
180
+ * @param {((site: object) => void) | null} [options.onSite=null] - Optional callback receiving the fire effect-site record.
181
+ * @param {string} [options.space='world'] - Host space id stored on the emitted site record.
182
+ * @returns {{ core: THREE.Mesh, site: object }}
183
+ */
184
+ export function addFlame(group, options = {}) {
185
+ const {
186
+ origin = { x: 0, z: 0 },
187
+ x = 0,
188
+ y = 0,
189
+ z = 0,
190
+ size = 0.3,
191
+ color = FLAME_DEFAULTS.color,
192
+ boost = FLAME_DEFAULTS.boost,
193
+ lampSize = FLAME_DEFAULTS.lampSize,
194
+ lampLight = FLAME_DEFAULTS.lampLight,
195
+ shapes = defaultShapes(),
196
+ makeGlowMesh = null,
197
+ onSite = null,
198
+ space = 'world',
199
+ } = options;
200
+ const core = makeGlowMesh
201
+ ? makeGlowMesh(shapes.sph, color, boost, group)
202
+ : (() => {
203
+ const m = new THREE.Mesh(shapes.sph, new THREE.MeshBasicMaterial({ color: new THREE.Color(color).multiplyScalar(boost) }));
204
+ if (group) group.add(m);
205
+ return m;
206
+ })();
207
+ core.position.set(origin.x + x, y, origin.z + z);
208
+ core.scale.set(size * 0.5, size * 1.1, size * 0.5);
209
+ const lamp = size < lampSize;
210
+ const site = {
211
+ space,
212
+ type: 'fire',
213
+ x: origin.x + x,
214
+ y,
215
+ z: origin.z + z,
216
+ rate: 3 + size * 8,
217
+ size: size * 0.9,
218
+ hot: 1,
219
+ soot: 0.1,
220
+ ...(lamp && lampLight),
221
+ };
222
+ onSite?.(site);
223
+ return { core, site };
224
+ }
225
+
133
226
  /**
134
227
  * Build a tall brass oil-lamp stand and invoke an optional flame callback at its wick.
135
228
  *
@@ -9,6 +9,7 @@ import * as THREE from 'three';
9
9
  import { TAU, clamp } from '../math/scalar.js';
10
10
  import { evaluateBallisticLodge, sampleBallisticFlight, solveBallisticLodge } from '../motion/ballistic-arc.js';
11
11
  import { buildArrowGeometry, buildKnifeGeometry, buildQuarrelGeometry } from '../geometry/projectile-shapes.js';
12
+ import { whiteInstanceColor } from './material-lod.js';
12
13
 
13
14
  const SHUDDER_SECONDS = 0.28,
14
15
  HIDDEN_MATRIX = new THREE.Matrix4().makeScale(0, 0, 0),
@@ -52,6 +53,7 @@ export function createProjectilePool({
52
53
  onGroundHit = null,
53
54
  maxPerKind = 32,
54
55
  layer = 1,
56
+ tinted = false,
55
57
  } = {}) {
56
58
  const _to = new THREE.Vector3(),
57
59
  _pos = new THREE.Vector3(),
@@ -100,6 +102,7 @@ export function createProjectilePool({
100
102
 
101
103
  function makePoolMesh(geo, material) {
102
104
  const m = new THREE.InstancedMesh(geo, material, maxPerKind + 1);
105
+ if (tinted) whiteInstanceColor(m);
103
106
  m.setMatrixAt(0, HIDDEN_MATRIX);
104
107
  m.count = 1;
105
108
  m.frustumCulled = false;
@@ -61,7 +61,12 @@ export function createTowns({ shapes, farMaterial, gableMaterial, towns = [] })
61
61
  for (let i = 0; i < list.length; i++) if (!wall || (list[i].wall || 0) === k) count++;
62
62
  if (!count) continue;
63
63
  // every town draws the same unit shapes, each part through a view of its own (geometryView)
64
- const im = new THREE.InstancedMesh(geometryView(shapes[type]), material, count);
64
+ const geo = geometryView(shapes[type]);
65
+ if (material.vertexColors && !geo.attributes.color) {
66
+ const verts = geo.attributes.position.count;
67
+ geo.setAttribute('color', new THREE.BufferAttribute(new Uint8Array(verts * 3).fill(255), 3, true));
68
+ }
69
+ const im = new THREE.InstancedMesh(geo, material, count);
65
70
  let n = 0;
66
71
  for (let i = 0; i < list.length; i++) {
67
72
  const b = list[i];
@@ -6,12 +6,12 @@
6
6
  import * as THREE from 'three';
7
7
  import { dim } from '../math/color.js';
8
8
  import { sstep } from '../math/scalar.js';
9
- import { GB, meshOf } from '../geometry/builder.js';
9
+ import { GB, meshOf, padParts } from '../geometry/builder.js';
10
10
  import { C } from '../geometry/primitives.js';
11
11
  import { shipLines } from '../geometry/ship-lines.js';
12
12
  import { gripOf, oarMatrix, oarPorts, oarPose } from '../geometry/ship-oars.js';
13
13
  import { YARD_APART } from '../geometry/ship-rig.js';
14
- import { twinMaterial } from './material-lod.js';
14
+ import { twinMaterial, whiteInstanceColor } from './material-lod.js';
15
15
 
16
16
  const _stretch = new THREE.Matrix4(),
17
17
  _m = new THREE.Matrix4();
@@ -34,6 +34,8 @@ const runHere = (job, inputOf, here) => Promise.resolve().then(here);
34
34
  * @param {(job: string, inputOf: () => object, here: () => object) => Promise<object>} [options.runOrHere] - Runs a job on a
35
35
  * worker pool, or `here()` on the page where there is none (as `createPool().runOrHere`). The page by default.
36
36
  * @param {string} [options.job] - The pool's job that answers `{ spec, options }` with `kit.shipParts(spec, options)`.
37
+ * @param {boolean} [options.padded=false] - Pad compact byte normals and colours on static ship meshes to 4 bytes per vertex
38
+ * so they align on 4-byte GPU strides and share vertex-alpha programs with padded settlement blocks.
37
39
  * @returns {{ buildShip: Function, orderShip: Function, shipOf: Function, raiseOars: Function }} buildShip(spec, options) a
38
40
  * ship now; orderShip(spec, options) the promise of her, built by the pool; shipOf(spec, options, parts) one from her arrays;
39
41
  * raiseOars(parent, spec, lines) her oars to pull. A ship is `{ group, set, setOther, furl, yard, stow, half, lines,
@@ -42,7 +44,7 @@ const runHere = (job, inputOf, here) => Promise.resolve().then(here);
42
44
  * `moving` (oars left out, to be rowed), `tacks` (lateen sails set on both sides), `yardApart` (the lateen yard built apart,
43
45
  * hoisted or stowed), `riding` (the riding light, a group to take in when she puts out).
44
46
  */
45
- export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere = runHere, job = 'ship' }) {
47
+ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere = runHere, job = 'ship', padded = false, tinted = false }) {
46
48
  // The spec a boat with a lateen yard is built from when the yard is to stand apart from her hull (`yardApart`: a boat that
47
49
  // both sails and lies): the yard, the sail furled on it and its hoisted ropes are left out of her own builders, and shipOf
48
50
  // builds them of their own in both poses.
@@ -58,7 +60,7 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
58
60
  function shipOf(spec, { far = false, yardApart = false }, parts) {
59
61
  const group = new THREE.Group(),
60
62
  lines = shipLines(spec),
61
- mesh = (p, mat, shadow = !far, parent = group) => (p ? meshOf(p, mat, parent, shadow) : null);
63
+ mesh = (p, mat, shadow = !far, parent = group) => (p ? meshOf(padded ? padParts(p) : p, mat, parent, shadow) : null);
62
64
  mesh(parts.wood, materials.wood);
63
65
  mesh(parts.rope, materials.cloth, false); // rope and iron cast none: a line a few centimetres thick is finer than the shadow map, and its shadow falls as dark smears
64
66
  mesh(parts.glass, materials.glass, false);
@@ -88,8 +90,8 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
88
90
  if (parts.ride) {
89
91
  ship.ridingLight = new THREE.Group();
90
92
  group.add(ship.ridingLight);
91
- meshOf(parts.ride.glass, materials.glass, ship.ridingLight, false);
92
- meshOf(parts.ride.iron, materials.cloth, ship.ridingLight, !far);
93
+ mesh(parts.ride.glass, materials.glass, false, ship.ridingLight);
94
+ mesh(parts.ride.iron, materials.cloth, !far, ship.ridingLight);
93
95
  }
94
96
  if (!spec.open) {
95
97
  const ladder = 1.5, // metres of deck over which a ladder climbs
@@ -118,7 +120,8 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
118
120
  const ports = oarPorts(spec, lines),
119
121
  colour = dim(C(spec.deckTone), 0.85),
120
122
  instanced = (gb, count) => {
121
- const mesh = new THREE.InstancedMesh(gb.build(), twinMaterial(materials.wood, 'instanced'), count);
123
+ const mesh = new THREE.InstancedMesh(gb.build(), twinMaterial(materials.wood, tinted ? 'tinted' : 'instanced'), count);
124
+ if (tinted) whiteInstanceColor(mesh);
122
125
  mesh.castShadow = mesh.receiveShadow = true;
123
126
  mesh.frustumCulled = false; // its instances spread wider than its geometry's bounds
124
127
  parent.add(mesh);