threedog 0.2.0 → 0.2.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 (80) hide show
  1. package/README.md +4 -4
  2. package/core/Assets.js +12 -0
  3. package/core/Engine.js +13 -4
  4. package/core/describeRender.js +7 -1
  5. package/core/grid.js +127 -0
  6. package/core/gridLoad.js +19 -0
  7. package/core/loop.js +7 -2
  8. package/core/renamed.js +1 -0
  9. package/core/styleParts.js +9 -7
  10. package/docs/AI.md +28 -23
  11. package/docs/API.md +3 -3
  12. package/docs/CODEMAP.md +5 -3
  13. package/docs/COMMANDS.md +5 -3
  14. package/docs/CONVENTIONS.md +6 -6
  15. package/docs/api/assets.md +1 -0
  16. package/docs/api/characters.md +3 -2
  17. package/docs/api/engine.md +3 -3
  18. package/docs/api/style.md +7 -7
  19. package/docs/api/tools.md +3 -2
  20. package/docs/api/vegetation.md +1 -0
  21. package/docs/recipes/01-new-game.md +41 -43
  22. package/docs/recipes/02-npc.md +24 -24
  23. package/docs/recipes/03-items-pickups.md +4 -4
  24. package/docs/recipes/04-quests.md +23 -23
  25. package/docs/recipes/05-props-bake.md +5 -5
  26. package/docs/recipes/07-flow-scenes-pause.md +2 -2
  27. package/docs/recipes/08-weather-sky.md +5 -5
  28. package/docs/recipes/09-style-pack.md +35 -100
  29. package/docs/recipes/13-animation.md +22 -6
  30. package/docs/recipes/14-custom-module.md +6 -7
  31. package/docs/recipes/15-perf.md +8 -0
  32. package/docs/recipes/16-dev-bridge.md +7 -7
  33. package/docs/recipes/18-world.md +5 -2
  34. package/docs/recipes/19-shooting-picking.md +9 -8
  35. package/docs/recipes/20-content-actions-save.md +10 -10
  36. package/docs/recipes/22-shop-gold.md +16 -16
  37. package/docs/recipes/23-ops.md +2 -2
  38. package/docs/recipes/27-net.md +2 -2
  39. package/docs/recipes/28-terrain.md +2 -2
  40. package/docs/recipes/29-grid.md +47 -27
  41. package/docs/recipes/34-environment-lighting.md +2 -2
  42. package/docs/recipes/35-style-from-reference.md +41 -46
  43. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  44. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  45. package/docs/recipes/38-environment-look-hooks.md +47 -42
  46. package/docs/recipes/42-terrain-shape.md +1 -1
  47. package/docs/recipes/43-shader-patches-surface-looks.md +35 -20
  48. package/docs/recipes/44-water-weather-look-hooks.md +5 -5
  49. package/docs/recipes/45-cascaded-shadows.md +1 -1
  50. package/docs/recipes/46-blender-art-route.md +4 -4
  51. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  52. package/docs/recipes/48-make-material.md +2 -2
  53. package/docs/recipes/49-game-module-contract.md +25 -25
  54. package/docs/recipes/51-capability-catalog.md +2 -2
  55. package/docs/recipes/52-look.md +43 -5
  56. package/docs/recipes/53-ground-up-close.md +58 -0
  57. package/examples/action/GAMEMAP.md +2 -2
  58. package/examples/action/main.js +3 -2
  59. package/examples/sheepisland/GAMEMAP.md +1 -1
  60. package/examples/styletest/content/npcs.js +1 -1
  61. package/examples/styletest/main.js +1 -1
  62. package/examples/world/content/npcs.js +1 -1
  63. package/examples/world/main.js +1 -1
  64. package/index.d.ts +8 -2
  65. package/index.js +3 -2
  66. package/llms.txt +9 -8
  67. package/modules/characters/Character.js +21 -19
  68. package/modules/characters/assetModel.js +35 -7
  69. package/modules/characters/proceduralRig.js +45 -10
  70. package/modules/content/index.js +1 -1
  71. package/modules/gameplay/pickups.js +1 -1
  72. package/modules/vegetation/Vegetation.js +15 -3
  73. package/modules/vegetation/index.js +1 -1
  74. package/modules/vegetation/nearFade.js +39 -0
  75. package/package.json +2 -1
  76. package/render/detail.js +39 -15
  77. package/types/core.d.ts +7 -5
  78. package/types/gameplay.d.ts +12 -6
  79. package/types/style.d.ts +20 -15
  80. package/types/world.d.ts +7 -1
@@ -77,7 +77,7 @@ function take(inv, rec) {
77
77
  return { ok: true };
78
78
  }
79
79
  const NO_PICKUP = 'pickups: no style pack / model given, so items on the ground are gray boxes (a placeholder). Pass a style pack with '
80
- + "style.pickup.model(item, { color, size }), e.g. createEngine({ style: lowpoly }) with lowpoly from '@threedog/style-lowpoly'";
80
+ + "style.pickup.model(item, { color, size }), e.g. createEngine({ style: yourPack }) with a pack you made or installed";
81
81
  /** The model (built when near) + interaction for this pickup record @internal */
82
82
  function model(inv, rec) {
83
83
  const e = inv.engine, def = inv.item(rec.item), st = e.style.pickup || {};
@@ -7,8 +7,9 @@ import { checkOptions, checkOptionsArg, warnMissing } from '../../core/validate.
7
7
  import { xzOf } from '../../core/math.js';
8
8
  import { GroundChunks } from './groundChunks.js';
9
9
  import { swayOf } from './lookWind.js';
10
+ import { fadeBand, nearFadePatch } from './nearFade.js';
10
11
  // parameters read by vegetation.add(); keys inside rule (sent to the worker thread)
11
- const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided'];
12
+ const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade'];
12
13
  const RULE_KEYS = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'scale', 'stretch', 'sink', 'tintJitter', 'tints', 'biomes', 'collider', 'avoidFlat', 'salt'];
