From b00905f893fab146c06ee67e8500fa64a3e7ff66 Mon Sep 17 00:00:00 2001 From: NeoLorenzo Date: Sun, 8 Nov 2026 05:57:40 +0000 Subject: [PATCH] =?UTF-8?q?Observer:=20sun=20path=20by=20day=20of=20year?= =?UTF-8?q?=20at=2052=C2=B0=20N=20and=20seasonal=20foliage=20[LIFE17-Sky-0?= =?UTF-8?q?77]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 6 + LAB_NOTES.md | 10 ++ src/valleyView/display.ts | 18 --- src/valleyView/seasonLook.test.ts | 63 +++++++++ src/valleyView/seasonLook.ts | 208 ++++++++++++++++++++++++++++++ src/valleyView/tiledInstances.ts | 13 +- src/valleyView/valleyScene.ts | 96 +++++++++++--- src/valleyView/valleyViewModel.ts | 2 +- 8 files changed, 377 insertions(+), 39 deletions(-) create mode 100644 src/valleyView/seasonLook.test.ts create mode 100644 src/valleyView/seasonLook.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 881b952..8f5d777 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to Econ-Engine are documented here. The changelog records what changed in each update. Design rationale, experiments, observations, and lessons are documented separately in [Lab Notes](LAB_NOTES.md). +## [LIFE17-Sky-077] - (2026-11-08) + +- The observer draws the year. The sun follows the solar declination for the day of the year at 52° N: about 61° high and 16½ hours of daylight at the summer solstice, 38° and 12 hours at the equinoxes, 15° and 7½ hours at the winter solstice. The run starts at the spring equinox. The day sky is paler in winter and warmer while the sun is low. +- Leaves follow the season: bilberry, hazel and birch blend from spring green through autumn yellow and brown to bare winter crowns; about half the trees are drawn as birches and half as evergreen pines, by a hash of the tree's number. The grass dulls in late autumn and winter. Colours change through shared shader uniforms, recoloured at most every tenth of a day. +- Observer only: the simulation's day still runs from `dawnHour` to `duskHour` all year, and trajectories and fingerprints are unchanged. New `seasonLook.ts` with unit tests; the fixed-day `daylightAt` and `sunAt` in `display.ts` are removed. + ## [LIFE16-Routes-075] - (2026-10-30) - Fixes a memory leak on long runs: the state kept every route ever walked, about 45,000 route segments a day, so the heap grew about 12 MB a day and a year's run ran out of memory, in Node and in the page's worker alike. Each step now frees the routes below the lowest one still being walked; route ids keep counting. diff --git a/LAB_NOTES.md b/LAB_NOTES.md index a672457..28f2395 100644 --- a/LAB_NOTES.md +++ b/LAB_NOTES.md @@ -6,6 +6,16 @@ Every meaningful model, architecture, experimental, or design update should receive a newest-first entry. Use at most one base update number per Git commit. Refinements completed before that commit keep the same base number with a decimal suffix—for example, `003` and `003.1` belong to the same commit family. Allocate the next base number only for a later commit. Preserve the context, observed problem or research question, rationale, important implementation decisions, trade-offs, findings, and unresolved questions. Distinguish verified observations from hypotheses. If the original rationale is unknown, say so rather than inferring intent from the finished code. +## [LIFE17-Sky-077] - (2026-11-08) + +The owner asked to see the seasons in the valley: the sun's path and day length changing through the year, and trees turning brown in autumn and losing their leaves in winter, without temperature or snow. This is drawn by the observer alone, from the displayed minute, so no trajectory changes. + +**Sun.** The valley is placed at 52° N, the latitude of the North Sea plain and Star Carr in the Mesolithic. The declination is `23.44° · sin(2π · yearFraction)`, with the year fraction 0 at the spring equinox, and the sun's height `sin φ sin δ + cos φ cos δ cos H`. The hour angle is zero at the middle of the simulation's day and ±π at its dawn and dusk hours, so at the equinoxes the drawn sun rises and sets on them. Light eases in while the sun is within about 4° of the horizon. + +**Leaves and grass.** Each deciduous plant has key colours and crown sizes through the year, blended smoothly so nothing steps on a season boundary. The engine has no tree species: birch or pine is the observer's choice per tree, from a hash that draws on no simulation stream. + +**Left for later.** People still work from `dawnHour` to `duskHour` all year, so in midsummer they sleep in daylight and in midwinter they work after the drawn sunset. Making them follow the sun changes trajectories and needs its own step. + ## [LIFE16-Routes-075] - (2026-10-30) While measuring Life 17, a one-year run ran out of memory, and `main` grew at the same rate: running the canonical configuration day by day with `advanceValley` and collecting garbage every 25 days, the heap grew about 12 MB a day, to 2.4 GB by day 150. Node's default heap and the page's worker both fail before a year. diff --git a/src/valleyView/display.ts b/src/valleyView/display.ts index f778479..71ba71b 100644 --- a/src/valleyView/display.ts +++ b/src/valleyView/display.ts @@ -26,24 +26,6 @@ export function clockLabel(hours: number) { return `Day ${day + 1} · ${hh}:${mm}` } -/** - * 0 at night, 1 in full daylight, easing over the half hour either side of dawn and dusk. Only the picture fades; the - * simulation's night still starts exactly at dusk. - */ -export function daylightAt(hourOfDay: number, dawnHour: number, duskHour: number) { - const smooth = (edge: number, t: number) => { - const x = Math.min(1, Math.max(0, (t - (edge - 0.5)) / 1)) - return x * x * (3 - 2 * x) - } - return Math.min(smooth(dawnHour, hourOfDay), 1 - smooth(duskHour, hourOfDay)) -} - -/** The sun's height (−1 to 1) and direction, rising at dawn in the east and setting at dusk in the west. */ -export function sunAt(hourOfDay: number, dawnHour: number, duskHour: number) { - const angle = ((hourOfDay - dawnHour) / (duskHour - dawnHour)) * Math.PI - return { elevation: Math.sin(angle), azimuth: Math.cos(angle) } -} - /** Forager IDs count from 0; people count from 1. */ export const foragerName = (foragerId: number) => `Forager ${foragerId + 1}` diff --git a/src/valleyView/seasonLook.test.ts b/src/valleyView/seasonLook.test.ts new file mode 100644 index 0000000..e533beb --- /dev/null +++ b/src/valleyView/seasonLook.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import { VALLEY_DEFAULT_CONFIG } from '../valley/config' +import { BIRCH, BILBERRY, dayLengthHours, foliageAt, grassTint, sunAt, yearFraction } from './seasonLook' + +const config = VALLEY_DEFAULT_CONFIG +/** The run's minute of a given hour on the day at this fraction of the year, from the spring equinox. */ +const minuteAt = (fraction: number, hour: number) => Math.round(fraction * config.daysPerYear) * 1_440 + hour * 60 + +describe('the sun through the year', () => { + it('counts the year from the spring equinox, where the run starts', () => { + expect(yearFraction(config, 0)).toBe(0) + expect(yearFraction(config, minuteAt(0.75, 0))).toBeCloseTo( + Math.round(0.75 * config.daysPerYear) / config.daysPerYear, + 9, + ) + }) + + it('stands highest at the summer solstice and lowest at the winter one', () => { + const summer = sunAt(config, minuteAt(0.25, 12)) + const equinox = sunAt(config, minuteAt(0.5, 12)) + const winter = sunAt(config, minuteAt(0.75, 12)) + expect(Math.asin(summer.up) * (180 / Math.PI)).toBeCloseTo(61.4, 0) + // Half a day past the equinox, the declination is already about 1° south. + expect(Math.abs(Math.asin(equinox.up) * (180 / Math.PI) - 38)).toBeLessThan(1.5) + expect(Math.asin(winter.up) * (180 / Math.PI)).toBeCloseTo(14.6, 0) + // At noon the sun is due south. + expect(winter.north).toBeLessThan(0) + expect(Math.abs(winter.east)).toBeLessThan(1e-9) + }) + + it('rises in the east, and keeps longer days in summer', () => { + expect(sunAt(config, minuteAt(0.5, 8)).east).toBeGreaterThan(0) + expect(dayLengthHours(config, 0.25)).toBeCloseTo(16.5, 0) + expect(dayLengthHours(config, 0.5)).toBeCloseTo(12, 5) + expect(dayLengthHours(config, 0.75)).toBeCloseTo(7.5, 0) + expect(sunAt(config, minuteAt(0.25, 20)).light).toBeGreaterThan(0.5) + expect(sunAt(config, minuteAt(0.75, 16.5)).light).toBe(0) + }) +}) + +describe('leaves through the year', () => { + it('are green in summer, turning in autumn and bare in winter', () => { + expect(foliageAt(BIRCH, 0.3)).toMatchObject({ colour: BIRCH.summer, cover: 1 }) + expect(foliageAt(BIRCH, 0.3).scale).toBeCloseTo(1, 9) + expect(foliageAt(BIRCH, 0.56).colour).toBe(BIRCH.turning) + expect(foliageAt(BIRCH, 0.85)).toMatchObject({ colour: BIRCH.bare, cover: 0 }) + expect(foliageAt(BIRCH, 0.85).scale).toBeCloseTo(BIRCH.bareScale, 9) + expect(foliageAt(BILBERRY, 0.02).colour).toBe(BILBERRY.bare) + }) + + it('blend smoothly from one day to the next, across the year end', () => { + for (let step = 0; step < 1_000; step += 1) { + const before = foliageAt(BIRCH, step / 1_000) + const after = foliageAt(BIRCH, (step + 1) / 1_000) + expect(Math.abs(before.cover - after.cover)).toBeLessThan(0.05) + } + }) + + it('leave the grass as drawn in summer and duller in winter', () => { + expect(grassTint(0.35)).toEqual([1, 1, 1]) + expect(grassTint(0.85)[1]).toBeLessThan(1) + }) +}) diff --git a/src/valleyView/seasonLook.ts b/src/valleyView/seasonLook.ts new file mode 100644 index 0000000..37df36b --- /dev/null +++ b/src/valleyView/seasonLook.ts @@ -0,0 +1,208 @@ +import type { Color, MeshStandardMaterial } from 'three' + +import { MINUTES_PER_DAY } from '../valley/calendar' +import type { ValleyConfig } from '../valley/types' + +// How the year looks: the sun's path and the colour of leaves and grass. The observer alone draws this, from the +// displayed minute; the simulation's day still runs from `dawnHour` to `duskHour` all year. + +type SkyConfig = Pick + +/** The valley's latitude for the sun's path: 52° N, Mesolithic northern Europe (the North Sea plain, Star Carr). */ +export const LATITUDE_DEG = 52 +/** The tilt of the Earth's axis, the solar declination at the solstices. */ +const TILT_DEG = 23.44 +const RADIANS = Math.PI / 180 + +/** + * The displayed moment's place in the year, 0 to 1, counted from the spring equinox: ¼ is the summer solstice, ½ the + * autumn equinox, ¾ the winter solstice. The run starts at the spring equinox, the first day of the calendar's spring. + * It moves smoothly through each day, so colours blend rather than step. + */ +export function yearFraction(config: Pick, minute: number) { + const days = minute / MINUTES_PER_DAY + return (((days % config.daysPerYear) + config.daysPerYear) % config.daysPerYear) / config.daysPerYear +} + +const smoothstep = (from: number, to: number, x: number) => { + const t = Math.min(1, Math.max(0, (x - from) / (to - from))) + return t * t * (3 - 2 * t) +} + +/** + * Where the sun stands at the displayed minute, from the solar declination for the day of the year at + * {@link LATITUDE_DEG}: `δ = 23.44° · sin(2π · yearFraction)` and `sin(altitude) = sin φ sin δ + cos φ cos δ cos H`, + * with the hour angle `H` zero at the middle of the simulation's day and π at its dawn and dusk hours, so at the + * equinoxes the sun rises and sets on them. Days are about 16½ hours at the summer solstice and 7½ at the winter one. + * + * Returns the sun's direction as east, north and up components of a unit vector, and `light`: 0 at night, 1 in full + * daylight, easing while the sun is within about 4° of the horizon. + */ +export function sunAt(config: SkyConfig, minute: number) { + const fraction = yearFraction(config, minute) + const declination = TILT_DEG * RADIANS * Math.sin(2 * Math.PI * fraction) + const latitude = LATITUDE_DEG * RADIANS + const hour = (((minute / 60) % 24) + 24) % 24 + const noon = (config.dawnHour + config.duskHour) / 2 + const hourAngle = ((hour - noon) / (config.duskHour - config.dawnHour)) * Math.PI + const up = + Math.sin(latitude) * Math.sin(declination) + Math.cos(latitude) * Math.cos(declination) * Math.cos(hourAngle) + const east = -Math.cos(declination) * Math.sin(hourAngle) + const north = + Math.cos(latitude) * Math.sin(declination) - Math.sin(latitude) * Math.cos(declination) * Math.cos(hourAngle) + /** 1 at the summer solstice, 0 at the winter one. */ + const summer = (Math.sin(2 * Math.PI * fraction) + 1) / 2 + return { up, east, north, light: smoothstep(-0.07, 0.07, up), summer } +} + +/** Hours of daylight (sun above the horizon) on a day with this year fraction, at {@link LATITUDE_DEG}. */ +export function dayLengthHours(config: Pick, fraction: number) { + const declination = TILT_DEG * RADIANS * Math.sin(2 * Math.PI * fraction) + const cosHalf = Math.min(1, Math.max(-1, -Math.tan(LATITUDE_DEG * RADIANS) * Math.tan(declination))) + return ((2 * Math.acos(cosHalf)) / Math.PI) * (config.duskHour - config.dawnHour) +} + +/** A plant's leaf colours through the year: fresh, summer, turning, fallen-brown and bare (its twigs or stems). */ +export interface LeafPalette { + fresh: number + summer: number + turning: number + brown: number + bare: number + /** Its crown's size when bare, as a share of its full crown. */ + bareScale: number +} + +/** Bilberry: fresh green, red in autumn, its green stems left in winter. */ +export const BILBERRY: LeafPalette = { + fresh: 0x5f9a45, + summer: 0x2f7a3c, + turning: 0xa8402e, + brown: 0x7a4a30, + bare: 0x55603e, + bareScale: 0.7, +} +/** Hazel: yellow in autumn, grey-brown twigs in winter. */ +export const HAZEL: LeafPalette = { + fresh: 0x86b84d, + summer: 0x4c8a35, + turning: 0xc9a83a, + brown: 0x9a6a2e, + bare: 0x6b5a48, + bareScale: 0.45, +} +/** Birch: bright yellow in autumn, grey-white twigs in winter. */ +export const BIRCH: LeafPalette = { + fresh: 0x8cbf55, + summer: 0x4f8a3a, + turning: 0xd4b23a, + brown: 0x9a7a40, + bare: 0x857c74, + bareScale: 0.45, +} + +type Stage = keyof Omit +/** + * The deciduous year, by year fraction from the spring equinox: the stage the leaves are at, and how much of the crown + * is in leaf. Leaves open through April and May, stay green through summer, turn from mid-September, fall through + * October and November, and the crowns are bare from late November to early April. + */ +const LEAF_YEAR: [number, Stage, number][] = [ + [0.04, 'bare', 0], + [0.1, 'fresh', 0.6], + [0.16, 'fresh', 1], + [0.27, 'summer', 1], + [0.46, 'summer', 1], + [0.56, 'turning', 1], + [0.64, 'brown', 0.55], + [0.72, 'bare', 0], +] + +const channels = (rgb: number) => [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255] as const + +/** A deciduous plant's leaf colour (as 0xRRGGBB) and crown scale on a day with this year fraction. */ +export function foliageAt(palette: LeafPalette, fraction: number) { + const keys = LEAF_YEAR + let next = keys.findIndex(([at]) => at > fraction) + if (next < 0) next = 0 + const previous = (next - 1 + keys.length) % keys.length + const [fromAt, fromStage, fromCover] = keys[previous]! + const [toAt, toStage, toCover] = keys[next]! + const span = (toAt - fromAt + 1) % 1 || 1 + const t = smoothstep(0, 1, ((fraction - fromAt + 1) % 1) / span) + const from = channels(palette[fromStage]) + const to = channels(palette[toStage]) + const mixed = from.map((value, index) => Math.round(value + (to[index]! - value) * t)) + const cover = fromCover + (toCover - fromCover) * t + return { + colour: (mixed[0]! << 16) | (mixed[1]! << 8) | mixed[2]!, + cover, + scale: palette.bareScale + (1 - palette.bareScale) * cover, + } +} + +/** + * How the grass is tinted, as red, green and blue multipliers of its colour: greener in spring, as drawn in summer, + * duller and browner from late autumn through winter. + */ +export function grassTint(fraction: number): [number, number, number] { + const leaf = foliageAt(HAZEL, fraction).cover + // Spring flush peaks a little after the leaves open, and fades by midsummer. + const flush = smoothstep(0.04, 0.14, fraction) * (1 - smoothstep(0.2, 0.32, fraction)) + const dull = 1 - leaf + return [1 - 0.06 * flush + 0.06 * dull, 1 + 0.1 * flush - 0.12 * dull, 1 - 0.08 * flush - 0.12 * dull] +} + +/** The uniforms one deciduous material's shader reads: its leaf colour and its crown scale. */ +export interface FoliageUniforms { + colour: { value: Color } + scale: { value: number } +} + +/** + * Makes a material's colour and size follow the season without touching its instances: its colour becomes the leaf + * colour uniform, and each instance's crown shrinks about its centre by the scale uniform, across fully and upwards by + * `upShare` of that. With `evergreen`, only instances whose instance colour's red channel is 1 are deciduous; those at + * 0 keep the evergreen colour and size, so pines and birches can share one mesh. The depth material used for shadows + * shrinks the same way. + */ +export function seasonalFoliage( + THREE: typeof import('three'), + material: MeshStandardMaterial, + uniforms: FoliageUniforms, + upShare: number, + evergreen?: Color, +) { + const key = `foliage-${upShare}-${evergreen ? 'mixed' : 'all'}` + const deciduous = evergreen ? '(instanceColor.r)' : '1.0' + const shrink = ` + #if ${evergreen ? 'defined( USE_INSTANCING_COLOR )' : '1'} + float leafScale = mix(1.0, uLeafScale, ${deciduous}); + transformed.xz *= leafScale; + transformed.y *= mix(1.0, leafScale, ${upShare.toFixed(3)}); + #endif` + const patchVertex = (shader: { vertexShader: string; uniforms: Record }) => { + shader.uniforms.uLeafScale = uniforms.scale + shader.vertexShader = + 'uniform float uLeafScale;\n' + + shader.vertexShader.replace('#include ', `#include \n${shrink}`) + } + material.onBeforeCompile = (shader) => { + patchVertex(shader) + shader.uniforms.uLeafColour = uniforms.colour + if (evergreen) shader.uniforms.uEvergreen = { value: evergreen } + shader.fragmentShader = + `uniform vec3 uLeafColour;\n${evergreen ? 'uniform vec3 uEvergreen;\n' : ''}` + + shader.fragmentShader.replace( + '#include ', + evergreen + ? '#if defined( USE_COLOR )\ndiffuseColor.rgb = mix(uEvergreen, uLeafColour, vColor.r);\n#endif' + : 'diffuseColor.rgb = uLeafColour;', + ) + } + material.customProgramCacheKey = () => key + const depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking }) + depth.onBeforeCompile = patchVertex + depth.customProgramCacheKey = () => `${key}-depth` + return depth +} diff --git a/src/valleyView/tiledInstances.ts b/src/valleyView/tiledInstances.ts index a7c12ac..f9979d3 100644 --- a/src/valleyView/tiledInstances.ts +++ b/src/valleyView/tiledInstances.ts @@ -1,4 +1,4 @@ -import type { BufferGeometry, Group, InstancedMesh, Material, Matrix4 } from 'three' +import type { BufferGeometry, Color, Group, InstancedMesh, Material, Matrix4 } from 'three' type Three = typeof import('three') @@ -77,6 +77,13 @@ export class TiledInstances { this.dirty.add(tile) } + /** Sets an instance's colour; call before the first draw, so each tile's shader is built with instance colours. */ + setColorAt(index: number, color: Color) { + const mesh = this.tiles[this.tileOf[index]!]! + mesh.setColorAt(this.localOf[index]!, color) + mesh.instanceColor!.needsUpdate = true + } + /** Whether a plant's tile is drawn. */ shows(plant: number) { return this.tiles[this.tileOfPlant[plant]!]!.visible @@ -125,6 +132,10 @@ export class TiledInstances { for (const tile of this.tiles) tile.receiveShadow = value } + set customDepthMaterial(value: Material) { + for (const tile of this.tiles) tile.customDepthMaterial = value + } + computeBoundingSphere() { for (const tile of this.tiles) tile.computeBoundingSphere() } diff --git a/src/valleyView/valleyScene.ts b/src/valleyView/valleyScene.ts index 07b0373..3408b56 100644 --- a/src/valleyView/valleyScene.ts +++ b/src/valleyView/valleyScene.ts @@ -18,6 +18,7 @@ import { livingMembers } from '../valley/social' import { TiledInstances } from './tiledInstances' import { tiledSurface } from './tiledSurface' import { meshSurfaces, surfaceHeightAt } from './meshSurface' +import { BILBERRY, BIRCH, foliageAt, grassTint, HAZEL, seasonalFoliage, sunAt, yearFraction } from './seasonLook' import type { GroundMesh } from '../valley/mesh' import { woodTarget } from '../valley/trade' import type { ValleyState } from '../valley/types' @@ -36,7 +37,6 @@ import { clampDistance, clampTarget, currentSwaps, - daylightAt, displayedHutLogs, displayedLoad, decorOf, @@ -58,7 +58,6 @@ import { type ClearView, plantLook, siteRings, - sunAt, toMetres, towardFire, treeShape, @@ -71,6 +70,10 @@ type Three = typeof import('three') const NIGHT_SKY = 0x070a12 const DAY_SKY = 0x7fa6b8 +/** The day sky at the winter solstice: paler and greyer than summer's. */ +const WINTER_SKY = 0x9aaab2 +/** The sky's warm tint while the sun is low. */ +const LOW_SUN_GLOW = 0xd99a6a const OUTSIDE = 0x2c4a30 /** The grassland's surface colours: grass, dirt and stone, by ground code. */ const GROUND_COLOURS = [0x4f7a42, 0x785b3b, 0x85827a] @@ -369,6 +372,20 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall const trunkMaterial = new THREE.MeshStandardMaterial({ color: TRUNK, roughness: 1, flatShading: true }) const crownGeometry = new THREE.ConeGeometry(1, 1, 8) const crownMaterial = new THREE.MeshStandardMaterial({ color: CROWN, roughness: 0.85, flatShading: true }) + // Leaves follow the season through shared uniforms: bilberry and hazel are deciduous, and so are the birches among + // the trees; the pines keep the evergreen crown colour. Bilberry keeps its height, being only thinned to its stems. + const foliage = (leaves: { summer: number }) => ({ + colour: { value: new THREE.Color(leaves.summer) }, + scale: { value: 1 }, + }) + const bushFoliage = foliage(BILBERRY) + const hazelFoliage = foliage(HAZEL) + const birchFoliage = foliage(BIRCH) + const leafDepth = seasonalFoliage(THREE, leafMaterial, bushFoliage, 0) + const hazelLeafDepth = seasonalFoliage(THREE, hazelLeafMaterial, hazelFoliage, 0.5) + const crownDepth = seasonalFoliage(THREE, crownMaterial, birchFoliage, 0.5, new THREE.Color(CROWN)) + /** The year fraction the leaves and grass were last coloured for. */ + let seasonDrawn = -1 const firewoodMaterial = new THREE.MeshStandardMaterial({ color: FIREWOOD, roughness: 0.95, flatShading: true }) const deadwoodGeometry = new THREE.CylinderGeometry(0.035, 0.045, 1, 5) const stoneGeometry = new THREE.DodecahedronGeometry(0.12, 0) @@ -445,6 +462,9 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall let ground: Mesh | null = null let outside: Mesh | null = null + /** The ground's materials, tinted by the season: their colour multiplies the grass, dirt and stone. */ + let groundMaterial: MeshStandardMaterial | null = null + let outsideMaterial: MeshStandardMaterial | null = null let leaves: TiledInstances | null = null let berryMesh: TiledInstances | null = null let hazelLeaves: TiledInstances | null = null @@ -1235,20 +1255,15 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall const size = state.config.valleySizeCm / 100 const surfaces = meshGeometries(state) const terrainGeometry = surfaces.terrain - ground = tiledSurface( - THREE, - terrainGeometry, - new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95, flatShading: true }), - SURFACE_TILE_M, - ) + groundMaterial = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95, flatShading: true }) + outsideMaterial = new THREE.MeshStandardMaterial({ color: OUTSIDE, roughness: 1 }) + seasonDrawn = -1 + ground = tiledSurface(THREE, terrainGeometry, groundMaterial, SURFACE_TILE_M) for (const tile of ground.children) { tile.receiveShadow = true tile.castShadow = true } - outside = new THREE.Mesh( - new THREE.PlaneGeometry(size * 8, size * 8), - new THREE.MeshStandardMaterial({ color: OUTSIDE, roughness: 1 }), - ) + outside = new THREE.Mesh(new THREE.PlaneGeometry(size * 8, size * 8), outsideMaterial) outside.rotation.x = -Math.PI / 2 outside.position.y = state.layout.terrain.height.reduce((min, h) => Math.min(min, h), 0) / 100 - 1 const water = state.layout.terrain.water @@ -1413,6 +1428,18 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall crowns = new TiledInstances(THREE, crownGeometry, crownMaterial, CROWN_CONES.length, treeX, treeZ, size, 100) stumps = new TiledInstances(THREE, trunkGeometry, trunkMaterial, 1, treeX, treeZ, size, 100) deadwood = new TiledInstances(THREE, deadwoodGeometry, firewoodMaterial, DEADWOOD_STICKS, treeX, treeZ, size, 100) + // About half the trees are birches and half pines, by a hash of the tree's number that draws on no simulation + // stream: a birch's crown instances carry red 1, which the crown shader reads as deciduous. + const broadleaf = new THREE.Color(1, 1, 1) + const needleleaf = new THREE.Color(0, 0, 0) + for (let tree = 0; tree < trees.count; tree += 1) { + const birch = Math.imul(tree + 1, 0x9e3779b1) >>> 31 === 0 + for (let cone = 0; cone < CROWN_CONES.length; cone += 1) + crowns.setColorAt(tree * CROWN_CONES.length + cone, birch ? broadleaf : needleleaf) + } + leaves.customDepthMaterial = leafDepth + hazelLeaves.customDepthMaterial = hazelLeafDepth + crowns.customDepthMaterial = crownDepth treeDrawn = Array.from({ length: trees.count }, () => ({ felled: false, trunk: 1, crown: 1, deadwood: 1 })) for (let tree = 0; tree < trees.count; tree += 1) placeTree(tree, treeDrawn[tree]!) // Stone spots: a heap of grey stones each. @@ -1566,8 +1593,12 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall } const night = new THREE.Color(NIGHT_SKY) - const day = new THREE.Color(DAY_SKY) + const summerDay = new THREE.Color(DAY_SKY) + const winterDay = new THREE.Color(WINTER_SKY) + const glow = new THREE.Color(LOW_SUN_GLOW) + const day = new THREE.Color() const sky = new THREE.Color() + const tint = new THREE.Color() const keys = new Set() function poseFigure(figure: Figure, pose: ForagerPose, id: number, nowMs: number) { @@ -1626,14 +1657,35 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall drawn = state const minutes = display.minute const nowMs = minutes * 60_000 - const hourOfDay = (minutes / 60) % 24 - const light = daylightAt(hourOfDay, config.dawnHour, config.duskHour) - const { elevation, azimuth } = sunAt(hourOfDay, config.dawnHour, config.duskHour) + // The sun follows the day of the year: high and long in summer, low and short in winter. + const sunNow = sunAt(config, minutes) + const { light } = sunNow + const elevation = Math.max(0, sunNow.up) + day.copy(winterDay).lerp(summerDay, sunNow.summer) sky.copy(night).lerp(day, light) + // A warm glow while the sun is low, at either end of the day. + sky.lerp(glow, 0.35 * light * (1 - Math.min(1, elevation / 0.3))) ;(scene.background as InstanceType).copy(sky) ;(scene.fog as InstanceType).color.copy(sky) - hemisphere.intensity = 0.25 + 0.65 * light + hemisphere.intensity = 0.25 + (0.5 + 0.25 * elevation) * light moon.intensity = 0.35 * (1 - light) + // Leaves and grass change slowly: recoloured when the year has moved on by a tenth of a day or more. + const fraction = yearFraction(config, minutes) + if (Math.abs(fraction - seasonDrawn) * config.daysPerYear >= 0.1) { + seasonDrawn = fraction + for (const [uniforms, leafYear] of [ + [bushFoliage, BILBERRY], + [hazelFoliage, HAZEL], + [birchFoliage, BIRCH], + ] as const) { + const look = foliageAt(leafYear, fraction) + uniforms.colour.value.setHex(look.colour) + uniforms.scale.value = look.scale + } + const [r, g, b] = grassTint(fraction) + groundMaterial?.color.setRGB(r, g, b) + outsideMaterial?.color.setHex(OUTSIDE).multiply(tint.setRGB(r, g, b)) + } // Keys pan and turn the camera smoothly, at a pace that follows the zoom. const step = Math.min(0.1, options.elapsedSeconds) * controls.distance @@ -1668,10 +1720,16 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall const span = Math.min(400, Math.max(15, controls.distance * 0.9)) const { target } = controls sun.target.position.set(target.x, 0, target.z) - sun.position.set(target.x + azimuth * span * 1.5, Math.max(0.15, elevation) * span * 2 + 10, target.z + span * 0.6) + // The scene's +x is east and +z south. Below a low floor the light keeps its height, so shadows stay bounded. + sun.position.set( + target.x + sunNow.east * span * 2, + Math.max(0.15, elevation) * span * 2 + 10, + target.z - sunNow.north * span * 2, + ) Object.assign(sun.shadow.camera, { left: -span, right: span, top: span, bottom: -span, near: 1, far: span * 6 }) sun.shadow.camera.updateProjectionMatrix() - sun.intensity = 3 * light * Math.max(0.25, elevation) + // Brighter the higher it stands: about 3.2 at a summer noon, 2.7 at an equinox and 2 at a winter noon. + sun.intensity = 3.4 * light * (0.45 + 0.55 * elevation) sun.color.setHSL(0.1, 0.6, 0.6 + 0.35 * Math.max(0, elevation)) // Only plants whose drawn fill changed are redrawn, and only those drawn; one out of view is redrawn when it shows. diff --git a/src/valleyView/valleyViewModel.ts b/src/valleyView/valleyViewModel.ts index 4796ad7..6552625 100644 --- a/src/valleyView/valleyViewModel.ts +++ b/src/valleyView/valleyViewModel.ts @@ -21,7 +21,7 @@ import type { Group, Plants, Point, ValleyConfig, ValleyLayout, ValleyState } fr import { palette } from '../ui/theme' import { decorPoints, foragerColor, foragerName, formatHours } from './display' -export { clockLabel, daylightAt, foragerName, formatKcal, sunAt, TERMS_COLORS } from './display' +export { clockLabel, foragerName, formatKcal, TERMS_COLORS } from './display' export { foragerColor, formatHours } /**