threedog 0.1.0 → 0.2.0
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.
- package/core/Animator.js +1 -0
- package/core/Assets.js +16 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +14 -3
- package/core/Engine.js +32 -69
- package/core/Events.js +59 -1
- package/core/I18n.js +2 -2
- package/core/Inspect.js +12 -32
- package/core/InspectScene.js +7 -3
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +43 -59
- package/core/Saves.js +5 -4
- package/core/UrlState.js +3 -2
- package/core/Vars.js +1 -0
- package/core/Views.js +49 -0
- package/core/actor.js +2 -2
- package/core/assetReport.js +83 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +11 -4
- package/core/errorCodes.js +33 -0
- package/core/errorHints.js +6 -1
- package/core/holds.js +106 -0
- package/core/lifecycle.js +1 -0
- package/core/lightWatch.js +23 -3
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +15 -14
- package/core/modules.js +19 -5
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +25 -14
- package/core/opsFail.js +20 -0
- package/core/opsHistory.js +6 -6
- package/core/opsRun.js +77 -0
- package/core/params.js +132 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +2 -2
- package/core/sceneMethods.js +9 -34
- package/core/services.js +73 -0
- package/core/startup.js +3 -1
- package/core/styleParts.js +2 -2
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +35 -24
- package/core/things.js +15 -1
- package/core/util.js +11 -0
- package/core/validate.js +23 -7
- package/docs/AI.md +83 -109
- package/docs/API.md +7 -8
- package/docs/CODEMAP.md +63 -51
- package/docs/COMMANDS.md +17 -5
- package/docs/CONVENTIONS.md +17 -6
- package/docs/THREE.md +3 -3
- package/docs/api/assets.md +2 -0
- package/docs/api/characters.md +2 -0
- package/docs/api/collision.md +4 -0
- package/docs/api/content.md +1 -0
- package/docs/api/engine.md +20 -11
- package/docs/api/events.md +5 -1
- package/docs/api/post.md +5 -4
- package/docs/api/saves.md +2 -1
- package/docs/api/sky.md +3 -3
- package/docs/api/style.md +3 -3
- package/docs/api/tools.md +2 -0
- package/docs/api/weather.md +1 -1
- package/docs/recipes/02-npc.md +16 -0
- package/docs/recipes/03-items-pickups.md +1 -1
- package/docs/recipes/06-clock-events.md +13 -0
- package/docs/recipes/07-flow-scenes-pause.md +4 -0
- package/docs/recipes/08-weather-sky.md +1 -1
- package/docs/recipes/09-style-pack.md +5 -5
- package/docs/recipes/12-navmesh.md +22 -0
- package/docs/recipes/13-animation.md +3 -0
- package/docs/recipes/15-perf.md +1 -1
- package/docs/recipes/16-dev-bridge.md +51 -17
- package/docs/recipes/21-camera.md +51 -2
- package/docs/recipes/23-ops.md +45 -9
- package/docs/recipes/27-net.md +1 -1
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/34-environment-lighting.md +9 -8
- package/docs/recipes/38-environment-look-hooks.md +8 -6
- package/docs/recipes/40-scene.md +29 -0
- package/docs/recipes/41-thing-registry.md +29 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
- package/docs/recipes/44-water-weather-look-hooks.md +6 -4
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +22 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/action/content/index.js +2 -1
- package/examples/action/content/views.js +6 -0
- package/examples/sheepisland/GAMEMAP.md +2 -3
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/styletest/main.js +1 -1
- package/examples/styletest/panel.js +3 -3
- package/examples/world/GAMEMAP.md +3 -3
- package/index.d.ts +27 -0
- package/index.js +3 -1
- package/llms.txt +5 -0
- package/modules/ambience/Ambience.js +5 -2
- package/modules/camera/FirstPersonCamera.js +3 -5
- package/modules/camera/FixedCamera.js +19 -12
- package/modules/camera/FollowCamera.js +14 -8
- package/modules/camera/RtsCamera.js +3 -5
- package/modules/camera/common.js +40 -10
- package/modules/camera/index.js +1 -1
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +29 -17
- package/modules/characters/astar.js +14 -7
- package/modules/characters/index.js +6 -3
- package/modules/characters/movers/simple.js +6 -1
- package/modules/characters/npcSim.js +8 -2
- package/modules/characters/pathAsync.js +12 -6
- package/modules/characters/pathJob.js +2 -1
- package/modules/characters/proceduralRig.js +5 -1
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +102 -4
- package/modules/content/explain.js +13 -0
- package/modules/content/index.js +2 -0
- package/modules/content/loader.js +3 -0
- package/modules/content/rules.js +1 -0
- package/modules/debug/DebugPanel.js +11 -5
- package/modules/entities/Entities.js +6 -2
- package/modules/flow/index.js +5 -2
- package/modules/gameplay/Dialogue.js +5 -2
- package/modules/gameplay/Interactions.js +12 -2
- package/modules/gameplay/Inventory.js +21 -11
- package/modules/gameplay/Quests.js +13 -3
- package/modules/gameplay/pickups.js +5 -3
- package/modules/grid/Layer.js +1 -1
- package/modules/grid/index.js +1 -1
- package/modules/grid/tiles.js +9 -5
- package/modules/hlod/index.js +5 -2
- package/modules/hud/index.js +5 -2
- package/modules/level/index.js +5 -3
- package/modules/lights/index.js +5 -2
- package/modules/music/Music.js +6 -2
- package/modules/nav/index.js +5 -3
- package/modules/net/Client.js +4 -3
- package/modules/net/Host.js +2 -2
- package/modules/net/index.js +5 -3
- package/modules/particles/Particles.js +1 -1
- package/modules/photo/Photo.js +10 -7
- package/modules/rigid/RigidBodies.js +5 -2
- package/modules/settings/Settings.js +6 -3
- package/modules/settings/apply.js +2 -1
- package/modules/sky/Sky.js +21 -19
- package/modules/sky/cascades.js +6 -6
- package/modules/sky/domeLayers.js +1 -1
- package/modules/sky/environment.js +39 -13
- package/modules/sky/fog.js +9 -6
- package/modules/sky/frame.js +4 -3
- package/modules/sky/look.js +3 -2
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/shader.js +2 -2
- package/modules/sky/shadow.js +4 -10
- package/modules/sky/skyModule.js +4 -3
- package/modules/terrain/ChunkManager.js +2 -33
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/index.js +10 -2
- package/modules/terrain/lookGround.js +61 -0
- package/modules/timeline/Timeline.js +7 -3
- package/modules/timeline/Tween.js +3 -7
- package/modules/timeline/shots.js +6 -4
- package/modules/triggers/index.js +9 -2
- package/modules/vegetation/Vegetation.js +2 -1
- package/modules/vegetation/index.js +6 -3
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/water/Water.js +19 -3
- package/modules/water/look.js +80 -0
- package/modules/weather/Weather.js +22 -31
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +1 -1
- package/modules/weather/strings.js +15 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +11 -4
- package/modules/world/thingSource.js +44 -0
- package/package.json +1 -1
- package/render/PostFX.js +48 -51
- package/render/effects.js +4 -2
- package/render/fuse.js +12 -0
- package/render/lights.js +4 -2
- package/render/lookSurface.js +161 -0
- package/render/materials.js +27 -10
- package/render/postLook.js +86 -0
- package/render/surface.js +3 -1
- package/types/core.d.ts +216 -24
- package/types/gameplay.d.ts +10 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +43 -0
- package/types/generated/core/Ops.d.ts +62 -21
- package/types/generated/core/Saves.d.ts +1 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
- package/types/generated/modules/grid/Layer.d.ts +1 -0
- package/types/generated/modules/sky/Sky.d.ts +10 -17
- package/types/generated/modules/weather/Weather.d.ts +5 -15
- package/types/generated/render/PostFX.d.ts +20 -23
- package/types/generated/render/materials.d.ts +10 -0
- package/types/physics.d.ts +8 -0
- package/types/style.d.ts +16 -6
- package/ui/Parts.js +6 -2
- package/ui/UI.js +1 -1
- package/ui/defaults.js +1 -1
- package/docs/api/debug.md +0 -10
package/modules/sky/fog.js
CHANGED
|
@@ -18,7 +18,8 @@ import * as THREE from 'three';
|
|
|
18
18
|
import { checkOptions, closest } from '../../core/validate.js';
|
|
19
19
|
|
|
20
20
|
const KINDS = ['linear', 'exp', 'exp2', 'height'];
|
|
21
|
-
const
|
|
21
|
+
export const FOG_KINDS = KINDS;
|
|
22
|
+
const KEYS = ['kind', 'color', 'density', 'height', 'falloff', 'glsl', 'near', 'far', 'enabled']; // near / far / enabled: look.fog (lookFog.js)
|
|
22
23
|
const NAMES = ['fog_pars_vertex', 'fog_vertex', 'fog_pars_fragment', 'fog_fragment'];
|
|
23
24
|
const ORIGINAL = Object.fromEntries(NAMES.map(n => [n, THREE.ShaderChunk[n]]));
|
|
24
25
|
// fog amount reached at the far distance with the derived density: exp(-3.9) = 2% (exp, height), exp(-1.98^2) = 2% (exp2)
|
|
@@ -47,7 +48,7 @@ export function resolveFog(spec) {
|
|
|
47
48
|
throw new Error('style.sky.fog.glsl must be GLSL that defines `vec4 threedogFog(vec3 color, float depth, vec3 worldPos)` returning (fog rgb, amount 0..1); see modules/sky/fog.js');
|
|
48
49
|
const color = s.color ?? 'horizon';
|
|
49
50
|
return { kind, color: color === 'horizon' || typeof color === 'function' ? color : new THREE.Color(color), density: s.density ?? null,
|
|
50
|
-
height: s.height ?? 0, falloff: s.falloff ?? 0.05, glsl: s.glsl ?? FN[kind] ?? null };
|
|
51
|
+
height: s.height ?? 0, falloff: s.falloff ?? 0.05, glsl: s.glsl ?? FN[kind] ?? null, near: s.near ?? null, far: s.far ?? null, enabled: s.enabled !== false };
|
|
51
52
|
}
|
|
52
53
|
|
|
53
54
|
/** The fog object for the kind: density-based kinds use FogExp2 (its fogDensity uniform is live), linear uses Fog */
|
|
@@ -119,14 +120,16 @@ function release(h) {
|
|
|
119
120
|
/** Per frame: fog color and distance / density from the sky's horizon and the modifier layers (fog multiplies the distance) */
|
|
120
121
|
export function updateFog(sky, horizon, M) {
|
|
121
122
|
// only when the sky drives fog (sky({ fog: true })) and scene.fog is still a fog object: the game may have nulled or replaced it
|
|
122
|
-
const fog = sky.engine.scene.fog, f = sky._fog
|
|
123
|
-
if (sky._drive.fog !== true || !fog?.color) return;
|
|
123
|
+
const fog = sky.engine.scene.fog, f = sky._fog;
|
|
124
|
+
if (sky._drive.fog !== true || sky._fogHeld || !fog?.color) return; // _fogHeld: look.fog.replace(...) gave the fog to the game
|
|
125
|
+
// look.fog: far / near set explicitly are the base distance (weather still scales it); enabled false pushes the fog out of reach without a recompile
|
|
126
|
+
const far = f.enabled ? (f.far ?? sky.engine.fogFar) * M.fog : 1e9;
|
|
124
127
|
if (f.color === 'horizon') fog.color.copy(horizon);
|
|
125
128
|
else if (typeof f.color === 'function') fog.color.set(f.color(sky));
|
|
126
129
|
else fog.color.copy(f.color);
|
|
127
130
|
// near / far are written for every kind: engine.setFogFar and the dev guard read them
|
|
128
|
-
fog.far = far; fog.near = far * 0.3;
|
|
129
|
-
if (f.kind !== 'linear') fog.density = f.density != null ? f.density / M.fog : REACH[f.kind] / far;
|
|
131
|
+
fog.far = far; fog.near = f.enabled && f.near != null ? f.near * M.fog : far * 0.3;
|
|
132
|
+
if (f.kind !== 'linear') fog.density = !f.enabled ? 0 : f.density != null ? f.density / M.fog : REACH[f.kind] / far;
|
|
130
133
|
}
|
|
131
134
|
|
|
132
135
|
/** Dome addition when the fog color is not the horizon: the dome's lower band fades to the fog color so the horizon line does not show */
|
package/modules/sky/frame.js
CHANGED
|
@@ -12,7 +12,7 @@ const STRINGS = {
|
|
|
12
12
|
sunColor: "edit style pack sky.keyframes or use engine.sky.modify('layerName', { tint, tintAmount })",
|
|
13
13
|
sunPos: 'sun position is driven by sky.timeOfDay',
|
|
14
14
|
hemi: "use engine.sky.modify('layerName', { ambient })",
|
|
15
|
-
fog: "use engine.sky.modify('layerName', { fog }) or engine.setFogFar(); to own scene.fog, create the sky with sky({ fog: 'manual' }) (or false)",
|
|
15
|
+
fog: "use look.fog.set({ color, density, far }), engine.sky.modify('layerName', { fog }) or engine.setFogFar(); to own scene.fog, create the sky with sky({ fog: 'manual' }) (or false)",
|
|
16
16
|
modifiers: "sky.modifiers is the composite of all layers; use engine.sky.modify('layerName', { sun, ambient, fog, ... })",
|
|
17
17
|
};
|
|
18
18
|
|
|
@@ -27,7 +27,7 @@ export function watchOwned(sky) {
|
|
|
27
27
|
D.sun !== false && ownedProps('sky.sun.position', () => sky.sun.position.toArray(), STRINGS.sunPos),
|
|
28
28
|
D.hemi === true && ownedProps('sky.hemi', () => [sky.hemi.intensity, ...sky.hemi.color.toArray(), ...sky.hemi.groundColor.toArray()], STRINGS.hemi),
|
|
29
29
|
// fog: the object itself, color, near/far ratio (engine.setFogFar keeps the ratio, so it is not a violation)
|
|
30
|
-
D.fog === true && ownedProps('scene.fog', () => [fog(), ...(fog()?.color?.toArray() ?? []), fog()?.near / fog()?.far], STRINGS.fog),
|
|
30
|
+
D.fog === true && ownedProps('scene.fog', () => sky._fogHeld ? [null] : [fog(), ...(fog()?.color?.toArray() ?? []), fog()?.near / fog()?.far], STRINGS.fog),
|
|
31
31
|
ownedProps('sky.modifiers', () => { const M = sky.modifiers; return [M.sun, M.ambient, M.fog, M.tintAmount, M.horizonTintAmount, M.flash, ...M.tint.toArray()]; }, STRINGS.modifiers),
|
|
32
32
|
].filter(Boolean);
|
|
33
33
|
}
|
|
@@ -66,8 +66,9 @@ export function updateSky(sky, focus) {
|
|
|
66
66
|
sky.hemi.color.copy(u.uTop.value).lerp(u.uHorizon.value, 0.5);
|
|
67
67
|
sky.hemi.groundColor.copy(sky.groundTint).multiplyScalar(0.4 + 0.6 * Math.min(1, hemiI));
|
|
68
68
|
}
|
|
69
|
+
sky.engine.look.lights.applyTop(); // a game look.lights.set({ sun: { intensity } }) wins over the keyframes (look/part.js)
|
|
69
70
|
const ex = sky.engine.exposureDriver;
|
|
70
|
-
if (ex) sky.engine.renderer.toneMappingExposure = ex(sky); // style.exposure keyframes / function (engine.
|
|
71
|
+
if (ex) sky.engine.renderer.toneMappingExposure = ex(sky); // style.exposure keyframes / function (engine.look.tone.set)
|
|
71
72
|
|
|
72
73
|
if (sky.skybox) sky.engine.scene.backgroundIntensity = Math.max(0.05, hemiI * M.ambient / 1.2);
|
|
73
74
|
if (sky.csm) cascadeFrame(sky, lightDir); // cascades place their own lights from the camera (cascades.js)
|
package/modules/sky/look.js
CHANGED
|
@@ -28,7 +28,8 @@ export function prepareLook(sky, st, over) {
|
|
|
28
28
|
if (sky._drive.sun === false) { sun.visible = false; sun.castShadow = false; }
|
|
29
29
|
if (sky._drive.hemi === false) hemi.visible = false;
|
|
30
30
|
/** @internal resolved fog settings (fog.js) */
|
|
31
|
-
sky.
|
|
31
|
+
sky._fogSpec = fogObj || over.fog == null ? st.fog : sky.engine.style.sky?.fog; // look.fog's style layer (lookFog.js)
|
|
32
|
+
sky._fog = resolveFog(sky._fogSpec);
|
|
32
33
|
sky._backdrop = resolveBackdrop(st);
|
|
33
34
|
const f = domeFog(sky._fog), l = resolveDomeLayers(st.layers);
|
|
34
35
|
const uniforms = { ...l.uniforms };
|
|
@@ -40,7 +41,7 @@ export function prepareLook(sky, st, over) {
|
|
|
40
41
|
// style.sky.backdrop: one flat color (or (sky) => color each frame) instead of the dome -- no gradient, horizon, sun / moon disk,
|
|
41
42
|
// stars or clouds. The color goes straight to scene.background (no tone mapping), so what is written is what shows; the keyframes
|
|
42
43
|
// still light the world, and fog in its default 'horizon' color follows the backdrop so far things fade into it.
|
|
43
|
-
function resolveBackdrop(st) {
|
|
44
|
+
export function resolveBackdrop(st) {
|
|
44
45
|
const v = st.backdrop;
|
|
45
46
|
if (v == null) return null;
|
|
46
47
|
const color = typeof v === 'number' || typeof v === 'string' || v.isColor;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// look.fog: the sky's fog as a look part. set({ kind, color, density, near, far, height, falloff, enabled }), patch('fog', glsl), replace('manual' | THREE.Fog).
|
|
2
|
+
// The sky still writes color and distance every frame (updateFog in fog.js) from the resolved values, so a game set() simply changes what it writes.
|
|
3
|
+
// What cannot change after the first frame: kind 'exp' / 'height', height, falloff and the 'fog' hook replace three's shared fog_* shader chunks, and
|
|
4
|
+
// three compiles each material once (fog.js explains). Those are accepted before the first frame (style, sky({ fog }), or right after createEngine) and
|
|
5
|
+
// throw afterwards, naming the way out. kind linear <-> exp2, color, density, near, far, enabled work live. The dome's horizon band (a fog-colored fade
|
|
6
|
+
// so the horizon line hides) is part of the dome shader and exists only when the start color was not 'horizon'.
|
|
7
|
+
import { defineLookPart, REPLACE } from '../../core/look/part.js';
|
|
8
|
+
import { resolveFog, makeFog, applyFogChunks, FOG_KINDS } from './fog.js';
|
|
9
|
+
|
|
10
|
+
const LATE = "look.fog: {what} changes three.js's shared fog shader chunks, which are compiled once per material, so it can only be set before the first frame " +
|
|
11
|
+
"(style.sky.fog, sky({ fog }), or right after createEngine). Live now: color, density, near, far, enabled, and kind 'linear' <-> 'exp2'";
|
|
12
|
+
const chunkKey = f => (f.glsl ? JSON.stringify([f.kind, f.height, f.falloff, f.glsl]) : '');
|
|
13
|
+
|
|
14
|
+
/** @param {any} sky @param {object} spec the style.sky.fog settings in use (look.js keeps them in sky._fogSpec) */
|
|
15
|
+
export function defineFogLook(sky, spec) {
|
|
16
|
+
const e = sky.engine, scene = e.scene;
|
|
17
|
+
const rendered = () => (e.renderer?.info?.render?.frame ?? 0) > 0;
|
|
18
|
+
let part;
|
|
19
|
+
sky._fogHeld = false;
|
|
20
|
+
sky._fogKey = chunkKey(sky._fog);
|
|
21
|
+
const late = (key, what) => v => (rendered() && v !== part?.value(key) && (sky._fogKey || (key === 'kind' && (v === 'exp' || v === 'height'))) ? LATE.replace('{what}', what) : null);
|
|
22
|
+
|
|
23
|
+
const rebuild = () => {
|
|
24
|
+
const v = part.values(), glsl = part.value('hook:fog');
|
|
25
|
+
const f = resolveFog({ kind: v.kind, color: v.color, density: v.density ?? undefined, height: v.height, falloff: v.falloff, near: v.near ?? undefined,
|
|
26
|
+
far: v.far ?? undefined, enabled: v.enabled, glsl: typeof glsl === 'string' ? glsl : undefined });
|
|
27
|
+
const key = chunkKey(f);
|
|
28
|
+
if (key !== sky._fogKey) {
|
|
29
|
+
if (rendered()) throw new Error(LATE.replace('{what}', 'this fog change'));
|
|
30
|
+
sky._fogOff();
|
|
31
|
+
try { sky._fogOff = applyFogChunks(f); } catch (err) { sky._fogOff = applyFogChunks(sky._fog); throw err; }
|
|
32
|
+
sky._fogKey = key;
|
|
33
|
+
}
|
|
34
|
+
sky._fog = f;
|
|
35
|
+
// linear is three's Fog, every other kind FogExp2: swap the object (materials recompile for it) when the kind crossed that line
|
|
36
|
+
const cur = scene.fog;
|
|
37
|
+
if (sky._drive.fog === true && !sky._fogHeld && cur && (f.kind === 'linear' ? !cur.isFog : !cur.isFogExp2)) {
|
|
38
|
+
scene.fog = makeFog(f, f.far ?? e.fogFar); scene.fog.color.copy(cur.color);
|
|
39
|
+
for (const o of sky._owned ?? []) o.mark();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
part = defineLookPart(e, {
|
|
44
|
+
id: 'fog', group: 'atmosphere', module: 'sky', object: () => scene.fog, applyAtStart: false, docs: ['recipes/52-look.md', 'recipes/38-sky.md'],
|
|
45
|
+
params: {
|
|
46
|
+
enabled: { type: 'bool', default: true, cost: 'uniform', desc: 'fog on / off without a recompile',
|
|
47
|
+
why: 'distant things melt into the sky and the edge of a streamed world is hidden', off: 'look.fog.set({ enabled: false }), or sky({ fog: false })' },
|
|
48
|
+
kind: { type: 'string', default: 'linear', values: FOG_KINDS, cost: 'shader', desc: "'linear' | 'exp' | 'exp2' | 'height'", neutral: true,
|
|
49
|
+
check: late('kind', "kind 'exp' / 'height'") },
|
|
50
|
+
color: { type: 'any', default: 'horizon', cost: 'uniform', desc: "'horizon' (the dome's horizon color, written every frame) | a color | (sky) => color", neutral: true },
|
|
51
|
+
density: { type: 'any', default: null, cost: 'uniform', neutral: true, desc: 'per meter for exp / exp2 / height; null = derived so the fog reaches the same distance as linear' },
|
|
52
|
+
far: { type: 'any', default: null, cost: 'uniform', desc: 'fog distance in meters (weather scales it); null = engine.fogFar (createEngine, terrain view range)',
|
|
53
|
+
why: 'fog reaches full strength at engine.fogFar (600 by default), starting at 0.3 x that', off: 'look.fog.set({ enabled: false })' },
|
|
54
|
+
near: { type: 'any', default: null, cost: 'uniform', neutral: true, desc: 'linear only: where the fog starts; null = 0.3 x far' },
|
|
55
|
+
height: { type: 'number', default: 0, neutral: true, cost: 'shader', desc: "kind 'height': the fog's floor (world y)", check: late('height', 'height') },
|
|
56
|
+
falloff: { type: 'number', default: 0.05, min: 0, neutral: true, cost: 'shader', desc: "kind 'height': how fast it thins above the floor (per meter)", check: late('falloff', 'falloff') },
|
|
57
|
+
},
|
|
58
|
+
style: () => {
|
|
59
|
+
const s = spec ?? {};
|
|
60
|
+
return { ...Object.fromEntries(['enabled', 'kind', 'color', 'density', 'far', 'near', 'height', 'falloff'].filter(k => s[k] != null).map(k => [k, s[k]])),
|
|
61
|
+
...(s.glsl ? { 'hook:fog': s.glsl } : {}) };
|
|
62
|
+
},
|
|
63
|
+
apply() { rebuild(); },
|
|
64
|
+
hooks: { fog: { signature: 'vec4 threedogFog(vec3 color, float depth, vec3 worldPos)', scope: ['fogColor', 'cameraPosition', 'fogNear / fogFar (linear)', 'fogDensity (other kinds)', 'THREEDOG_FOG_HEIGHT', 'THREEDOG_FOG_FALLOFF'],
|
|
65
|
+
example: 'vec4 threedogFog(vec3 color, float depth, vec3 worldPos){ return vec4(color, 1.0 - exp(-fogDensity * depth)); }' } },
|
|
66
|
+
applyHook(name, glsl) {
|
|
67
|
+
rebuild();
|
|
68
|
+
},
|
|
69
|
+
// wrong hook GLSL or replace value stops here, before any layer is written
|
|
70
|
+
validate: (k, v) => k === 'hook:fog' ? (typeof v === 'string' && /vec4\s+threedogFog\s*\(/.test(v) ? null : 'needs GLSL that defines `vec4 threedogFog(vec3 color, float depth, vec3 worldPos)` returning (fog rgb, amount 0..1)')
|
|
71
|
+
: k === REPLACE && v !== 'manual' && !v?.isFog && !v?.isFogExp2 ? "is 'manual' or a THREE.Fog / THREE.FogExp2; null gives the fog back to the sky" : null,
|
|
72
|
+
replace: { accepts: "'manual' (the sky stops writing scene.fog) | a THREE.Fog / FogExp2 (becomes scene.fog)", loses: ['weather fog distance (sky.modify fog)', 'the sky-colored horizon fade'] },
|
|
73
|
+
applyReplace(impl) {
|
|
74
|
+
sky._fogHeld = impl != null;
|
|
75
|
+
if (impl?.isFog || impl?.isFogExp2) scene.fog = impl;
|
|
76
|
+
else if (impl == null && sky._drive.fog === true) scene.fog = makeFog(sky._fog, sky._fog.far ?? e.fogFar);
|
|
77
|
+
for (const o of sky._owned ?? []) o.mark(); // the dev guard re-reads the fog it watches
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// look.shadow: the sun's shadow as a look part (set only: the csm patch is internal, and a game that wants its own shadows lights with its own lights).
|
|
2
|
+
// Why a part: the type / cascades / bias a game set were invisible to describe(); now every key says who set it.
|
|
3
|
+
// the work itself is Sky._applyShadow (shadow.js).
|
|
4
|
+
import { defineLookPart } from '../../core/look/part.js';
|
|
5
|
+
import { SHADOW_TYPES } from '../../core/shadowTypes.js';
|
|
6
|
+
|
|
7
|
+
const SPLITS = ['practical', 'uniform', 'logarithmic'];
|
|
8
|
+
const KEYS = ['bias', 'normalBias', 'updateEvery', 'snap', 'ahead', 'type', 'radius', 'blurSamples', 'cascades', 'maxFar', 'fade', 'lightMargin', 'split'];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {any} sky @param {object} sh shadowFor(...) at start: becomes the style layer (style.sky.shadow, tier-adjusted, merged with sky({ shadow }))
|
|
12
|
+
*/
|
|
13
|
+
export function defineShadowLook(sky, sh) {
|
|
14
|
+
const e = sky.engine, sun = sky.sun;
|
|
15
|
+
const cost = 'shadow pass';
|
|
16
|
+
defineLookPart(e, {
|
|
17
|
+
id: 'shadow', group: 'atmosphere', module: 'sky', object: () => sun.shadow, docs: ['recipes/52-look.md', 'recipes/45-cascaded-shadows.md'],
|
|
18
|
+
params: {
|
|
19
|
+
enabled: { type: 'bool', default: e.shadows, cost, desc: 'master shadow switch (engine.setShadows)',
|
|
20
|
+
why: 'the sun casts shadows (createEngine({ shadows }) is the start value)', off: 'look.shadow.set({ enabled: false }), or createEngine({ shadows: false })' },
|
|
21
|
+
type: { type: 'string', default: e.shadowType, values: Object.keys(SHADOW_TYPES), neutral: true, cost, desc: "'basic' hard edge | 'pcf' | 'vsm' softest; switching recompiles materials, do it rarely" },
|
|
22
|
+
radius: { type: 'number', default: 1, min: 0, neutral: true, cost: 'uniform', desc: 'edge softness (pcf, vsm)' },
|
|
23
|
+
blurSamples: { type: 'int', default: 8, min: 1, neutral: true, cost, desc: 'blur quality (vsm only)' },
|
|
24
|
+
bias: { type: 'number', default: -0.0006, neutral: true, cost: 'uniform', desc: 'depth bias against acne' },
|
|
25
|
+
normalBias: { type: 'number', default: 0.04, neutral: true, cost: 'uniform', desc: 'normal offset against acne (meters)' },
|
|
26
|
+
mapSize: { type: 'int', default: 2048, min: 64, neutral: true, cost: 'gpu', desc: 'shadow map pixels (the nearest cascade with cascades)' },
|
|
27
|
+
updateEvery: { type: 'int', default: 1, min: 1, neutral: true, cost, desc: 'update the shadow map every N frames' },
|
|
28
|
+
snap: { type: 'any', default: 0.5, neutral: true, cost: 'uniform', desc: "shadow center snap grid in meters, or 'texel'" },
|
|
29
|
+
ahead: { type: 'number', default: 0, neutral: true, cost: 'uniform', desc: 'meters the shadow center is shifted in front of the view' },
|
|
30
|
+
cascades: { type: 'int', default: 1, neutral: true, cost, desc: '1 = one shadow map; 2-4 = cascaded shadows (recipes/45)',
|
|
31
|
+
check: v => (v < 1 || v > 4 ? `must be a whole number 1 (one shadow map, the default) to 4; got ${v}` : v > 1 && sky._drive.sun === false ? "cannot be above 1: cascades split the engine sun's shadow, and sky({ sun: false }) has no engine sun" : null) },
|
|
32
|
+
maxFar: { type: 'number', default: 120, min: 0.001, neutral: true, cost: 'uniform', desc: 'meters from the camera that cascades cover' },
|
|
33
|
+
fade: { type: 'bool', default: true, neutral: true, cost: 'uniform', desc: 'cascades blend into each other' },
|
|
34
|
+
lightMargin: { type: 'number', default: 100, neutral: true, cost: 'uniform', desc: 'meters the cascade lights sit behind their frustum' },
|
|
35
|
+
split: { type: 'any', default: 'practical', neutral: true, cost: 'uniform', desc: "'practical' | 'uniform' | 'logarithmic' | (count, near, far, out) => void",
|
|
36
|
+
check: v => (typeof v === 'function' || SPLITS.includes(v) ? null : `must be ${SPLITS.map(s => `'${s}'`).join(' | ')} or a function (count, near, far, out) => void; got ${JSON.stringify(v)}`) },
|
|
37
|
+
},
|
|
38
|
+
style: () => ({ ...Object.fromEntries(KEYS.filter(k => sh[k] !== undefined).map(k => [k, sh[k]])), ...(sh.mapSize !== undefined ? { mapSize: sh.mapSize } : {}) }),
|
|
39
|
+
read: () => ({ enabled: e.shadows, type: e.shadowType, radius: sun.shadow.radius, mapSize: sun.shadow.mapSize.x, bias: sun.shadow.bias, normalBias: sun.shadow.normalBias }),
|
|
40
|
+
apply(v, changed) {
|
|
41
|
+
const o = {};
|
|
42
|
+
for (const k of changed) if (KEYS.includes(k)) o[k] = v[k];
|
|
43
|
+
if (changed.has('enabled') && v.enabled !== e.shadows) e.setShadows(v.enabled);
|
|
44
|
+
if (changed.has('mapSize')) sky.setShadowMapSize(v.mapSize);
|
|
45
|
+
if (Object.keys(o).length) sky._applyShadow(o);
|
|
46
|
+
},
|
|
47
|
+
noPatch: "the cascade patch ('csm') is internal; change the shadows with look.shadow.set({ type, radius, cascades, ... })",
|
|
48
|
+
noReplace: 'to own the shadows, light the world with your own three.js lights: sky({ sun: false }) or createEngine({ lights: false })',
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// look.sky: the sky dome as a look part.
|
|
2
|
+
// set({ clouds: { coverage, scale, speed, opacity, softness, color, shade }, backdrop }) live uniforms of the dome; backdrop = one flat color instead of the dome
|
|
3
|
+
// patch('clouds', glsl) the cloud function threedogClouds (clouds.js); null gives the style / built-in kind back
|
|
4
|
+
// patch('layer:<name>', glsl | { glsl, uniforms, order, blend }) add or change a named dome layer (domeLayers.js); null removes it
|
|
5
|
+
// replace(skybox name | Texture | Object3D) the dome gives way to a panorama or your own background object; null gives the dome back
|
|
6
|
+
// Layers used to be an array addressed by index (style.sky.layers); they are named now. A style's array entries are named by their `name` key, else layer0, layer1 ...
|
|
7
|
+
// A hook change rebuilds the dome shader text and recompiles that one material (a hitch, so do it at a scene change, not every frame).
|
|
8
|
+
import * as THREE from 'three';
|
|
9
|
+
import { defineLookPart, REPLACE } from '../../core/look/part.js';
|
|
10
|
+
import { resolveClouds } from './clouds.js';
|
|
11
|
+
import { resolveDomeLayers } from './domeLayers.js';
|
|
12
|
+
import { domeFragment, loadSkybox } from './shader.js';
|
|
13
|
+
import { domeFog } from './fog.js';
|
|
14
|
+
import { resolveBackdrop } from './look.js';
|
|
15
|
+
|
|
16
|
+
const LAYER = 'layer:';
|
|
17
|
+
const CLOUD_KEYS = { 'clouds.coverage': 'uCloudCover', 'clouds.scale': 'uCloudScale', 'clouds.speed': 'uCloudSpeed', 'clouds.opacity': 'uCloudOpacity',
|
|
18
|
+
'clouds.softness': 'uCloudSoft', 'clouds.color': 'uCloudColor', 'clouds.shade': 'uCloudShade' };
|
|
19
|
+
const isColorLike = v => typeof v === 'number' || typeof v === 'string' || !!v?.isColor;
|
|
20
|
+
const glslOf = v => (typeof v === 'string' ? v : v?.glsl);
|
|
21
|
+
|
|
22
|
+
/** @param {any} sky @param {object} st style.sky merged with the sky({ ... }) options */
|
|
23
|
+
export function defineSkyLook(sky, st) {
|
|
24
|
+
const e = sky.engine, scene = e.scene, U = sky.uniforms;
|
|
25
|
+
let part, added = null;
|
|
26
|
+
const layers = new Map((Array.isArray(st.layers) ? st.layers : []).map((l, i) => [l?.name ?? `layer${i}`, l]));
|
|
27
|
+
|
|
28
|
+
// The dome shader from the current clouds function and layers; throws (changing nothing) when a hook is not valid GLSL for its contract
|
|
29
|
+
const rebuild = (cloudsHook, map) => {
|
|
30
|
+
const cl = resolveClouds({ ...(st.clouds ?? {}), glsl: glslOf(cloudsHook), uniforms: { ...(st.clouds?.uniforms), ...(cloudsHook?.uniforms) } });
|
|
31
|
+
const l = resolveDomeLayers([...map.values()].map(v => (typeof v === 'string' ? { glsl: v } : v)));
|
|
32
|
+
const f = 'uFogColor' in U ? domeFog({ color: 'fog' }) : { decl: '', body: '' }; // the fog band exists only when the start fog color was not 'horizon'
|
|
33
|
+
const text = domeFragment(cl, { decl: [f.decl, l.decl].filter(Boolean).join('\n'), body: f.body + l.body });
|
|
34
|
+
return { text, uniforms: { ...cl.uniforms, ...l.uniforms } };
|
|
35
|
+
};
|
|
36
|
+
const apply = r => {
|
|
37
|
+
for (const [k, u] of Object.entries(r.uniforms)) if (!(k in U)) U[k] = u;
|
|
38
|
+
if (sky.dome.material.fragmentShader === r.text) return;
|
|
39
|
+
sky.dome.material.fragmentShader = r.text; sky.dome.material.needsUpdate = true;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const setBackdrop = v => {
|
|
43
|
+
if (v == null) { sky._backdrop = null; sky.dome.visible = !sky.skybox && !added; scene.background = sky.skybox ?? null; return; }
|
|
44
|
+
sky._backdrop = resolveBackdrop({ backdrop: v }); // the sky writes scene.background and hides the dome each frame (frame.js)
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const hooks = { clouds: { signature: 'vec4 threedogClouds(vec3 dir, float time, vec3 sunDir, float night, vec3 lit, vec3 shade, float cover)', scope: ['threedogHash', 'threedogNoise', 'uCloud* uniforms'],
|
|
48
|
+
example: 'vec4 threedogClouds(vec3 d, float t, vec3 s, float night, vec3 lit, vec3 shade, float cover){ return vec4(lit, step(0.5, threedogNoise(d.xz * 4.0)) * cover); }' },
|
|
49
|
+
[LAYER + '<name>']: { signature: 'vec4 threedogSkyLayer(vec3 dir, float time, vec3 sunDir, float night)', scope: ['threedogHash', 'threedogNoise', 'uTop', 'uHorizon', 'uSunColor ...'],
|
|
50
|
+
example: "look.sky.patch('layer:aurora', { glsl: 'vec4 threedogSkyLayer(vec3 d, float t, vec3 s, float n){ return vec4(0.2, 1.0, 0.5, n * smoothstep(0.1, 0.6, d.y) * 0.4); }', blend: 'add' })" } };
|
|
51
|
+
// layer:<name> takes any name: the spec lists one documented entry, the check accepts the prefix
|
|
52
|
+
const hookSpec = new Proxy(hooks, { has: (t, k) => k in t || (typeof k === 'string' && /^layer:[\w-]+$/.test(k)) });
|
|
53
|
+
|
|
54
|
+
const cloudDesc = { coverage: 'cloud amount 0..1+ (also follows the weather)', scale: 'cloud size (smaller = bigger clouds)', speed: 'drift [x, z] per second', opacity: 'cloud opacity',
|
|
55
|
+
softness: 'edge softness', color: 'lit side color', shade: 'shaded side color' };
|
|
56
|
+
const num = d => ({ type: 'number', min: 0, cost: 'uniform', neutral: true, desc: d });
|
|
57
|
+
part = defineLookPart(e, {
|
|
58
|
+
id: 'sky', group: 'atmosphere', module: 'sky', object: () => sky.dome, applyAtStart: false, docs: ['recipes/52-look.md', 'recipes/36-style.md'],
|
|
59
|
+
params: {
|
|
60
|
+
// all neutral: with coverage 0 (no clouds unless the style gives them) nothing of these is drawn
|
|
61
|
+
'clouds.coverage': { ...num(cloudDesc.coverage), neutral: true, default: 0 },
|
|
62
|
+
'clouds.scale': { ...num(cloudDesc.scale), neutral: true, default: 0.35 },
|
|
63
|
+
'clouds.speed': { type: 'array', default: [0.004, 0.002], neutral: true, cost: 'uniform', desc: cloudDesc.speed },
|
|
64
|
+
'clouds.opacity': { ...num(cloudDesc.opacity), neutral: true, default: 0.9 },
|
|
65
|
+
'clouds.softness': { ...num(cloudDesc.softness), neutral: true, default: 0.3 },
|
|
66
|
+
'clouds.color': { type: 'any', default: '#f4f4f4', neutral: true, cost: 'uniform', desc: cloudDesc.color },
|
|
67
|
+
'clouds.shade': { type: 'any', default: '#aaaaaa', neutral: true, cost: 'uniform', desc: cloudDesc.shade },
|
|
68
|
+
backdrop: { type: 'any', default: null, neutral: true, cost: 'uniform', desc: 'a flat color (or (sky) => color) in place of the dome: no gradient, sun, moon, stars or clouds; null = the dome',
|
|
69
|
+
check: v => (isColorLike(v) || typeof v === 'function' ? null : `must be a color (0xefebe4, '#efebe4') or (sky) => color; got ${JSON.stringify(v)}`) },
|
|
70
|
+
},
|
|
71
|
+
style: () => ({
|
|
72
|
+
'clouds.coverage': U.uCloudCover.value, 'clouds.scale': U.uCloudScale.value, 'clouds.speed': U.uCloudSpeed.value.toArray(), 'clouds.opacity': U.uCloudOpacity.value,
|
|
73
|
+
'clouds.softness': U.uCloudSoft.value, 'clouds.color': '#' + U.uCloudColor.value.getHexString(), 'clouds.shade': '#' + U.uCloudShade.value.getHexString(),
|
|
74
|
+
...(st.backdrop != null ? { backdrop: st.backdrop } : {}),
|
|
75
|
+
...(st.clouds?.glsl ? { 'hook:clouds': st.clouds.glsl } : {}),
|
|
76
|
+
...Object.fromEntries([...layers].map(([n, l]) => [`hook:${LAYER}${n}`, l])),
|
|
77
|
+
...(st.skybox ? { [REPLACE]: st.skybox } : {}),
|
|
78
|
+
}),
|
|
79
|
+
apply(v, changed) {
|
|
80
|
+
for (const k of changed) {
|
|
81
|
+
const u = CLOUD_KEYS[k];
|
|
82
|
+
if (!u) continue;
|
|
83
|
+
if (k === 'clouds.speed') U[u].value.set(v[k][0], v[k][1]);
|
|
84
|
+
else if (U[u].value?.isColor) U[u].value.set(v[k]);
|
|
85
|
+
else U[u].value = v[k];
|
|
86
|
+
}
|
|
87
|
+
if (changed.has('backdrop')) setBackdrop(v.backdrop);
|
|
88
|
+
},
|
|
89
|
+
hooks: hookSpec,
|
|
90
|
+
applyHook(name, glsl) {
|
|
91
|
+
if (name === 'clouds') { apply(rebuild(glsl, layers)); return; }
|
|
92
|
+
const n = name.slice(LAYER.length), next = new Map(layers);
|
|
93
|
+
if (glsl == null) next.delete(n); else next.set(n, glsl);
|
|
94
|
+
apply(rebuild(part.value('hook:clouds'), next)); // throws before anything changes when the layer's GLSL is not valid
|
|
95
|
+
layers.clear(); for (const [k, v] of next) layers.set(k, v);
|
|
96
|
+
},
|
|
97
|
+
validate: (k, v) => k === REPLACE && typeof v !== 'string' && !v?.isTexture && !v?.isObject3D ? 'is a skybox asset name, a THREE.Texture or a THREE.Object3D; null gives the dome back' : null,
|
|
98
|
+
replace: { accepts: 'a skybox name (equirectangular panorama asset) | a THREE.Texture | a THREE.Object3D used as the background', loses: ['the gradient dome, sun and moon discs, stars, clouds and dome layers'] },
|
|
99
|
+
applyReplace(impl) {
|
|
100
|
+
if (added) { scene.remove(added); added = null; }
|
|
101
|
+
if (impl == null) { sky.skybox = null; scene.background = sky._backdrop?.color ?? null; sky.dome.visible = !sky._backdrop; return; }
|
|
102
|
+
sky.dome.visible = false;
|
|
103
|
+
if (typeof impl === 'string') loadSkybox(sky, impl);
|
|
104
|
+
else if (impl.isTexture) { impl.mapping = THREE.EquirectangularReflectionMapping; scene.background = impl; sky.skybox = impl; }
|
|
105
|
+
else if (impl.isObject3D) { scene.add(impl); added = impl; scene.background = null; sky.skybox = null; }
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
package/modules/sky/shader.js
CHANGED
|
@@ -47,7 +47,7 @@ export function makeSkyUniforms(st, engineUniforms) {
|
|
|
47
47
|
*/
|
|
48
48
|
export function makeDome(uniforms, st, extra = { decl: '', body: '' }) {
|
|
49
49
|
const dome = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16),
|
|
50
|
-
new THREE.ShaderMaterial({ vertexShader: vert, fragmentShader:
|
|
50
|
+
new THREE.ShaderMaterial({ vertexShader: vert, fragmentShader: domeFragment(resolveClouds(st.clouds), extra), uniforms, side: THREE.BackSide, depthWrite: false, depthTest: false }));
|
|
51
51
|
dome.frustumCulled = false; dome.renderOrder = -1000; dome.userData.budgetTag = 'sky';
|
|
52
52
|
dome.onBeforeRender = (r, sc, cam) => {
|
|
53
53
|
dome.position.copy(cam.position); dome.scale.setScalar(/** @type {THREE.PerspectiveCamera} */ (cam).far * 0.9); dome.updateMatrixWorld();
|
|
@@ -65,7 +65,7 @@ export function loadSkybox(sky, name) {
|
|
|
65
65
|
|
|
66
66
|
const vert = `varying vec3 vDir;
|
|
67
67
|
void main(){ vDir = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position = p.xyww; }`;
|
|
68
|
-
const
|
|
68
|
+
export const domeFragment = (cl, x) => `uniform vec3 uTop; uniform vec3 uHorizon; uniform vec3 uSunDir; uniform vec3 uSunColor; uniform float uNight;
|
|
69
69
|
uniform float uSunSize; uniform float uSunGlow; uniform float uSunPower; uniform float uMoonPower; uniform float uMoonSize; uniform vec3 uMoonColor; uniform float uStars; uniform float uStarScale; uniform float uCurve;
|
|
70
70
|
uniform float uTime; uniform float uCloud; uniform float uCloudCover; uniform float uCloudScale; uniform vec2 uCloudSpeed; uniform vec3 uCloudColor; uniform vec3 uCloudShade;
|
|
71
71
|
${CLOUD_UNIFORM_DECL}
|
package/modules/sky/shadow.js
CHANGED
|
@@ -15,21 +15,15 @@ export function shadowFor(tier, styleShadow = {}, optionShadow = undefined) {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
export const shadowMethods = {
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
* snap snap = shadow center snap grid (meters, or 'texel' to snap to shadow pixels); ahead = meters to shift the shadow center in front of the view;
|
|
21
|
-
* type = 'basic' (hard edge) | 'pcf' | 'vsm' (soft, costlier; switching rebuilds the shadow map and recompiles materials, so do it rarely);
|
|
22
|
-
* radius = edge softness (pcf, vsm; no effect on basic); blurSamples = blur quality (vsm only);
|
|
23
|
-
* cascades / maxFar / fade / lightMargin / split = cascaded shadows (cascades.js)
|
|
24
|
-
*/
|
|
25
|
-
setShadow(o = {}) {
|
|
18
|
+
/** Apply shadow fields (engine.look.shadow.set(o): bias / normalBias, updateEvery, snap, ahead, type, radius, blurSamples, cascades / maxFar / fade / lightMargin / split; lookShadow.js calls this) to the sun and the cascades (look.shadow's apply; the part checked the values when it took them) */
|
|
19
|
+
_applyShadow(o) {
|
|
26
20
|
const s = this.shadow;
|
|
27
|
-
if (o.type !== undefined) shadowTypeOf(o.type, '
|
|
21
|
+
if (o.type !== undefined) shadowTypeOf(o.type, 'look.shadow.set({ type })');
|
|
28
22
|
checkCascades(this, o);
|
|
29
23
|
for (const k of Object.keys(s)) if (o[k] !== undefined) s[k] = o[k];
|
|
30
24
|
const sm = this.engine.renderer.shadowMap, sun = this.sun.shadow;
|
|
31
25
|
// validate before applying so a typo leaves the previous type in place
|
|
32
|
-
if (o.type !== undefined) { sm.type = shadowTypeOf(o.type, '
|
|
26
|
+
if (o.type !== undefined) { sm.type = shadowTypeOf(o.type, 'look.shadow.set({ type })'); this.engine.shadowType = o.type; }
|
|
33
27
|
else s.type = this.engine.shadowType;
|
|
34
28
|
sun.bias = s.bias; sun.normalBias = s.normalBias; sun.radius = s.radius; sun.blurSamples = s.blurSamples;
|
|
35
29
|
sm.autoUpdate = s.updateEvery <= 1;
|
package/modules/sky/skyModule.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { Sky } from './Sky.js';
|
|
4
4
|
import { dropCascades } from './cascades.js';
|
|
5
5
|
import { timeCondition } from './calendar.js';
|
|
6
|
-
import {
|
|
6
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
7
7
|
import { parseClock } from '../../core/dayTime.js';
|
|
8
8
|
/** @import { ModuleDef } from '../../types/core' */
|
|
9
9
|
/** @import { SkyOptions } from '../../types/world' */
|
|
@@ -12,6 +12,7 @@ import { parseClock } from '../../core/dayTime.js';
|
|
|
12
12
|
const SKY_OPTIONS = ['time', 'dayLength', 'day', 'daysPerSeason', 'seasons', 'keyframes', 'groundTint', 'sunSize', 'sunGlow', 'sunBrightness', 'moonBrightness',
|
|
13
13
|
'moonSize', 'moonColor', 'clouds', 'starDensity', 'starScale', 'gradientCurve', 'skybox', 'shadow', 'orbitTilt', 'orbitSway', 'hoursPerDay', 'environment',
|
|
14
14
|
'sun', 'hemisphere', 'fog', 'layers', 'backdrop'];
|
|
15
|
+
const SKY_PARAMS = keysSchema(SKY_OPTIONS); // keys only: the values take several shapes (time: 'HH:MM' | 0-1), Sky checks them
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* Sky, day/night, calendar -> engine.sky
|
|
@@ -19,11 +20,11 @@ const SKY_OPTIONS = ['time', 'dayLength', 'day', 'daysPerSeason', 'seasons', 'ke
|
|
|
19
20
|
* @returns {ModuleDef<Sky>}
|
|
20
21
|
*/
|
|
21
22
|
export function sky(opts = {}) {
|
|
23
|
+
readParams('sky', SKY_PARAMS, opts);
|
|
22
24
|
let s = null;
|
|
23
25
|
return {
|
|
24
|
-
name: 'sky', label: 'Sky', stage: 'environment',
|
|
26
|
+
name: 'sky', label: 'Sky', params: SKY_PARAMS, options: opts, stage: 'environment',
|
|
25
27
|
install(e) {
|
|
26
|
-
checkOptions('sky()', opts, SKY_OPTIONS);
|
|
27
28
|
s = new Sky(e, opts);
|
|
28
29
|
// audio rule condition { time: 'day' | 'night' | ['18:00', '06:00'] } for music / ambience rule lists
|
|
29
30
|
e.audio.condition('time', timeCondition(s));
|
|
@@ -12,11 +12,11 @@ import { TerrainEdits } from './terrainEdit.js';
|
|
|
12
12
|
import { terrainMaterial } from '../../render/materials.js';
|
|
13
13
|
import { chunkRing } from '../../core/streamSources.js';
|
|
14
14
|
import { chunkQueries } from './chunkQueries.js';
|
|
15
|
+
import { chunkLevels, NO_VEG } from './chunkLevels.js';
|
|
15
16
|
import { mountTerrain } from './mountTerrain.js';
|
|
16
17
|
import { disposeColorMap } from './terrainTexture.js';
|
|
17
18
|
|
|
18
19
|
const COLLIDER_LAG = 30; // base delay before chunk collision takes effect (fixed steps, 30 = 0.5 s), multiplied by (1 + ring)
|
|
19
|
-
const NO_VEG = { baseNames: () => [], nearNames: () => [], list: () => [], get: () => null };
|
|
20
20
|
|
|
21
21
|
export class ChunkManager {
|
|
22
22
|
constructor(engine, terrainCfg, material = null) {
|
|
@@ -225,20 +225,6 @@ export class ChunkManager {
|
|
|
225
225
|
}
|
|
226
226
|
|
|
227
227
|
/** Due but chunk not ready: if the worker result already arrived, upload it now, else generate on the main thread (same code as the worker, same result) */
|
|
228
|
-
_forceReady(c) {
|
|
229
|
-
if (c.state === 'ready') return true;
|
|
230
|
-
const i = this.ready.findIndex(r => r.terrain && r.cx === c.cx && r.cz === c.cz && r.gen === c.gen && r.ev === this.edits.version(c.key));
|
|
231
|
-
let r = i >= 0 ? this.ready.splice(i, 1)[0] : null;
|
|
232
|
-
if (!r) {
|
|
233
|
-
const veg = this.engine.vegetation || NO_VEG;
|
|
234
|
-
r = { terrain: this.T.buildChunk(c.cx, c.cz), veg: {} };
|
|
235
|
-
for (const name of veg.baseNames()) r.veg[name] = this.T.place(c.cx, c.cz, veg.get(name).rule, this.density);
|
|
236
|
-
}
|
|
237
|
-
this._applyTerrain(c, r.terrain);
|
|
238
|
-
for (const name in r.veg) this._applyVeg(c, name, r.veg[name]);
|
|
239
|
-
c.level = -1;
|
|
240
|
-
return true;
|
|
241
|
-
}
|
|
242
228
|
|
|
243
229
|
_job(c, terrain, species) {
|
|
244
230
|
const ev = this.edits.version(c.key), edits = this.edits.forChunk(c.cx, c.cz);
|
|
@@ -257,23 +243,6 @@ export class ChunkManager {
|
|
|
257
243
|
// the InstancedMesh of one species in a chunk is built by vegetation (the same code builds its chunks on any other ground)
|
|
258
244
|
_applyVeg(c, name, r) { this.engine.vegetation.mount(c, name, r); }
|
|
259
245
|
|
|
260
|
-
_setLevel(c, ring) {
|
|
261
|
-
if (c.level === ring) return;
|
|
262
|
-
c.level = ring;
|
|
263
|
-
const veg = this.engine.vegetation || NO_VEG;
|
|
264
|
-
for (const sp of veg.list()) {
|
|
265
|
-
const im = c.veg[sp.name];
|
|
266
|
-
if (sp.nearOnly) {
|
|
267
|
-
// detailDone: this species was already placed here and came back empty; without it the empty result would reset the level and re-ask forever
|
|
268
|
-
if (ring <= sp.maxRing && !im && !c.pendingDetail && !c.detailDone.has(sp.name)) {
|
|
269
|
-
c.pendingDetail = true;
|
|
270
|
-
this._send(this._job(c, false, veg.nearNames()));
|
|
271
|
-
} else if (ring > sp.maxRing + 1 && im) { veg.unmount(c, sp.name); c.detailDone.delete(sp.name); }
|
|
272
|
-
continue;
|
|
273
|
-
}
|
|
274
|
-
if (im) veg.levelOf(im, sp, ring);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
246
|
|
|
278
247
|
/** Stop the chunk workers (called by terrain dispose; in-flight results are discarded) */
|
|
279
248
|
dispose() { this.lane.dispose(); this.ready.length = 0; }
|
|
@@ -288,4 +257,4 @@ export class ChunkManager {
|
|
|
288
257
|
for (const n in c.veg) c.veg[n].dispose();
|
|
289
258
|
}
|
|
290
259
|
}
|
|
291
|
-
Object.assign(ChunkManager.prototype, chunkQueries);
|
|
260
|
+
Object.assign(ChunkManager.prototype, chunkQueries, chunkLevels);
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Chunk loading detail: forcing one chunk ready now and choosing per-species detail level by ring (mixed into ChunkManager.prototype).
|
|
2
|
+
// Split out of ChunkManager.js; the methods use the manager state (chunks, ready, edits, T, density) through this.
|
|
3
|
+
|
|
4
|
+
/** Stand-in for engine.vegetation when the vegetation module is not installed */
|
|
5
|
+
export const NO_VEG = { baseNames: () => [], nearNames: () => [], list: () => [], get: () => null };
|
|
6
|
+
|
|
7
|
+
export const chunkLevels = {
|
|
8
|
+
_forceReady(c) {
|
|
9
|
+
if (c.state === 'ready') return true;
|
|
10
|
+
const i = this.ready.findIndex(r => r.terrain && r.cx === c.cx && r.cz === c.cz && r.gen === c.gen && r.ev === this.edits.version(c.key));
|
|
11
|
+
let r = i >= 0 ? this.ready.splice(i, 1)[0] : null;
|
|
12
|
+
if (!r) {
|
|
13
|
+
const veg = this.engine.vegetation || NO_VEG;
|
|
14
|
+
r = { terrain: this.T.buildChunk(c.cx, c.cz), veg: {} };
|
|
15
|
+
for (const name of veg.baseNames()) r.veg[name] = this.T.place(c.cx, c.cz, veg.get(name).rule, this.density);
|
|
16
|
+
}
|
|
17
|
+
this._applyTerrain(c, r.terrain);
|
|
18
|
+
for (const name in r.veg) this._applyVeg(c, name, r.veg[name]);
|
|
19
|
+
c.level = -1;
|
|
20
|
+
return true;
|
|
21
|
+
},
|
|
22
|
+
|
|
23
|
+
_setLevel(c, ring) {
|
|
24
|
+
if (c.level === ring) return;
|
|
25
|
+
c.level = ring;
|
|
26
|
+
const veg = this.engine.vegetation || NO_VEG;
|
|
27
|
+
for (const sp of veg.list()) {
|
|
28
|
+
const im = c.veg[sp.name];
|
|
29
|
+
if (sp.nearOnly) {
|
|
30
|
+
// detailDone: this species was already placed here and came back empty; without it the empty result would reset the level and re-ask forever
|
|
31
|
+
if (ring <= sp.maxRing && !im && !c.pendingDetail && !c.detailDone.has(sp.name)) {
|
|
32
|
+
c.pendingDetail = true;
|
|
33
|
+
this._send(this._job(c, false, veg.nearNames()));
|
|
34
|
+
} else if (ring > sp.maxRing + 1 && im) { veg.unmount(c, sp.name); c.detailDone.delete(sp.name); }
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (im) veg.levelOf(im, sp, ring);
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
};
|
package/modules/terrain/index.js
CHANGED
|
@@ -29,22 +29,26 @@ async function loadGray(url) {
|
|
|
29
29
|
import { ChunkManager } from './ChunkManager.js';
|
|
30
30
|
import { DEFAULT_TERRAIN } from './terrainGen.js';
|
|
31
31
|
import { checkOptions } from '../../core/validate.js';
|
|
32
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
32
33
|
import { compilePure } from '../../core/threadPure.js';
|
|
33
34
|
import { warnOnce } from '../../core/validate.js';
|
|
34
35
|
import { prepareShape, voidWatcher } from './terrainShapeMain.js';
|
|
36
|
+
import { defineGroundLook } from './lookGround.js';
|
|
35
37
|
|
|
36
38
|
const NO_HEIGHT = 'terrain(): no height function or height map was given, so the ground is flat gray at y = 0 (a placeholder, not a look). '
|
|
37
39
|
+ 'Pass terrain({ height, groundType }) or a preset, e.g. terrain({ ...terrainPreset() }) with terrainPreset from @threedog/terrain-noise';
|
|
38
40
|
|
|
39
41
|
export { createTerrain, DEFAULT_TERRAIN } from './terrainGen.js';
|
|
40
42
|
|
|
43
|
+
const TERRAIN_PARAMS = keysSchema(['viewChunks', 'density', 'material', 'viewFog', ...Object.keys(DEFAULT_TERRAIN)], { ...DEFAULT_TERRAIN, viewChunks: 4, density: 1, viewFog: false }); // defaults shown in the catalog; createTerrain applies the real ones
|
|
44
|
+
|
|
41
45
|
export function terrain(opts = {}) {
|
|
46
|
+
readParams('terrain', TERRAIN_PARAMS, opts);
|
|
42
47
|
const { viewChunks = 4, density = 1, material, viewFog = false, ...cfg } = opts;
|
|
43
48
|
let w = null, watchVoid = null;
|
|
44
49
|
return {
|
|
45
|
-
name: 'terrain', label: 'Terrain', optional: ['vegetation'], stage: 'world',
|
|
50
|
+
name: 'terrain', label: 'Terrain', params: TERRAIN_PARAMS, options: opts, noSkip: 'void-fall watch only; nothing accumulates over time', optional: ['vegetation'], stage: 'world',
|
|
46
51
|
install(e) {
|
|
47
|
-
checkOptions('terrain()', opts, ['viewChunks', 'density', 'material', 'viewFog', ...Object.keys(DEFAULT_TERRAIN)]);
|
|
48
52
|
const style = e.style.terrain || {};
|
|
49
53
|
for (const k in cfg) if (cfg[k] === undefined) delete cfg[k];
|
|
50
54
|
// a game's generator functions go to the workers as source text: checked here (outside variables name themselves) so the error points at this call
|
|
@@ -69,6 +73,9 @@ export function terrain(opts = {}) {
|
|
|
69
73
|
w.density = density;
|
|
70
74
|
w.viewFog = viewFog; // opt-in: the fog ends where the chunks end (hides the edge); otherwise createEngine({ fogFar }) / the game's fog stays
|
|
71
75
|
this._cfg = terrainCfg;
|
|
76
|
+
// look.ground: what terrain({...}) itself was given goes on the game layer (owner 'terrain()'); the style's values are the style layer
|
|
77
|
+
defineGroundLook(e, w, { cfg: () => this._cfg, setCfg: c => { this._cfg = c; },
|
|
78
|
+
game: { colors: cfg.colors && terrainCfg.colors, biomeColors: cfg.biomeColors && terrainCfg.biomeColors, steep: cfg.steep, shading: cfg.shading, material } });
|
|
72
79
|
e.setGround({
|
|
73
80
|
height: (x, z) => w.T.surface(x, z),
|
|
74
81
|
slope: (x, z) => w.T.slope(x, z),
|
|
@@ -99,6 +106,7 @@ export function terrain(opts = {}) {
|
|
|
99
106
|
const needH = hm?.url && !hm.data, needM = mk?.url && !mk.data;
|
|
100
107
|
if (!needH && !needM) return;
|
|
101
108
|
const cfg2 = { ...this._cfg };
|
|
109
|
+
this._cfg = cfg2; // look.ground rebuilds from the current config
|
|
102
110
|
if (needH) cfg2.heightmap = { ...hm, ...await loadGray(hm.url), url: undefined };
|
|
103
111
|
if (needM) cfg2.shape = { ...cfg2.shape, mask: { ...mk, ...await loadGray(mk.url), url: undefined } };
|
|
104
112
|
const species = {}; for (const sp of e.vegetation?.list() || []) species[sp.name] = sp.rule;
|