Skip to content

Official Codebase of 3DCodeVerse

Python

scene lib: the aerial-perspective ramp ends where the scene's fog closes, and god-ray pools and dust fade as added light

gaoypeng4a04af881c71
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js
index 21c918ff..761684c4 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/atmosphere.js
@@ -12,6 +12,7 @@ import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
import { makeShaderMaterial, patchStandard, tickShaders, keepOutOfDepthPasses } from './shader.js';
+import { MOODS } from './environment.js';
// Sheets are packed toward the ground (h ~ f^PACK): an evenly spaced
// stack spends most of its geometry in the thin top half where there
@@ -31,10 +32,10 @@ const BASE_H = 0.03;
// the dial means one physical thing at any `extent`, `height` or
// LAYERS. Written into the GLSL below as 1/REF_M.
const REF_M = 10;
-// environment.js MOODS.day.horizon — the fallback for a bank built with
-// no scene to read. Not a light colour anyone should be relying on:
-// pass `scene` (or `color`) and the bank takes the scene's own.
-const DAY_HORIZON = 0xdbe3ea;
+// The day mood's horizon — the fallback for a bank built with no scene
+// to read. Not a light colour anyone should be relying on: pass `scene`
+// (or `color`) and the bank takes the scene's own.
+const DAY_HORIZON = MOODS.day.horizon;
// Henyey-Greenstein asymmetry. Water droplets scatter hard forward, so
// a bank you look THROUGH toward the sun is a light source and the same
// bank with the sun behind you is a grey wall. HG_NORM normalises the
@@ -172,16 +173,19 @@ function inScatterFloor(color, ref, floor) {
* @param {THREE.Scene} [scene]
* @returns {{air: THREE.Color|null, fog: THREE.Color|null,
* dir: THREE.Vector3|null, sun: THREE.Color|null, key: number,
- * amb: THREE.Color|null, ambLum: number, fogDensity: number}}
+ * amb: THREE.Color|null, ambLum: number, fogFar: number}} — `fogFar` is
+ * where the scene's fog is (nearly) opaque: a linear Fog's `far`, one
+ * e-fold of a FogExp2, 0 without fog.
*/
function readScene(scene) {
const out = { air: null, fog: null, dir: null, sun: null, key: 0,
- amb: null, ambLum: 0, fogDensity: 0 };
+ amb: null, ambLum: 0, fogFar: 0 };
if (!scene || typeof scene.traverse !== 'function') return out;
out.air = horizonRadiance(scene);
if (scene.fog && scene.fog.color) {
out.fog = scene.fog.color.clone();
- out.fogDensity = scene.fog.density || 0;
+ out.fogFar = scene.fog.isFog ? scene.fog.far
+ : scene.fog.density > 0 ? 1 / scene.fog.density : 0;
}
let best = null;
let fill = null;
@@ -550,12 +554,13 @@ const AERIAL_HEAD = [
* @param {THREE.Material} material Any built-in material (the patch
* needs three's `<color_fragment>`); patched in place.
* @param {object} [opts] `scene` THREE.Scene to read — the shift then
- * targets the scene's OWN fog colour and finishes at one e-fold of
- * its density, so the two cues cannot disagree about where far is;
+ * targets the scene's OWN fog colour and finishes where that fog
+ * closes, so the two cues cannot disagree about where far is;
* `skyColor` THREE.Color override (default the day mood horizon,
* matching `worldShell`); `start`/`end` metres over which the shift
- * ramps in (default 40/600 — `end` is one e-fold of the day fog
- * density, so the shift completes as fog takes over); `strength`
+ * ramps in (default 40 and where the scene's fog closes — a linear
+ * Fog's far, a FogExp2's e-fold, else the day mood's ~556 m — so the
+ * shift completes as fog takes over); `strength`
* maximum shift (default 0.8; 1.0 is pure sky); `lift` how much of
* the sky's own brightness the far field takes on — airlight
* (default 0.35; 0 is the pure hue shift, 1 flattens the far field
@@ -576,10 +581,10 @@ export function patchAerialPerspective(material, opts = {}) {
env.air || env.amb,
env.air ? 0.5 * lumOf(env.air) : 0.2 * env.ambLum);
const start = opts.start ?? 40;
- // One e-fold of the scene's own fog, exactly as the 600 m default is
- // one e-fold of the day mood's 0.0018.
- const efold = env.fogDensity > 0 ? 1 / env.fogDensity : 600;
- const end = Math.max(start + 1, opts.end ?? efold);
+ // Where the scene's own fog closes (a linear Fog's far, a FogExp2's
+ // e-fold); with no fog, the day mood's e-fold.
+ const far = env.fogFar > 0 ? env.fogFar : 1 / MOODS.day.fogDensity;
+ const end = Math.max(start + 1, opts.end ?? far);
// Pre-divided by its own luminance, so `uAerialSky * L` lands back on
// the fragment's brightness and the shader stays two instructions.
const lum = lumOf(sky);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
index 710551fe..79c2a6bf 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/environment.js
@@ -13,7 +13,7 @@ import { patchStandard, sunVector } from './shader.js';
import { skyRadiance } from './sky.js';
import { snapshotResources, attachDisposal } from './lifecycle.js';
-const MOODS = {
+export const MOODS = {
day: { zenith: 0x5d8fd6, horizon: 0xdbe3ea, ridge: 0x9fb2c4,
fogDensity: 0.0018 },
golden: { zenith: 0x3f5a9e, horizon: 0xf2c17e, ridge: 0x8c7a90,
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js
index 8a03fd6b..9a81045b 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js
@@ -37,19 +37,6 @@ import {
const _UP = new THREE.Vector3(0, 1, 0);
-// Additive light must FADE with distance. three's fog chunk mixes
-// toward the fog colour, which on an additive pass ADDS haze instead of
-// removing contrast, so the alpha carries the recession itself.
-const _FOG_FADE = [
- '#ifdef USE_FOG',
- ' #ifdef FOG_EXP2',
- ' a *= exp(-fogDensity * fogDensity * vFogDepth * vFogDepth);',
- ' #else',
- ' a *= 1.0 - smoothstep(fogNear, fogFar, vFogDepth);',
- ' #endif',
- '#endif',
-].join('\n');
-
/**
* Build a field of light shafts, their floor pools and their dust.
*
@@ -402,7 +389,6 @@ function shaftMaterial(dir, color, air, soft, gain, hazy) {
// through what they let through.
' float amp = 0.55 + 0.8 * astraHash11(vShaft * 13.0 + 0.5);',
' float a = uGain * amp * chord * striae * fade * ends;',
- _FOG_FADE,
// Rolled off instead of clamped: a beam that saturates
// draws a flat white band with a hard rim, which is the
// cylinder again.
@@ -425,6 +411,9 @@ function shaftMaterial(dir, color, air, soft, gain, hazy) {
' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
].join('\n'),
transparent: true,
+ // Added light fades into distance through its alpha (shader.js
+ // `additive`); a hazy veil is a surface and takes the fog colour.
+ additive: !hazy,
blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,
side: THREE.DoubleSide,
depthWrite: false,
@@ -484,16 +473,13 @@ function poolMesh(shafts, dir, run, side, color, air, spark) {
// on. One power alone is a soft blob with no centre.
' float a = (pow(1.0 - d, 2.9) * 0.44',
' + pow(1.0 - d, 7.0) * 0.26) * shim * uAmp;',
- _FOG_FADE,
// A pool has a hot heart and a scattered margin: holding one
// tint out to the rim is what makes it read as a decal.
' vec3 c = mix(uColor, uAir, smoothstep(0.15, 1.0, d) * 0.7);',
' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.005;',
' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
].join('\n'),
- transparent: true,
- blending: THREE.AdditiveBlending,
- depthWrite: false,
+ additive: true,
});
const mesh = new THREE.Mesh(geom, mat);
mesh.name = 'Pools';
@@ -610,17 +596,13 @@ function moteMaterial(dir, side, perp, color, air, spark, width) {
'#include <fog_vertex>',
'}',
].join('\n'),
- fragmentShader: [
- '#include <common>',
- '#include <logdepthbuf_pars_fragment>',
- '#include <fog_pars_fragment>',
- 'uniform vec3 uColor; uniform vec3 uAir; uniform float uAmp;',
- 'varying vec2 vUv;',
- 'varying float vLife;',
- 'varying float vTwinkle;',
- 'varying float vMist;',
- 'void main() {',
- '#include <logdepthbuf_fragment>',
+ // The fragment is built by makeShaderMaterial so `additive` can
+ // fade the dust into distance through its alpha.
+ util: false,
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir; uniform float uAmp;'
+ + ' varying vec2 vUv; varying float vLife; varying float vTwinkle;'
+ + ' varying float vMist;',
+ fragmentMain: [
' float d = length(vUv - 0.5) * 2.0;',
' if (d > 1.0) discard;',
// Lives and dies inside the beam so nothing pops at the
@@ -631,15 +613,10 @@ function moteMaterial(dir, side, perp, color, air, spark, width) {
// a ball of cotton.
' float a = (pow(1.0 - d, 3.4) + 0.14 * pow(1.0 - d, 1.3))',
' * life * vTwinkle * exp(-vLife * 1.2) * 1.05 * uAmp;',
- _FOG_FADE,
' if (a < 0.003) discard;',
' gl_FragColor = vec4(mix(uColor, uAir, vMist),',
' clamp(a, 0.0, 1.0));',
- '#include <fog_fragment>',
- '}',
].join('\n'),
- transparent: true,
- blending: THREE.AdditiveBlending,
- depthWrite: false,
+ additive: true,
});
}
diff --git a/harness/tests/scene_runtime/lib/test_atmosphere.py b/harness/tests/scene_runtime/lib/test_atmosphere.py
index 9a974fbf..0689025b 100644
--- a/harness/tests/scene_runtime/lib/test_atmosphere.py
+++ b/harness/tests/scene_runtime/lib/test_atmosphere.py
@@ -34,3 +34,21 @@ console.log(JSON.stringify({
assert out["day"] > 0.5 and 0.02 < out["night"] < 0.08, out
assert out["night"] > out["fog"] * 4 and out["nightRB"] < 0.75, out # lit, and blue
assert out["forced"][0] > 0.9 and out["forced"][2] < 0.05, out
+
+
[email protected]("fog, end", [
+ ("new THREE.FogExp2(0xdbe3ea, 0.0018)", 1 / 0.0018),
+ # the linear Fog contract.md and the cookbook teach: the ramp once ran on to 600 m,
+ # four times past the fog wall, where no hue shift can be seen
+ ("new THREE.Fog(0x9fc4e8, 40, 140)", 140),
+ ("null", 1 / 0.0018), # no fog: the day mood's e-fold
+])
+def test_the_aerial_ramp_ends_where_the_scene_fog_closes(fog, end):
+ out = measure(f"""
+import * as THREE from 'three';
+import {{ patchAerialPerspective }} from './lib/atmosphere.js';
+const scene = new THREE.Scene(); scene.fog = {fog};
+const m = patchAerialPerspective(new THREE.MeshStandardMaterial(), {{ scene }});
+console.log(JSON.stringify({{ end: m.userData.uniforms.uAerialEnd.value }}));
+""", ("atmosphere.js", "environment.js", "sky.js"))
+ assert out["end"] == pytest.approx(end)
diff --git a/harness/tests/scene_runtime/lib/test_godrays.py b/harness/tests/scene_runtime/lib/test_godrays.py
index 6468182b..87eef59c 100644
--- a/harness/tests/scene_runtime/lib/test_godrays.py
+++ b/harness/tests/scene_runtime/lib/test_godrays.py
@@ -124,3 +124,21 @@ console.log(JSON.stringify({
assert out["steepNames"] == ["Motes", "Pools", "Shafts"], out
+
+
+def test_added_light_fades_with_distance_and_never_takes_the_fog_colour():
+ """The pools and dust were additive but built without `additive: true`, so each
+ faded its alpha AND ran three's fog chunk, which ADDS fog-coloured haze to an
+ added light. Every additive material ends in the alpha fade only."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeGodRays } from './lib/godrays.js';
+const g = makeGodRays({ count: 3, height: 6, seed: 2 });
+const mats = [];
+g.traverse((o) => { if (o.material && o.material.blending === THREE.AdditiveBlending) mats.push({
+ name: o.material.name, mix: o.material.fragmentShader.includes('#include <fog_fragment>'),
+ fade: o.material.fragmentShader.includes('gl_FragColor.a *= 1.0 - clamp(astraFogF') }); });
+console.log(JSON.stringify(mats));
+""", _LIBS)
+ assert {m["name"] for m in out} >= {"GodRayPool", "GodRayMotes"}, out
+ assert all(m["fade"] and not m["mix"] for m in out), out