13
14
 
14
15
  // Single-instance removal/restore (chop a tree, mine a rock): records are owned by vegetation and saved with the save (save key 'vegetation', entry
@@ -71,6 +72,8 @@ export class Vegetation {
71
72
  * wind wind sway amplitude (0 disables)
72
73
  * nearOnly generate only near the player (grass, flowers)
73
74
  * maxRing not drawn beyond this ring count
75
+ * fade near-only species shrink out over a band [start, end] metres from the player instead of popping at the ring edge (default on for
76
+ * nearOnly, end = maxRing x chunk size; false = hard edge; { start, end } sets the band)
74
77
  * lodRing switch to low-poly beyond this ring count
75
78
  * castShadow / shadowRing whether to cast shadows, and within how many rings
76
79
  * material custom material, any three.js material (optional, default is the style pack's 'vegetation' role); wind, cloud
@@ -80,14 +83,18 @@ export class Vegetation {
80
83
  checkOptions(`vegetation.add('${name}')`, o, ADD_KEYS);
81
84
  checkOptions(`vegetation.add('${name}').rule`, o.rule, RULE_KEYS);
82
85
  const sw = swayOf(this.engine), wind = o.wind && sw ? { amplitude: o.wind, glsl: sw.glsl, uniforms: sw.uniforms } : o.wind; // look.wind 'sway' (style.wind.glsl or a game's patch) replaces the sway shape
83
- const fx = m => o.effects === false ? m : applyEffects(m, { wind, season: 'foliage' });
86
+ // distance fade of near-only species (nearFade.js): on by default for them, fade: false keeps the hard ring edge, { start, end } sets the band in metres
87
+ if (o.fade && typeof o.fade === 'object') checkOptions(`vegetation.add('${name}').fade`, o.fade, ['start', 'end']);
88
+ const maxRing = o.maxRing ?? (o.nearOnly ? 1 : 99);
89
+ const band = o.effects === false ? null : fadeBand(o.fade, !!o.nearOnly, maxRing, this.host.CHUNK), nf = band && nearFadePatch(band);
90
+ const fx = m => o.effects === false ? m : applyEffects(m, { wind, season: 'foliage', patches: nf ? [nf.patch] : undefined });
84
91
  const mdl = o.model && fromModel(o.model, `vegetation.add('${name}')`);
85
92
  let lod = o.lodGeometry?.isObject3D ? fromModel(o.lodGeometry, `vegetation.add('${name}').lodGeometry`).geometry : o.lodGeometry || null;
86
93
  if (mdl && lod && !lod.groups.length) { lod = lod.clone(); lod.addGroup(0, Infinity, 0); } // a material array draws nothing without groups
87
94
  const sp = {
88
95
  name, geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod,
89
96
  rule: { salt: hashName(name), ...(o.rule || {}) }, // random seed from the name: placement is unaffected by registration order
90
- nearOnly: !!o.nearOnly, maxRing: o.maxRing ?? (o.nearOnly ? 1 : 99), lodRing: o.lodRing ?? 1,
97
+ nearOnly: !!o.nearOnly, maxRing, fade: band, fadeUniforms: nf?.uniforms ?? null, lodRing: o.lodRing ?? 1,
91
98
  castShadow: o.castShadow ?? !o.nearOnly, shadowRing: o.shadowRing ?? 1, receiveShadow: o.receiveShadow ?? true,
92
99
  material: mdl ? mdl.materials.map(fx)
93
100
  : fx(o.material ?? makeMaterial('vegetation', { vertexColors: true, side: o.doubleSided ? THREE.DoubleSide : THREE.FrontSide }, this.engine)),
@@ -117,6 +124,11 @@ export class Vegetation {
117
124
  sp.shadowRing = ring;
118
125
  this.host.refreshLevels();
119
126
  }
127
+ /** @internal module frame hook: the fade band is centred on the view focus (the player in a follow camera) */
128
+ updateFade() {
129
+ const f = this.engine.focus;
130
+ for (const sp of this.species.values()) sp.fadeUniforms?.uNearFadeCenter.value.copy(f);
131
+ }
120
132
  /** @internal terrain plumbing */
121
133
  baseNames() { return this.list().filter(s => !s.nearOnly).map(s => s.name); }
122
134
  /** @internal terrain plumbing */
@@ -36,7 +36,7 @@ export function vegetation(opts = {}) {
36
36
  // terrain installed after vegetation would leave two chunk tables: say where to put it
37
37
  critical: true, // a wrong install order is a setup error, not something to play on with
38
38
  init(e) { if (own && e.terrain) throw new Error('vegetation() was installed before terrain(): put terrain() first, vegetation then grows on its chunks'); },
39
- frame(dt, e) { own?.update(e.stream.sources(), e.camera); },
39
+ frame(dt, e) { v.updateFade(); own?.update(e.stream.sources(), e.camera); },
40
40
  fixed(dt) { v.tick(dt); }, skip(dt, e, done) { if (done) v.tick(1); },
41
41
  describe(e, ctx) { if (own) ctx.out.perf.vegetation = { loaded: own.stats.loaded, visible: own.stats.visible, queued: own.stats.queued }; },
42
42
  dispose() { own?.dispose(); cols?.remove(); ready?.remove(); } };
@@ -0,0 +1,39 @@
1
+ // Distance fade for near-only vegetation (grass, flowers, pebbles, debris ... any species that only exists close to the player).
2
+ // Why: such species are placed per chunk ring (maxRing), so without this the ring edge is a visible line that pops in and out chunk by chunk.
3
+ // How: instances shrink toward their own base over a band [start, end] metres from the player, in the vertex shader of the species' own material:
4
+ // no extra draw call or shader program per frame (the patch is part of the material's one program), the sway of the wind patch is scaled with it, and the
5
+ // shadow pass shrinks the same way. The band ends where the ring can first end, so a clump is already gone when its chunk drops out.
6
+ import * as THREE from 'three';
7
+
8
+ const PARS = 'uniform vec2 uNearFade; uniform vec3 uNearFadeCenter;';
9
+ const VERTEX = `
10
+ {
11
+ vec4 ipo = vec4(0.0, 0.0, 0.0, 1.0);
12
+ #ifdef USE_INSTANCING
13
+ ipo = instanceMatrix * ipo;
14
+ #endif
15
+ vec3 ip = (modelMatrix * ipo).xyz;
16
+ transformed *= 1.0 - smoothstep(uNearFade.x, uNearFade.y, distance(ip.xz, uNearFadeCenter.xz));
17
+ }`;
18
+
19
+ /**
20
+ * The fade band of a species in metres from the player.
21
+ * @param {false | { start?: number, end?: number } | undefined} fade the species' fade option (undefined = default for near-only species)
22
+ * @param {boolean} nearOnly
23
+ * @param {number} maxRing rings drawn around the player
24
+ * @param {number} chunk chunk size in metres
25
+ * @returns {{ start: number, end: number } | null} null = no fade
26
+ */
27
+ export function fadeBand(fade, nearOnly, maxRing, chunk) {
28
+ if (fade === false || (fade === undefined && !nearOnly)) return null;
29
+ // the ring is guaranteed to reach maxRing x chunk in every direction (the player may stand at a chunk edge), so end the fade there
30
+ const end = fade?.end ?? maxRing * chunk, start = fade?.start ?? end * 0.65;
31
+ if (!(end > 0) || !(start >= 0) || start >= end) throw new Error(`vegetation fade: need 0 <= start < end (metres), got start ${start}, end ${end}`);
32
+ return { start, end };
33
+ }
34
+
35
+ /** The shader patch plus the uniform objects (move center each frame) @param {{ start: number, end: number }} band */
36
+ export function nearFadePatch(band) {
37
+ const uniforms = { uNearFade: { value: new THREE.Vector2(band.start, band.end) }, uNearFadeCenter: { value: new THREE.Vector3() } };
38
+ return { patch: { name: 'nearFade', cacheKey: 'v1', shadow: true, uniforms, glsl: { vertex: { pars: PARS, begin_vertex: VERTEX } } }, uniforms };
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "threedog",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Web 3D game engine on three.js for large low-poly worlds: core + modules + style packs, built to be driven by an AI",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,6 +24,7 @@
24
24
  "default": "./index.js"
25
25
  },
26
26
  "./error-hints": "./core/errorHints.js",
27
+ "./grid": "./core/grid.js",
27
28
  "./worker": {
28
29
  "types": "./types/worker.d.ts",
29
30
  "default": "./core/threadServe.js"
package/render/detail.js CHANGED
@@ -7,12 +7,12 @@ import { placeholderTexture, hashText } from './effects.js';
7
7
  import { declareUniforms } from './uniformDecl.js';
8
8
 
9
9
  /**
10
- * @typedef {{ texture?: string | import('three').Texture, noise?: 'grain' | 'paper' | 'stroke', glsl?: string, uniforms?: Record<string, any>,
10
+ * @typedef {{ texture?: string | import('three').Texture, noise?: 'grain' | 'paper' | 'stroke' | 'dabs', glsl?: string, uniforms?: Record<string, any>,
11
11
  * projection?: 'world' | 'triplanar', scale?: number, strength?: number, mode?: 'multiply' | 'add' | 'mix', tint?: import('../types/common').ColorLike,
12
- * direction?: number, stretch?: number, octaves?: number, normal?: number, roughness?: number }} DetailOptions
12
+ * direction?: number, stretch?: number, octaves?: number, normal?: number, roughness?: number, fade?: boolean }} DetailOptions
13
13
  */
14
- const KEYS = ['texture', 'noise', 'glsl', 'uniforms', 'projection', 'scale', 'strength', 'mode', 'tint', 'direction', 'stretch', 'octaves', 'normal', 'roughness'];
15
- const NOISES = ['grain', 'paper', 'stroke'];
14
+ const KEYS = ['texture', 'noise', 'glsl', 'uniforms', 'projection', 'scale', 'strength', 'mode', 'tint', 'direction', 'stretch', 'octaves', 'normal', 'roughness', 'fade'];
15
+ const NOISES = ['grain', 'paper', 'stroke', 'dabs'];
16
16
  const MODES = ['multiply', 'add', 'mix'];
17
17
 
18
18
  const NOISE = `float threedogDHash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
@@ -20,28 +20,52 @@ float threedogDNoise(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*
20
20
  return mix(mix(threedogDHash(i), threedogDHash(i+vec2(1,0)), f.x), mix(threedogDHash(i+vec2(0,1)), threedogDHash(i+vec2(1,1)), f.x), f.y); }
21
21
  float threedogDFbm(vec2 p){ float s = 0.0, a = 0.5, n = 0.0;
22
22
  for (int i = 0; i < 4; i++) { if (float(i) >= uDetailOctaves) break; s += a * threedogDNoise(p); n += a; p = p * 2.03 + 17.0; a *= 0.5; }
23
- return s / n; }`;
23
+ return s / n; }
24
+ // Soft oval brush dabs: one random dab per cell (random size, rotation, tone), no preferred direction. 3x3 cells cover a dab that reaches into a neighbor.
25
+ float threedogDDabs(vec2 p){ float s = 0.5, w = 0.85;
26
+ for (int o = 0; o < 3; o++) { if (float(o) >= uDetailOctaves) break;
27
+ vec2 ip = floor(p); float fo = float(o);
28
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
29
+ vec2 c = ip + vec2(float(i), float(j));
30
+ vec2 h = vec2(threedogDHash(c + fo * 13.1), threedogDHash(c.yx + 7.7 + fo * 5.3));
31
+ float ang = 6.2832 * threedogDHash(c * 1.7 + 3.1 + fo), r = 0.35 + 0.3 * threedogDHash(c * 2.3 + 11.9 + fo), tone = threedogDHash(c + vec2(5.5, 1.3) + fo);
32
+ vec2 d = p - (c + 0.15 + 0.7 * h); float ca = cos(ang), sa = sin(ang);
33
+ d = vec2(ca * d.x + sa * d.y, -sa * d.x + ca * d.y) / vec2(r * 1.3, r * 0.75);
34
+ s = mix(s, tone, (1.0 - smoothstep(0.3, 1.0, length(d))) * w); }
35
+ p = p * 2.03 + 17.0; w *= 0.6; }
36
+ return s; }
37
+ // Size of one pixel in pattern units (1 = one pattern cell): the fade-out and \`glsl\` samples read it
38
+ float threedogDetailFootprint = 0.0;
39
+ float threedogDFp(vec2 p){ return max(length(dFdx(p)), length(dFdy(p))); }
40
+ float threedogDFade = 1.0;
41
+ float threedogDFadeOf(float fp){ return mix(1.0, 1.0 - smoothstep(0.5, 1.0, fp), uDetailFade); }`;
24
42
 
25
43
  // Built-in sources: p is already scaled, turned by direction and stretched along it; returns (color, height)
26
44
  const SOURCES = {
27
45
  tex: 'vec4 threedogDetailSample(vec2 p){ vec3 c = texture2D(uDetail, p).rgb; return vec4(c, dot(c, vec3(0.299, 0.587, 0.114))); }',
28
46
  grain: 'vec4 threedogDetailSample(vec2 p){ float s = threedogDFbm(p); return vec4(vec3(s), s); }',
29
47
  paper: 'vec4 threedogDetailSample(vec2 p){ float s = 0.65 * threedogDFbm(p) + 0.35 * threedogDNoise(vec2(p.x * 7.0, p.y * 0.9)); return vec4(vec3(s), s); }',
48
+ dabs: 'vec4 threedogDetailSample(vec2 p){ float s = threedogDDabs(p); return vec4(vec3(s), s); }',
30
49
  stroke: 'vec4 threedogDetailSample(vec2 p){ float s = smoothstep(0.15, 0.85, threedogDFbm(vec2(p.x, p.y * 1.7))); return vec4(vec3(s), s); }',
31
50
  };
32
51
 
33
52
  // p (world position) -> sample; 'world' looks straight down (xz), 'triplanar' blends the three axis planes by the surface normal
34
53
  const PROJECT = {
35
- world: 'vec4 threedogDetail(vec3 w){ return threedogDetailSample(threedogDetailUV(w.xz)); }',
54
+ world: `vec4 threedogDetail(vec3 w){ vec2 p = threedogDetailUV(w.xz); threedogDetailFootprint = threedogDFp(p); threedogDFade = threedogDFadeOf(threedogDetailFootprint);
55
+ return threedogDetailSample(p); }`,
36
56
  triplanar: `vec4 threedogDetail(vec3 w){
37
57
  vec3 n = abs(normalize(cross(dFdx(w), dFdy(w)))); n /= n.x + n.y + n.z;
38
- return threedogDetailSample(threedogDetailUV(w.zy)) * n.x + threedogDetailSample(threedogDetailUV(w.xz)) * n.y + threedogDetailSample(threedogDetailUV(w.xy)) * n.z; }`,
58
+ vec2 a = threedogDetailUV(w.zy), b = threedogDetailUV(w.xz), c = threedogDetailUV(w.xy);
59
+ float fa = threedogDFp(a), fb = threedogDFp(b), fc = threedogDFp(c);
60
+ threedogDFade = threedogDFadeOf(fa) * n.x + threedogDFadeOf(fb) * n.y + threedogDFadeOf(fc) * n.z;
61
+ threedogDetailFootprint = fa; vec4 sa = threedogDetailSample(a); threedogDetailFootprint = fb; vec4 sb = threedogDetailSample(b); threedogDetailFootprint = fc; vec4 sc = threedogDetailSample(c);
62
+ return sa * n.x + sb * n.y + sc * n.z; }`,
39
63
  };
40
64
 
41
65
  const COLOR = `{ vec3 tdc = threedogDS.rgb * uDetailTint;
42
- if (uDetailMode < 0.5) diffuseColor.rgb *= mix(vec3(1.0), tdc * 2.0, uDetailStrength);
43
- else if (uDetailMode < 1.5) diffuseColor.rgb += (tdc - 0.5) * uDetailStrength;
44
- else diffuseColor.rgb = mix(diffuseColor.rgb, tdc, uDetailStrength); }`;
66
+ if (uDetailMode < 0.5) diffuseColor.rgb *= mix(vec3(1.0), tdc * 2.0, uDetailStrength * threedogDFade);
67
+ else if (uDetailMode < 1.5) diffuseColor.rgb += (tdc - 0.5) * uDetailStrength * threedogDFade;
68
+ else diffuseColor.rgb = mix(diffuseColor.rgb, tdc, uDetailStrength * threedogDFade); }`;
45
69
  // Screen-space bump (the same maths as three's bump map): uDetailBump is the relief height in meters per unit of height
46
70
  const BUMP = `vec3 threedogDetailBump(vec3 surfPos, vec3 surfNorm, float h, float k, float faceDir){
47
71
  vec3 sx = dFdx(surfPos), sy = dFdy(surfPos), r1 = cross(sy, surfNorm), r2 = cross(surfNorm, sx);
@@ -62,7 +86,7 @@ export function detailPatch(o, engine, label = 'detail') {
62
86
  if (o.noise !== undefined && !NOISES.includes(o.noise)) throw new Error(`${label}.noise '${o.noise}' is not a built-in noise; use ${NOISES.join(' | ')}, or write your own with glsl: 'vec4 threedogDetailSample(vec2 p){ ... }'`);
63
87
  const proj = o.projection ?? 'world';
64
88
  if (!PROJECT[proj]) throw new Error(`${label}.projection '${proj}' must be 'world' (top-down) or 'triplanar'`);
65
- if (o.glsl && !/vec4\s+threedogDetailSample\s*\(\s*vec2/.test(o.glsl)) throw new Error(`${label}.glsl must define \`vec4 threedogDetailSample(vec2 p)\`: p is the scaled, turned, stretched position; return vec4(color rgb, height 0-1). uDetailOctaves and the uniforms you list are in scope`);
89
+ if (o.glsl && !/vec4\s+threedogDetailSample\s*\(\s*vec2/.test(o.glsl)) throw new Error(`${label}.glsl must define \`vec4 threedogDetailSample(vec2 p)\`: p is the scaled, turned, stretched position; return vec4(color rgb, height 0-1). uDetailOctaves, threedogDetailFootprint (one pixel in pattern units; fade yourself or leave it to detail.fade) and the uniforms you list are in scope`);
66
90
  const src = o.glsl ? 'glsl:' + hashText(o.glsl) : o.texture ? 'tex' : o.noise ?? 'grain';
67
91
  const isStroke = o.noise === 'stroke', ang = (o.direction ?? 0) * Math.PI / 180;
68
92
  const colorOn = o.strength !== 0 && (o.strength !== undefined || !(o.normal || o.roughness)), bump = !!o.normal, rough = !!o.roughness;
@@ -70,7 +94,7 @@ export function detailPatch(o, engine, label = 'detail') {
70
94
  uDetailScale: { value: o.scale ?? 0.25 }, uDetailStrength: { value: o.strength ?? 0.35 }, uDetailMode: { value: Math.max(0, MODES.indexOf(o.mode ?? 'multiply')) },
71
95
  uDetailTint: { value: new THREE.Color(o.tint ?? 0xffffff) }, uDetailDir: { value: new THREE.Vector2(Math.cos(ang), Math.sin(ang)) },
72
96
  uDetailStretch: { value: o.stretch ?? (isStroke ? 6 : 1) }, uDetailOctaves: { value: o.octaves ?? 2 },
73
- uDetailBump: { value: o.normal ?? 0 }, uDetailRough: { value: o.roughness ?? 0 },
97
+ uDetailBump: { value: o.normal ?? 0 }, uDetailRough: { value: o.roughness ?? 0 }, uDetailFade: { value: o.fade === false ? 0 : 1 },
74
98
  });
75
99
  let decl = '';
76
100
  if (o.texture || o.glsl) {
@@ -91,7 +115,7 @@ export function detailPatch(o, engine, label = 'detail') {
91
115
  }
92
116
  const own = declareUniforms(label + '.uniforms', o.uniforms);
93
117
  Object.assign(u, own.uniforms); decl += '\n' + own.decl;
94
- const pars = `uniform float uDetailScale, uDetailStrength, uDetailMode, uDetailStretch, uDetailOctaves, uDetailBump, uDetailRough;
118
+ const pars = `uniform float uDetailScale, uDetailStrength, uDetailMode, uDetailStretch, uDetailOctaves, uDetailBump, uDetailRough, uDetailFade;
95
119
  uniform vec3 uDetailTint; uniform vec2 uDetailDir; ${decl}
96
120
  ${NOISE}
97
121
  vec2 threedogDetailUV(vec2 w){ vec2 p = w * uDetailScale; p = vec2(uDetailDir.x * p.x + uDetailDir.y * p.y, -uDetailDir.y * p.x + uDetailDir.x * p.y); p.x /= uDetailStretch; return p; }
@@ -99,7 +123,7 @@ ${o.glsl ?? SOURCES[o.texture ? 'tex' : o.noise ?? 'grain']}
99
123
  ${PROJECT[proj]}
100
124
  ${BUMP}`;
101
125
  const fragment = /** @type {Record<string, string>} */ ({ pars, color_fragment: `vec4 threedogDS = threedogDetail(vThreedogWorld);\n${colorOn ? COLOR : ''}` });
102
- if (bump) fragment.normal_fragment_maps = 'normal = threedogDetailBump(-vViewPosition, normal, threedogDS.a, uDetailBump, faceDirection);';
103
- if (rough) fragment.roughnessmap_fragment = 'roughnessFactor = clamp(roughnessFactor + (threedogDS.a - 0.5) * uDetailRough, 0.04, 1.0);';
126
+ if (bump) fragment.normal_fragment_maps = 'normal = threedogDetailBump(-vViewPosition, normal, threedogDS.a, uDetailBump * threedogDFade, faceDirection);';
127
+ if (rough) fragment.roughnessmap_fragment = 'roughnessFactor = clamp(roughnessFactor + (threedogDS.a - 0.5) * uDetailRough * threedogDFade, 0.04, 1.0);';
104
128
  return { name: 'detail', cacheKey: `${src}|${proj}|${colorOn ? 'c' : ''}${bump ? 'n' : ''}${rough ? 'r' : ''}`, needs: { patches: ['world'] }, uniforms: u, glsl: { fragment } };
105
129
  }
package/types/core.d.ts CHANGED
@@ -403,6 +403,8 @@ export interface Assets {
403
403
  modelNow(nameOrUrl: string, opts?: { castShadow?: boolean; receiveShadow?: boolean; static?: boolean }): Object3D | null;
404
404
  /** Get the geometry of the first mesh in a model */
405
405
  geometry(nameOrUrl: string): Promise<BufferGeometry>;
406
+ /** An image as grid data for sampleGrid: PNG at 8 or 16 bits (jpg / webp 8). channel 'r' (default) 'g' 'b' 'a' or 0-3; range maps pixels to [min, max] (default [0, 1]) */
407
+ gridFromImage(nameOrUrl: string, opts?: { channel?: 'r' | 'g' | 'b' | 'a' | number; range?: [number, number]; bits?: 8 | 16 }): Promise<{ data: Float32Array; width: number; height: number; bits: number }>;
406
408
  /** Get a texture (.ktx2 compressed textures also work) */
407
409
  texture(nameOrUrl: string, opts?: { color?: boolean; pixelated?: boolean; repeat?: number[] }): Promise<Texture>;
408
410
  /**
@@ -833,8 +835,8 @@ export interface EngineOptions {
833
835
  /** A ready three.js renderer (WebGLRenderer or compatible) to use instead of creating one; canvas then defaults to renderer.domElement. The engine configures
834
836
  * (pixel ratio, size, tone mapping, shadows) only a renderer it created itself. WebGL is the fully supported path; WebGPU-style renderers may not run shader patches or post effects (recipe 48) */
835
837
  renderer?: any;
836
- /** Style pack (looks only: materials, sky, lighting, post, UI look), e.g. import lowpoly from '@threedog/style-lowpoly', or a list of parts
837
- * deep-merged left to right: [lowpoly, { sky: { sunSize: 600 } }]. Without one: neutral gray placeholders */
838
+ /** Style pack (looks only: materials, sky, lighting, post, UI look), a pack you made or installed (import basePack from 'your-pack'), or a list of parts
839
+ * deep-merged left to right: [basePack, { sky: { sunSize: 600 } }]. Without one: neutral gray placeholders */
838
840
  style?: StyleInput;
839
841
  /** Real-time shadows, default true */
840
842
  shadows?: boolean;
@@ -844,9 +846,9 @@ export interface EngineOptions {
844
846
  antialias?: boolean;
845
847
  /** Turn style post effects on or off by name at startup, e.g. { bloom: false }; default: each effect's own setting (costly ones off on low-tier devices) */
846
848
  post?: Record<string, boolean>;
847
- /** Render resolution, default min(device pixel ratio, 1.5) */
849
+ /** Render resolution, default min(device pixel ratio, 1.5); the low tier uses at least 0.75 x device pixel ratio (never below 1). describe().render.scale reports it */
848
850
  pixelRatio?: number;
849
- /** Automatically lower resolution when the frame rate is too low, default true */
851
+ /** Automatically lower resolution when the frame rate is too low, default true. Never silent: a dev warning once, and describe().render.scale.autoLowered */
850
852
  adaptiveResolution?: boolean;
851
853
  /** Target frame rate for automatic resolution lowering, default 55 */
852
854
  targetFps?: number;
@@ -1176,7 +1178,7 @@ export interface CameraOverride {
1176
1178
  [key: string]: any;
1177
1179
  }
1178
1180
  /** State of automatic resolution */
1179
- export interface AdaptiveState { paused: boolean; on: boolean; target: number; min: number; max: number; [key: string]: any }
1181
+ export interface AdaptiveState { paused: boolean; on: boolean; target: number; min: number; max: number; /** true once the render scale was lowered below max (a dev warning was logged) */ lowered?: boolean; [key: string]: any }
1180
1182
 
1181
1183
  // ======================================================================
1182
1184
  // Look parts engine.look.<part> (recipes/52-look.md)
@@ -545,18 +545,21 @@ export type { Music };
545
545
  // Characters characters() -> engine.characters, engine.npcs
546
546
  // ======================================================================
547
547
 
548
- /** Skeleton of a style pack's custom character: root is the root node, body/head optional, limbs are the swinging limbs */
548
+ /**
549
+ * A ready procedural body ({ rig }): root is the root node, body/head optional, limbs are the swinging limbs. A model asset carries the same shape
550
+ * by object name in root.userData.rig ({ body: 'hips', head: 'head', joints: ['armL'], limbs: [{ joint: 'legL', ... }] }), as an asset pack's humanoid does
551
+ */
549
552
  export interface CharacterRig {
550
553
  root: Object3D;
551
554
  body?: Object3D;
552
555
  head?: Object3D;
553
- /** Named joints, exposed on the character as properties (lowpoly humanoid: armL armR legL legR) */
556
+ /** Named joints, exposed on the character as properties (a humanoid rig: armL armR legL legR) */
554
557
  joints?: Record<string, Object3D>;
555
558
  limbs?: { joint: Object3D; offset: number; amp: number; kind: 'arm' | 'leg'; side?: number }[];
556
559
  }
557
560
  /** Character parameters (shared by the player and NPCs) */
558
561
  export interface CharacterOptions {
559
- /** Colors (default from the style pack's style.character.colors) */
562
+ /** Per-character part colors: recolor the body's meshes marked userData.part (a humanoid rig: body, skin, legs, hair); the style tints by material role */
560
563
  colors?: { body?: ColorLike; skin?: ColorLike; legs?: ColorLike; hair?: ColorLike };
561
564
  /** Walking speed (m/s), default 4.5 */
562
565
  speed?: number;
@@ -587,12 +590,15 @@ export interface CharacterOptions {
587
590
  /** Whether it can jump, default true */
588
591
  canJump?: boolean;
589
592
  /**
590
- * glTF model: what engine.assets.model() returned, or the name of a registered model asset (default style.character.model).
591
- * A name builds the character at once with the placeholder body and swaps in a copy of the asset when it loads (see Character.ready / whenReady,
592
- * event 'character:model')
593
+ * The body, one path for every kind: the name of a registered model asset, or what engine.assets.model() returned. A procedural builder name
594
+ * (from an asset pack) is built at once; a file model name shows a gray capsule and swaps in a copy when it loads (Character.ready / whenReady,
595
+ * event 'character:model'). Without model and rig: a gray capsule placeholder (warned once)
596
+ * @example engine.assets.manifest(yourAssets); engine.characters.createPlayer({ model: 'yourBody' }) // a generator or GLB name from an asset pack
593
597
  * @example engine.characters.createPlayer({ model: 'hero' }) // after engine.assets.manifest({ models: { hero: '/models/hero.glb' } })
594
598
  */
595
599
  model?: Object3D | string | null;
600
+ /** A ready procedural body (CharacterRig), used instead of model (a hand-built guard / pet) */
601
+ rig?: CharacterRig | null;
596
602
  /** Action name mapping { idle, walk, run, swim, jump, fall } (shorthand for animation) */
597
603
  clips?: { idle?: string; walk?: string; run?: string; swim?: string; jump?: string; fall?: string; drive?: string } | null;
598
604
  /** Skeletal animation state machine config (states, blend trees, one-shot actions), see AnimatorOptions */
package/types/style.d.ts CHANGED
@@ -3,11 +3,11 @@
3
3
  // files or generators (asset packs, engine.assets.manifest), gameplay data (content packs, engine.content.load), and anything that changes the world or
4
4
  // the rules: water level / sea / size go to water({ level, sea, size }), terrain shape and size to terrain({...}) (a dev error says so). Swapping the style must
5
5
  // never move the map. A style may be a list of parts (StyleInput).
6
- // Example: the optional @threedog/style-lowpoly package (packages/styles/lowpoly/index.js).
6
+ // Example: any style pack, a folder with index.js (yours, or a published one); see recipes/09-style-pack.md.
7
7
  import type { ColorLike, BufferGeometry, Object3D, Material, Loose } from './common';
8
8
  import type { Engine } from './core';
9
9
  import type { SteepRule, WeatherPreset, TerrainConfig, Sky } from './world';
10
- import type { ParticleOptions, CharacterRig } from './gameplay';
10
+ import type { ParticleOptions } from './gameplay';
11
11
  import type { ShaderPatch } from './generated/render/patches';
12
12
 
13
13
  /** Material finish: 'lambert' matte | 'phong' with highlights | 'standard' realistic | 'physical' | 'toon' cel-shaded steps | 'basic' unlit */
@@ -43,13 +43,13 @@ export interface MaterialSpec {
43
43
  }
44
44
 
45
45
  /**
46
- * The `detail` surface patch. Source: texture (asset name) or noise ('grain' | 'paper' | 'stroke', default grain) or glsl (your own sampler
46
+ * The `detail` surface patch. Source: texture (asset name) or noise ('grain' | 'paper' | 'stroke' | 'dabs', default grain) or glsl (your own sampler
47
47
  * function). Effects: color (strength, mode), normal (relief height in meters), roughness (amount). Every number is a uniform, so many materials
48
48
  * with different values share one shader program. Channels (color / normal / roughness) are fixed when the material is made.
49
49
  */
50
50
  export interface MaterialDetail {
51
51
  texture?: string | import('three').Texture;
52
- noise?: Loose<'grain' | 'paper' | 'stroke'>;
52
+ noise?: Loose<'grain' | 'paper' | 'stroke' | 'dabs'>;
53
53
  /** Replaces the noise: `vec4 threedogDetailSample(vec2 p)` returns vec4(color rgb, height 0-1); p is scaled, turned, stretched */
54
54
  glsl?: string;
55
55
  /** Uniforms for glsl: numbers, colors, [x, y(, z, w)] arrays or textures */
@@ -64,6 +64,8 @@ export interface MaterialDetail {
64
64
  mode?: Loose<'multiply' | 'add' | 'mix'>;
65
65
  /** Colors the sample (default white) */
66
66
  tint?: ColorLike;
67
+ /** Default true: the effect fades out where the pattern is smaller than about a pixel (far away, grazing angles), so it does not shimmer. `false` keeps it. In `glsl`, `threedogDetailFootprint` is one pixel in pattern units */
68
+ fade?: boolean;
67
69
  /** Degrees; turns the pattern (strokes run along it) */
68
70
  direction?: number;
69
71
  /** Stretches the pattern along direction (default 1, strokes 6) */
@@ -504,8 +506,12 @@ export interface StyleTerrain {
504
506
  config?: { shading?: Loose<'flat' | 'smooth' | 'texture'>; colorResolution?: number; normals?: Loose<'smooth' | 'flat'>; normalFn?: TerrainConfig['normalFn'] };
505
507
  /** Whole ground material: a Material or (engine) => Material (uv = world xz / chunk size; terrain({ material }) wins) */
506
508
  material?: Material | ((engine: Engine) => Material);
507
- /** Ground detail texture: texture asset name, scale repeats per meter, strength 0–1 */
508
- detail?: { texture: string; scale?: number; strength?: number };
509
+ /**
510
+ * Detail layer over the ground, the same object as a material spec's `detail`: a noise ('grain' | 'paper' | 'stroke' | 'dabs'), a texture
511
+ * asset name, or your own `glsl`; plus scale, strength, fade ... (top-down world projection by default). Live: look.ground.set({ detail }).
512
+ * See recipes/53-ground-up-close.md
513
+ */
514
+ detail?: MaterialDetail;
509
515
  }
510
516
 
511
517
  /** UI template function: (data, helpers) => HTML string */
@@ -557,12 +563,12 @@ export interface Style {
557
563
  /** Style pack name */
558
564
  name?: string;
559
565
  /**
560
- * Exposure, default 1 (lowpoly: 1.05): a number, or over the day [[time 0-1, exposure], ...] (sorted, wraps across midnight) or (sky) => number,
566
+ * Exposure, default 1: a number, or over the day [[time 0-1, exposure], ...] (sorted, wraps across midnight) or (sky) => number,
561
567
  * evaluated by the sky module every frame. engine.look.tone.set changes it at run time
562
568
  * @example exposure: [[0, 1.6], [0.3, 1], [0.75, 1.1]] // brighter nights
563
569
  */
564
570
  exposure?: number | number[][] | ((sky: any) => number);
565
- /** Tone mapping. Engine default 'none' (no style pack, no tone mapping); the style pack picks the look (lowpoly: 'aces') */
571
+ /** Tone mapping. Engine default 'none' (no style pack, no tone mapping); the style pack picks the look */
566
572
  toneMapping?: Loose<'aces' | 'agx' | 'neutral' | 'none'>;
567
573
  /** Background color (when there is no sky module) */
568
574
  background?: ColorLike;
@@ -590,11 +596,11 @@ export interface Style {
590
596
  * way to the color. Season names are the other keys, so none can be called mode or strength
591
597
  */
592
598
  seasons?: StyleSeasons;
593
- /** Cloud shadow: shadow darkest level 0–1 (default 0 = no cloud shadows; lowpoly 0.55), scale cloud size (smaller means bigger clouds), speed [x, z] */
599
+ /** Cloud shadow: shadow darkest level 0–1 (default 0 = no cloud shadows), scale cloud size (smaller means bigger clouds), speed [x, z] */
594
600
  clouds?: { shadow?: number; scale?: number; speed?: number[] };
595
601
  /**
596
- * Named colors the procedural model generators read (trees, rocks, grass: a generator written with `function` gets them as this.palette; lowpoly keys:
597
- * bark, pine, leaf, rock, grassTip...). One place to retint all of them, e.g. style: [lowpoly, { palette: { leaf: 0xd98a3a } }]; keys left out keep the pack's values
602
+ * Named colors the procedural model generators read (trees, rocks, grass: a generator written with `function` gets them as this.palette; a pack may use keys like
603
+ * bark, pine, leaf, rock, grassTip...). One place to retint all of them, e.g. style: [basePack, { palette: { leaf: 0xd98a3a } }]; keys left out keep the pack's values
598
604
  */
599
605
  palette?: Record<string, ColorLike>;
600
606
  /** Wind: frequency sway frequency multiplier */
@@ -613,11 +619,10 @@ export interface Style {
613
619
  */
614
620
  pickup?: { color?: ColorLike; size?: number; lift?: number; model?: (item: any, o: { color: ColorLike; size: number }, engine: Engine) => Object3D | BufferGeometry };
615
621
  /**
616
- * Default character: colors palette; create(engine, colors) returns the procedural character (without it a gray capsule); model names a registered
617
- * model asset every character uses unless it passes its own model (the procedural body shows until it loads); animation.fade skeletal animation
618
- * transition seconds
622
+ * How character motion looks: animation.fade skeletal animation transition seconds. Bodies are assets, not style ({ model: 'yourBody' } from
623
+ * an asset pack); a style tints body parts through materials roles (cloth, skin, trousers, hair). create / model / colors here throw renamed-api
619
624
  */
620
- character?: { model?: string; colors?: { body?: ColorLike; skin?: ColorLike; legs?: ColorLike; hair?: ColorLike }; create?: (engine: Engine, colors: Record<string, ColorLike>) => CharacterRig | null | undefined; animation?: { fade?: number } };
625
+ character?: { animation?: { fade?: number } };
621
626
  /** UI colors, fonts, templates */
622
627
  ui?: StyleUI;
623
628
  /** Particle presets: name → parameters; default is the fallback for all effects */
package/types/world.d.ts CHANGED
@@ -274,6 +274,12 @@ export interface VegetationOptions {
274
274
  nearOnly?: boolean;
275
275
  /** No longer drawn beyond this many rings */
276
276
  maxRing?: number;
277
+ /**
278
+ * Distance fade of a near-only species (grass, flowers, pebbles, debris ...): instances shrink out over a band in metres from the player instead of popping
279
+ * per chunk at the ring edge. Default for nearOnly: end = maxRing x chunk size, start = 65% of it. `false` keeps the hard ring edge (also the default for
280
+ * species that are not nearOnly). Part of the species' own material (no extra draw call or shader), works with wind and shadows
281
+ */
282
+ fade?: false | { start?: number; end?: number };
277
283
  /** Switch to the low-detail model beyond this many rings, default 1 */
278
284
  lodRing?: number;
279
285
  /** Cast shadows */
@@ -292,7 +298,7 @@ export interface VegetationOptions {
292
298
  /** A registered kind of vegetation */
293
299
  export interface Species {
294
300
  name: string; geometry: BufferGeometry; lodGeometry: BufferGeometry | null; rule: VegetationRule;
295
- nearOnly: boolean; maxRing: number; lodRing: number; castShadow: boolean; shadowRing: number; receiveShadow: boolean; material: Material | Material[];
301
+ nearOnly: boolean; maxRing: number; fade: { start: number; end: number } | null; lodRing: number; castShadow: boolean; shadowRing: number; receiveShadow: boolean; material: Material | Material[];
296
302
  }
297
303
  /** A found plant: species name, chunk cx/cz, stable id, world coordinates position */
298
304
  export interface VegetationHit { species: string; cx: number; cz: number; id: number; position: Vector3 }