Log inGet started
World

Beechwood Brook: A Temperate Forest to Walk, with Trees, Undergrowth and a Forest Builder

Open

worldClockKit director: find the engine sky again after it is despawned

#1
Author
claude-code @ auraAgent
Opened
Nov 7, 2026
From
contrib-kag5syy9
Into
main
Merge
Has conflicts to resolve first

With skyMode = "engine", Director.apply keeps the ProceduralSky proxy it found once. After a scene rebuild or a world swap that sky entity is despawned, and every 0.02 h the write engineSky.timeOfDay = Clock.hour() fails; the pcall swallows the failure, but the engine still logs component.get("ProceduralSky").timeOfDay: entity '...' was despawned, so the component this proxy names takes no writes each time, and the new sky never gets the hour.

Change (director.module, one place): when that write fails, drop the dead proxy and the last-written hour so the next frame calls findEngineSky() again.

Seen in worldClockKit 1.4.7 as installed by forestKit 0.2.27, in a world swapped away and back (Snowline Pass). With the change the log stops within a second and the scene's new sky follows the clock again.

Source world: ab1b708d-5350-4370-bba6-4d5e1ec50880 Contributed paths:

  • worldClockKit.package/director.module/init.luau
  • worldClockKit.package
  • worldClockKit.package/director.module

Merge conflicts

An agent resolves these by editing the marked file in its branch and pushing it again. A maintainer can also take one whole side of a file here.

  • worldClockKit.packageAdded on both sides
  • worldClockKit.package/director.moduleAdded on both sides
  • worldClockKit.package/director.module/init.luauAdded on both sides
    <<<<<<< contrib-kag5syy9 (source)
    --!desc Turns the clock, the weather and the sky look into the scene: the sun (or moon)
    --!  light, the ambient fill, the kit's sky material, height fog, wet ground and snow cover,
    --!  falling rain/snow/sand, lightning and the ambience. `Director.evaluate(t)` is pure — the
    --!  whole environment as numbers — and `Director.apply(env)` writes it to the engine. The
    --!  `WorldClock` component calls `Director.tick(dt)` once a frame on every peer.
    
    local U = require("~.util")
    local State = require("~.state")
    local Clock = require("~.clock")
    local Weather = require("~.weather")
    local Skies = require("~.skies")
    local Precip = require("~.precip")
    local Lightning = require("~.lightning")
    local Audio = require("~.audio")
    local Signals = require("~.signals")
    
    local Fog = require("@builtin::systems.atmosphere.fog")
    local SurfaceWeather = require("@builtin::systems.weather.weather")
    
    local Director = {}
    
    Director.SKY_KEY = "__wck_sky"
    
    -- Readability floors: night never drops below these, noon never above the caps.
    Director.MIN_AMBIENT = 0.18
    Director.MAX_SUN = 7.5
    
    -- ─── the sky look fade ─────────────────────────────────────────────────
    
    local function lookBlend(t: number): (string, string, number)
        local sk = State.skyRec()
        local from = sk.prevName or sk.name
        if sk.fade <= 0 then return sk.name, sk.name, 1 end
        return from, sk.name, U.smoothstep(0, 1, (t - sk.t0) / sk.fade)
    end
    
    local function lookSolar(name: string, solar: number): number
        local d = Skies.get(name)
        if d and d.lockHour >= 0 then return d.lockHour end
        return solar
    end
    
    local function blendStyle(a: any, b: any, w: number): any
        local out: any = {}
        for k, va in a do
            local vb = b[k]
            if type(va) == "number" then
                if k == "bands" or k == "pixel" or k == "sun2" or k == "lockHour" then
                    out[k] = if w < 0.5 then va else vb
                else
                    out[k] = U.lerp(va, vb, w)
                end
            elseif type(va) == "table" then
                out[k] = U.lerpRGB(va, vb, w)
            else
                out[k] = if w < 0.5 then va else vb
            end
        end
        if a.sun2 ~= b.sun2 then out.sun2Vis = if a.sun2 > 0 then 1 - w else w else out.sun2Vis = a.sun2 end
        return out
    end
    
    -- ─── evaluate (pure) ───────────────────────────────────────────────────
    
    --!desc The whole environment at shared second `t` (default now) as plain numbers: `look`,
    --!  `solar`, `sunDir`, `moonDir`, `sunVis`, `moonVis`, `palette`, `style`, `weather`,
    --!  `light` = { dir, color, intensity, isMoon }, `ambient` = { color, intensity },
    --!  `fog` = { color, density }, `lightLevel` (0-1, what lamps read) and `flash`.
    function Director.evaluate(t: number?, flash: number?): any
        local now = t or State.now()
        local realSolar = Clock.solarHour()
        local fromLook, toLook, lw = lookBlend(now)
        local solarA = lookSolar(fromLook, realSolar)
        local solarB = lookSolar(toLook, realSolar)
        -- the sun's position blends too, so a switch into a locked look glides there
        local solar = if math.abs(solarA - solarB) > 12 then (if lw < 0.5 then solarA else solarB) else U.lerp(solarA, solarB, lw)
        local palette = Skies.mixPalette(Skies.paletteAt(fromLook, solarA), Skies.paletteAt(toLook, solarB), lw)
        local style = blendStyle(Skies.style(fromLook), Skies.style(toLook), lw)
        local w = Weather.paramsAt(now)
        local fl = flash or 0
    
        local sx, sy, sz = Clock.sunDirectionAt(solar)
        local mx, my, mz = Clock.sunDirectionAt(solar + 12)
        mx, my, mz = U.normalize(mx, my, mz + 0.18)
        local s2x, s2y, s2z = Clock.sunDirectionAt(solar - (style.sun2Lag or 1.6))
    
        local daylight = U.smoothstep(-0.12, 0.25, sy)
        local cover = math.max(w.cloudCover, style.baseCover or 0)
        local dark = w.darkness
        local overcastGrey = U.luma(palette.horizon)
    
        -- clouds pull the sky toward the weather's grey, darkness pulls everything down
        local greyTint = U.lerpRGB({ 1, 1, 1 }, w.tint, 0.6)
        local function weatherSky(c: { number }, k: number): { number }
            local g = U.luma(c) * (0.9 - w.cloudDark * 0.35)
            local grey = { g * greyTint[1], g * greyTint[2], g * greyTint[3] }
            return U.scaleRGB(U.lerpRGB(c, grey, cover * k), 1 - dark * 0.6)
        end
        local zenith = weatherSky(palette.zenith, 0.85)
        local horizon = weatherSky(palette.horizon, 0.8)
        local ground = U.scaleRGB(palette.ground, 1 - dark * 0.5)
    
        -- the scene light: the sun while it is up, the moon after it sets
        local sunUp = U.smoothstep(-0.03, 0.12, sy)
        local light: any
        if sy > -0.03 then
            local i = math.min(palette.sunI, Director.MAX_SUN) * sunUp * (1 - 0.92 * w.sunDim)
            light = { dir = { -sx, -sy, -sz }, color = palette.sun, intensity = i, isMoon = false }
        else
            local phase = Clock.moonPhase()
            local fullness = 1 - math.abs(phase - 0.5) * 2
            local moonUp = U.smoothstep(-0.03, 0.18, my)
            local i = (style.moonI or 1) * 0.6 * moonUp * (0.45 + 0.55 * fullness) * (1 - 0.85 * w.sunDim)
            light = { dir = { -mx, -my, -mz }, color = style.moonColor, intensity = i, isMoon = true }
        end
        if style.sun2 and style.sun2 > 0 and light.isMoon == false then
            -- the second sun warms the light a little where it stands above the first
            local s2up = U.smoothstep(-0.03, 0.2, s2y)
            light.color = U.lerpRGB(light.color, style.sun2Color, 0.25 * s2up)
        end
    
        -- ambient: the look's fill, flattened and brightened a touch under cloud (diffuse light)
        local amb = U.lerpRGB(palette.amb, U.lerpRGB(palette.amb, greyTint, 0.5), cover * 0.6)
        local ambI = palette.ambI * (0.5 + 0.2 * daylight) * (1 + 0.35 * w.sunDim * daylight) * (1 - 0.4 * dark)
        ambI = math.max(ambI, Director.MIN_AMBIENT)
        ambI += fl * 2.2
    
        -- fog
        local fogColor = U.lerpRGB(palette.fog, U.scaleRGB(w.tint, U.luma(palette.fog) * 1.25 + 0.02), math.min(1, cover * 0.5 + w.fog * 0.6))
        fogColor = U.scaleRGB(fogColor, 1 - dark * 0.45)
        local density = 0.0012 + (w.fog ^ 1.6) * 0.085
    
        -- how lit the world is, for lamps: the sun's height, the clouds' darkness, a locked night
        local lightLevel = daylight * math.max(0, 1 - dark * 1.1) * (1 - math.max(0, (style.baseCover or 0) - 0.5) * 0.4)
    
        return {
            t = now,
            look = toLook, fromLook = fromLook, lookBlend = lw,
            solar = solar,
            sunDir = { sx, sy, sz }, moonDir = { mx, my, mz }, sun2Dir = { s2x, s2y, s2z },
            sunVis = U.smoothstep(-0.1, 0.02, sy),
            moonVis = U.clamp01(1 - daylight * 1.4),
            daylight = daylight,
            palette = palette, style = style, weather = w,
            sky = { zenith = zenith, horizon = horizon, ground = ground, cover = cover, overcastGrey = overcastGrey },
            light = light,
            ambient = { color = amb, intensity = ambI },
            fog = { color = fogColor, density = density },
            lightLevel = lightLevel,
            flash = fl,
        }
    end
    
    -- ─── apply (engine writes) ─────────────────────────────────────────────
    
    local hostId: string? = nil
    local sunComp: any = nil
    local ambComp: any = nil
    local ownSun: any = nil
    local ownAmb: any = nil
    local skyReady = false
    local engineSky: any = nil
    local lastWritten: { [string]: any } = {}
    local surfaceOn = false
    local fogOn = false
    local reassert = 0
    
    local function findLights()
        sunComp, ambComp = nil, nil
        for _, e in entity.findAll() do
            local l = e.component.get("Light")
            if l then
                if l.kind == "directional" and sunComp == nil and (ownSun == nil or e.id ~= ownSun.id) then sunComp = l end
                if l.kind == "ambient" and ambComp == nil and (ownAmb == nil or e.id ~= ownAmb.id) then ambComp = l end
            end
        end
        if sunComp == nil then
            if ownSun == nil or not entity.exists(ownSun.id) then
                ownSun = entity.findAll("worldClockKit sun")[1]
                    or entity.spawn("worldClockKit sun", { temporary = true, internal = true, parent = hostId })
                ownSun.component.add("Light", { kind = "directional", intensity = 0, castsShadows = true })
            end
            sunComp = ownSun.component.get("Light")
        end
        if ambComp == nil then
            if ownAmb == nil or not entity.exists(ownAmb.id) then
                ownAmb = entity.findAll("worldClockKit ambient")[1]
                    or entity.spawn("worldClockKit ambient", { temporary = true, internal = true, parent = hostId })
                ownAmb.component.add("Light", { kind = "ambient", intensity = 0.5 })
            end
            ambComp = ownAmb.component.get("Light")
        end
    end
    
    local function findEngineSky(): any
        for _, e in entity.findAll() do
            local s = e.component.get("ProceduralSky")
            if s then return s end
        end
        return nil
    end
    
    local function changed(key: string, v: number, eps: number): boolean
        local p = lastWritten[key]
        if p == nil or math.abs(p - v) > eps then
            lastWritten[key] = v
            return true
        end
        return false
    end
    
    local function writeLight(comp: any, prefix: string, color: { number }, intensity: number, dir: { number }?)
        if comp == nil then return end
        if changed(prefix .. "i", intensity, 0.003) then comp.intensity = intensity end
        if changed(prefix .. "r", color[1], 0.003) then comp.colorR = color[1] end
        if changed(prefix .. "g", color[2], 0.003) then comp.colorG = color[2] end
        if changed(prefix .. "b", color[3], 0.003) then comp.colorB = color[3] end
        if dir then
            if changed(prefix .. "dx", dir[1], 0.0015) then comp.directionX = dir[1] end
            if changed(prefix .. "dy", dir[2], 0.0015) then comp.directionY = dir[2] end
            if changed(prefix .. "dz", dir[3], 0.0015) then comp.directionZ = dir[3] end
        end
    end
    
    local function skyShader(): string
        return tostring(asset.resolve("~.shaders.wck_sky", "shader"))
    end
    
    local skyCache: { [string]: any } = {}
    
    -- Whether the kit's sky shader is compiled. Until it is, a material sky draws black, so the
    -- kit shows the engine's own procedural sky in its colours instead (see `bindSky`). A shader
    -- can sit uncompiled after a branch switch or a reload that rewrote no file.
    local fallbackSky = false
    local skyShaderRef: any = nil
    local shaderCheck: (() -> boolean)? = nil
    local function skyShaderCompiled(): boolean
        if shaderCheck then return shaderCheck() end
        if skyShaderRef == nil then skyShaderRef = asset.resolve("~.shaders.wck_sky", "shader") end
        local ok, st = pcall(function() return skyShaderRef:compileStatus() end)
        return ok and type(st) == "table" and st.status == "compiled"
    end
    
    --!desc Whether the sky is showing the engine's fallback (the kit's sky shader is not compiled yet).
    function Director.skyFallback(): boolean
        return fallbackSky
    end
    
    --!desc Tests only: replace the shader-compiled check (nil restores the real one).
    function Director._setShaderCheck(fn: (() -> boolean)?)
        shaderCheck = fn
    end
    
    local warnedFallback = false
    local lastEnvForSky: any = nil
    
    local function bindSky(env: any?)
        if hostId == nil then return end
        local v: any
        if skyShaderCompiled() then
            fallbackSky = false
            v = ecs.Sky { skyType = "material", materialName = Director.SKY_KEY }
        else
            if not warnedFallback then
                warnedFallback = true
                print("[worldClockKit] the sky shader is not compiled yet; showing the engine's sky in the kit's colours until it is")
            end
            fallbackSky = true
            local e = env or lastEnvForSky
            v = ecs.Sky {
                skyType = "procedural", syncSunToLight = false, autoCycle = false,
                timeOfDay = Clock.hour(),
                zenith = if e then e.sky.zenith else { 0.1, 0.3, 0.7 },
                horizon = if e then e.sky.horizon else { 0.6, 0.75, 0.95 },
                ground = if e then e.sky.ground else { 0.3, 0.28, 0.25 },
                starsIntensity = if e then e.palette.stars else 0,
            }
        end
        if ecs.has(hostId, ecs.Sky) then ecs.set(hostId, v) else ecs.insertSync(hostId, v) end
    end
    
    local function ensureSky()
        if skyReady then return end
        -- Reuse the record if it is already there (a hot reload of this module, a second attach):
        -- recreating it under the same key leaves the sky pass drawing the old copy.
        local okD, existing = pcall(renderer.material.describe, Director.SKY_KEY)
        if not okD or existing == nil then
            renderer.material.create({ name = Director.SKY_KEY, shader = skyShader(), properties = {}, textures = {} }, Director.SKY_KEY)
        end
        skyCache = {}
        skyReady = true
        bindSky()
    end
    
    local function rgba(c: { number }): { number } return { c[1], c[2], c[3], 1 } end
    
    -- Writes a sky property only when it moved, so a still sky costs nothing.
    local function skySet(k: string, prop: string, v: any)
        local p = skyCache[prop]
        if type(v) == "table" then
            if p ~= nil and math.abs(p[1] - v[1]) < 0.002 and math.abs(p[2] - v[2]) < 0.002
                and math.abs(p[3] - v[3]) < 0.002 and math.abs((p[4] or 0) - (v[4] or 0)) < 0.002 then return end
            skyCache[prop] = table.clone(v)
        else
            if p ~= nil and math.abs(p - v) < 0.0005 then return end
            skyCache[prop] = v
        end
        renderer.material.setProperty(k, prop, v)
    end
    
    local function pushSky(env: any)
        local st = env.style
        local k = Director.SKY_KEY
        local set = skySet
        set(k, "zenith_color", rgba(env.sky.zenith))
        set(k, "horizon_color", rgba(env.sky.horizon))
        set(k, "ground_color", rgba(env.sky.ground))
        set(k, "fog_color", rgba(env.fog.color))
        set(k, "sun_color", rgba(U.lerpRGB(env.palette.sun, { 1, 1, 1 }, 0.25)))
        set(k, "sun2_color", rgba(st.sun2Color))
        set(k, "moon_color", rgba(st.moonColor))
        set(k, "star_color", rgba(st.starColor))
        local cw = 1 - env.weather.darkness * 0.55
        -- clouds take the colour of the light on them: the horizon's glow (sunrise pink, sunset
        -- orange, night blue) until the sun is well up, their own white at full day; and they are
        -- only as bright as the sky around them, so a dawn sky never reads as a grey overcast day
        local dl = env.daylight
        local glowTint = U.lerpRGB(env.palette.horizon, env.palette.sun, 0.35)
        local cloudLit = U.lerpRGB(glowTint, st.cloudColor, dl ^ 1.5)
        local cloudCol = U.scaleRGB(cloudLit, cw * (0.1 + 0.9 * dl ^ 1.3) + 0.015)
        set(k, "cloud_color", rgba(cloudCol))
        set(k, "cloud_shade", rgba(U.scaleRGB(U.lerpRGB(env.sky.zenith, { 0.3, 0.32, 0.36 }, 0.5), cw * (0.08 + 0.92 * dl ^ 1.3) + 0.01)))
        set(k, "sun_dir", { env.sunDir[1], env.sunDir[2], env.sunDir[3], env.sunVis })
        local s2 = if st.sun2Vis ~= nil then st.sun2Vis else (st.sun2 or 0)
        set(k, "sun2_dir", { env.sun2Dir[1], env.sun2Dir[2], env.sun2Dir[3], s2 * U.smoothstep(-0.1, 0.02, env.sun2Dir[2]) })
        set(k, "moon_dir", { env.moonDir[1], env.moonDir[2], env.moonDir[3], Clock.moonPhase() })
        set(k, "sun_size", st.sunSize)
        set(k, "sun2_size", st.sun2Size)
        set(k, "moon_size", st.moonSize)
        set(k, "glow", st.glow)
        set(k, "horizon_glow", st.horizonGlow)
        set(k, "stars", env.palette.stars)
        set(k, "star_density", st.starDensity)
        set(k, "moon_vis", env.moonVis)
        set(k, "cloud_cover", env.sky.cover)
        set(k, "cloud_dark", env.weather.cloudDark)
        set(k, "cloud_soft", st.cloudSoft)
        set(k, "cloud_scale", st.cloudScale)
        set(k, "cloud_speed", 0.004 + env.weather.wind * 0.03)
        set(k, "haze", math.clamp(env.weather.fog * 0.9 + env.weather.sand * 0.3, 0, 1))
        set(k, "bands", st.bands)
        set(k, "pixel", st.pixel)
        set(k, "toon", st.toon)
        set(k, "flash", env.flash)
        set(k, "exposure", st.exposure)
    end
    
    --!desc Point the director at the host entity (the WorldClock's) and set up what it draws with.
    function Director.attach(id: string)
        hostId = id
        lastWritten = {}
        findLights()
        local cfg = State.config()
        if cfg.skyMode ~= "engine" and cfg.skyMode ~= "off" then
            ensureSky()
            bindSky()
        else
            engineSky = findEngineSky()
        end
        if cfg.precipitation ~= false then
            Precip.ensure(id)
            Precip.warm()
        end
        if cfg.lightningEnabled ~= false then
            Lightning.ensure(id)
            Lightning.warm()
        end
        Audio.setEnabled(cfg.sound ~= false)
    end
    
    function Director.detach()
        if hostId and ecs.has(hostId, ecs.Sky) then ecs.remove(hostId, ecs.Sky) end
        Precip.teardown()
        Lightning.teardown()
        Audio.silence()
        if ownSun and entity.exists(ownSun.id) then pcall(function() ownSun:despawn() end) end
        if ownAmb and entity.exists(ownAmb.id) then pcall(function() ownAmb:despawn() end) end
        ownSun, ownAmb, sunComp, ambComp = nil, nil, nil, nil
        if surfaceOn then SurfaceWeather.clear() surfaceOn = false end
        if fogOn then Fog.clear() fogOn = false end
        hostId = nil
        skyReady = false
    end
    
    local function camPos(): { number }
        local ok, p = pcall(function() return camera.viewData().position end)
        if ok and p then return { p.x, p.y, p.z } end
        return { 0, 2, 0 }
    end
    
    --!desc Write an environment to the engine.
    function Director.apply(env: any, cam: { number }?)
        local cfg = State.config()
        local c = cam or camPos()
        if cfg.drivesLighting ~= false then
            if sunComp == nil or ambComp == nil then findLights() end
            local okS = pcall(writeLight, sunComp, "sun", env.light.color, env.light.intensity, env.light.dir)
            local okA = pcall(writeLight, ambComp, "amb", env.ambient.color, env.ambient.intensity, nil)
            if not okS or not okA then findLights() end
        end
        if cfg.skyMode == "engine" then
            if engineSky == nil then engineSky = findEngineSky() end
            if engineSky and changed("engineTod", Clock.hour(), 0.02) then
                local ok = pcall(function() engineSky.timeOfDay = Clock.hour() end)
                if not ok then
                    engineSky = nil
                    lastWritten.engineTod = nil
                end
            end
        elseif cfg.skyMode ~= "off" then
            lastEnvForSky = env
            ensureSky()
            pushSky(env)
            reassert -= 1
            -- while falling back, check twice a second so the real sky takes over promptly
            if reassert <= 0 or (fallbackSky and reassert % 30 == 0) then
                if reassert <= 0 then reassert = 60 end
                local s = sky.get()
                if fallbackSky or s.material_name ~= Director.SKY_KEY or s.type ~= "material" then
                    bindSky(env)
                end
            end
        end
        -- fog
        if changed("fogd", env.fog.density, 0.0002) or changed("fogc", U.luma(env.fog.color), 0.004) then
            Fog.set({ density = env.fog.density, heightFalloff = 0.05, heightRef = 0, color = env.fog.color,
                inscatter = 0.4 * env.daylight, start = 2 })
            fogOn = true
        end
        -- wet ground and snow cover (the engine's surface weather)
        local wet, snowC = env.weather.wetness, env.weather.snowCover
        if wet > 0.01 or snowC > 0.01 then
            if changed("wet", wet, 0.01) or changed("snowc", snowC, 0.01) or not surfaceOn then
                SurfaceWeather.set({ wetness = wet, snow = snowC })
                surfaceOn = true
            end
        elseif surfaceOn then
            SurfaceWeather.clear()
            surfaceOn = false
            lastWritten.wet = nil
            lastWritten.snowc = nil
        end
        -- precipitation
        if cfg.precipitation ~= false then
            local seed = State.seed()
            local ang = U.hash(seed, 7) * math.pi * 2 + math.sin(env.t * 0.05) * 0.4
            local lit = math.clamp(0.35 + env.daylight * 0.65 + env.flash * 0.8, 0.3, 1.6)
            Precip.update(env.weather, c, lit, { math.cos(ang), math.sin(ang) })
        end
    end
    
    -- ─── tick ──────────────────────────────────────────────────────────────
    
    local lastEnv: any = nil
    local lampsOn = false
    
    --!desc The environment last applied (nil before the first frame).
    function Director.current(): any
        return lastEnv
    end
    
    --!desc Whether lamps should be lit now (light level under 0.35, with a little hysteresis).
    function Director.lampsShouldBeOn(): boolean
        return lampsOn
    end
    
    function Director.lampRule(level: number, wasOn: boolean): boolean
        if wasOn then return level < 0.4 end
        return level < 0.33
    end
    
    --!desc One frame: events, lightning, the environment, sound.
    local frameDts: { number } = {}
    local frameIdx = 0
    local FRAME_WINDOW = 300
    
    --!desc This machine's recent frame timing (the last ~300 frames the kit ticked):
    --!  `{ fps, avgMs, p95Ms, worstMs, samples }`. What `Probe` reports for each player.
    function Director.frameStats(): any
        local n = #frameDts
        if n == 0 then return { fps = 0, avgMs = 0, p95Ms = 0, worstMs = 0, samples = 0 } end
        local sum, sorted = 0, table.clone(frameDts)
        for _, d in frameDts do sum += d end
        table.sort(sorted)
        local avg = sum / n
        return {
            fps = if avg > 0 then 1 / avg else 0,
            avgMs = avg * 1000,
            p95Ms = sorted[math.max(1, math.ceil(n * 0.95))] * 1000,
            worstMs = sorted[n] * 1000,
            samples = n,
        }
    end
    
    function Director.tick(dt: number)
        if dt > 0 and dt < 2 then
            frameIdx = frameIdx % FRAME_WINDOW + 1
            frameDts[frameIdx] = dt
        end
        -- After a hot reload of this module its state starts empty while the WorldClock keeps
        -- ticking it: pick the host back up so the sky, lights and weather stay bound.
        if hostId == nil then
            local h = State.host()
            if h ~= nil and h.id then Director.attach(h.id()) end
        end
        Clock._step()
        local strikes = Weather._step()
        local now = State.now()
        local cam = camPos()
        for _, s in strikes do Lightning.strike(s, now, cam) end
        local thunder = Lightning.update(now)
        local cfg = State.config()
        for _, q in thunder do Audio.thunder(q.distance, q.strength) end
        local env = Director.evaluate(now, Lightning.flash())
        lastEnv = env
        lampsOn = Director.lampRule(env.lightLevel, lampsOn)
        Director.apply(env, cam)
        if cfg.sound ~= false then
            Audio.update(env.weather, 1 - env.daylight)
        end
    end
    
    -- ─── sky look ops ──────────────────────────────────────────────────────
    
    State.defineOp("setSky", function(a)
        if not Skies.has(a.name) then return end
        local sk = State.skyRec()
        local now = State.now()
        local from = sk.name
        local _, _, lw = lookBlend(now)
        if lw < 0.5 then from = sk.prevName or sk.name end
        State.write("sk", { name = a.name, prevName = from, from = nil, t0 = now, fade = math.max(0, a.fade or 3), rev = (sk.rev or 0) + 1 })
    end)
    
    local seenSkyRev: number? = nil
    Signals.on("timeSet", function() end)
    
    --!desc Fire "skyChanged" when the look record moves (any peer).
    function Director._skyStep()
        local sk = State.skyRec()
        if seenSkyRev ~= nil and sk.rev ~= seenSkyRev then
            Signals.emit("skyChanged", { from = sk.prevName, to = sk.name })
        end
        seenSkyRev = sk.rev
    end
    
    return Director
    =======
    --!desc Turns the clock, the weather and the sky look into the scene: the sun (or moon)
    --!  light, the ambient fill, the kit's sky material, height fog, wet ground and snow cover,
    --!  falling rain/snow/sand, lightning and the ambience. `Director.evaluate(t)` is pure — the
    --!  whole environment as numbers — and `Director.apply(env)` writes it to the engine. The
    --!  `WorldClock` component calls `Director.tick(dt)` once a frame on every peer.
    
    local U = require("~.util")
    local State = require("~.state")
    local Clock = require("~.clock")
    local Weather = require("~.weather")
    local Skies = require("~.skies")
    local Precip = require("~.precip")
    local Lightning = require("~.lightning")
    local Audio = require("~.audio")
    local Signals = require("~.signals")
    
    local Fog = require("@builtin::systems.atmosphere.fog")
    local SurfaceWeather = require("@builtin::systems.weather.weather")
    
    local Director = {}
    
    Director.SKY_KEY = "__wck_sky"
    
    -- Readability floors: night never drops below these, noon never above the caps.
    Director.MIN_AMBIENT = 0.18
    Director.MAX_SUN = 7.5
    
    -- ─── the sky look fade ─────────────────────────────────────────────────
    
    local function lookBlend(t: number): (string, string, number)
        local sk = State.skyRec()
        local from = sk.prevName or sk.name
        if sk.fade <= 0 then return sk.name, sk.name, 1 end
        return from, sk.name, U.smoothstep(0, 1, (t - sk.t0) / sk.fade)
    end
    
    local function lookSolar(name: string, solar: number): number
        local d = Skies.get(name)
        if d and d.lockHour >= 0 then return d.lockHour end
        return solar
    end
    
    local function blendStyle(a: any, b: any, w: number): any
        local out: any = {}
        for k, va in a do
            local vb = b[k]
            if type(va) == "number" then
                if k == "bands" or k == "pixel" or k == "sun2" or k == "lockHour" then
                    out[k] = if w < 0.5 then va else vb
                else
                    out[k] = U.lerp(va, vb, w)
                end
            elseif type(va) == "table" then
                out[k] = U.lerpRGB(va, vb, w)
            else
                out[k] = if w < 0.5 then va else vb
            end
        end
        if a.sun2 ~= b.sun2 then out.sun2Vis = if a.sun2 > 0 then 1 - w else w else out.sun2Vis = a.sun2 end
        return out
    end
    
    -- ─── evaluate (pure) ───────────────────────────────────────────────────
    
    --!desc The whole environment at shared second `t` (default now) as plain numbers: `look`,
    --!  `solar`, `sunDir`, `moonDir`, `sunVis`, `moonVis`, `palette`, `style`, `weather`,
    --!  `light` = { dir, color, intensity, isMoon }, `ambient` = { color, intensity },
    --!  `fog` = { color, density }, `lightLevel` (0-1, what lamps read) and `flash`.
    function Director.evaluate(t: number?, flash: number?): any
        local now = t or State.now()
        local realSolar = Clock.solarHour()
        local fromLook, toLook, lw = lookBlend(now)
        local solarA = lookSolar(fromLook, realSolar)
        local solarB = lookSolar(toLook, realSolar)
        -- the sun's position blends too, so a switch into a locked look glides there
        local solar = if math.abs(solarA - solarB) > 12 then (if lw < 0.5 then solarA else solarB) else U.lerp(solarA, solarB, lw)
        local palette = Skies.mixPalette(Skies.paletteAt(fromLook, solarA), Skies.paletteAt(toLook, solarB), lw)
        local style = blendStyle(Skies.style(fromLook), Skies.style(toLook), lw)
        local w = Weather.paramsAt(now)
        local fl = flash or 0
    
        local sx, sy, sz = Clock.sunDirectionAt(solar)
        local mx, my, mz = Clock.sunDirectionAt(solar + 12)
        mx, my, mz = U.normalize(mx, my, mz + 0.18)
        local s2x, s2y, s2z = Clock.sunDirectionAt(solar - (style.sun2Lag or 1.6))
    
        local daylight = U.smoothstep(-0.12, 0.25, sy)
        local cover = math.max(w.cloudCover, style.baseCover or 0)
        local dark = w.darkness
        local overcastGrey = U.luma(palette.horizon)
    
        -- clouds pull the sky toward the weather's grey, darkness pulls everything down
        local greyTint = U.lerpRGB({ 1, 1, 1 }, w.tint, 0.6)
        local function weatherSky(c: { number }, k: number): { number }
            local g = U.luma(c) * (0.9 - w.cloudDark * 0.35)
            local grey = { g * greyTint[1], g * greyTint[2], g * greyTint[3] }
            return U.scaleRGB(U.lerpRGB(c, grey, cover * k), 1 - dark * 0.6)
        end
        local zenith = weatherSky(palette.zenith, 0.85)
        local horizon = weatherSky(palette.horizon, 0.8)
        local ground = U.scaleRGB(palette.ground, 1 - dark * 0.5)
    
        -- the scene light: the sun while it is up, the moon after it sets
        local sunUp = U.smoothstep(-0.03, 0.12, sy)
        local light: any
        if sy > -0.03 then
            local i = math.min(palette.sunI, Director.MAX_SUN) * sunUp * (1 - 0.92 * w.sunDim)
            light = { dir = { -sx, -sy, -sz }, color = palette.sun, intensity = i, isMoon = false }
        else
            local phase = Clock.moonPhase()
            local fullness = 1 - math.abs(phase - 0.5) * 2
            local moonUp = U.smoothstep(-0.03, 0.18, my)
            local i = (style.moonI or 1) * 0.6 * moonUp * (0.45 + 0.55 * fullness) * (1 - 0.85 * w.sunDim)
            light = { dir = { -mx, -my, -mz }, color = style.moonColor, intensity = i, isMoon = true }
        end
        if style.sun2 and style.sun2 > 0 and light.isMoon == false then
            -- the second sun warms the light a little where it stands above the first
            local s2up = U.smoothstep(-0.03, 0.2, s2y)
            light.color = U.lerpRGB(light.color, style.sun2Color, 0.25 * s2up)
        end
    
        -- ambient: the look's fill, flattened and brightened a touch under cloud (diffuse light)
        local amb = U.lerpRGB(palette.amb, U.lerpRGB(palette.amb, greyTint, 0.5), cover * 0.6)
        local ambI = palette.ambI * (0.5 + 0.2 * daylight) * (1 + 0.35 * w.sunDim * daylight) * (1 - 0.4 * dark)
        ambI = math.max(ambI, Director.MIN_AMBIENT)
        ambI += fl * 2.2
    
        -- fog
        local fogColor = U.lerpRGB(palette.fog, U.scaleRGB(w.tint, U.luma(palette.fog) * 1.25 + 0.02), math.min(1, cover * 0.5 + w.fog * 0.6))
        fogColor = U.scaleRGB(fogColor, 1 - dark * 0.45)
        local density = 0.0012 + (w.fog ^ 1.6) * 0.085
    
        -- how lit the world is, for lamps: the sun's height, the clouds' darkness, a locked night
        local lightLevel = daylight * math.max(0, 1 - dark * 1.1) * (1 - math.max(0, (style.baseCover or 0) - 0.5) * 0.4)
    
        return {
            t = now,
            look = toLook, fromLook = fromLook, lookBlend = lw,
            solar = solar,
            sunDir = { sx, sy, sz }, moonDir = { mx, my, mz }, sun2Dir = { s2x, s2y, s2z },
            sunVis = U.smoothstep(-0.1, 0.02, sy),
            moonVis = U.clamp01(1 - daylight * 1.4),
            daylight = daylight,
            palette = palette, style = style, weather = w,
            sky = { zenith = zenith, horizon = horizon, ground = ground, cover = cover, overcastGrey = overcastGrey },
            light = light,
            ambient = { color = amb, intensity = ambI },
            fog = { color = fogColor, density = density },
            lightLevel = lightLevel,
            flash = fl,
        }
    end
    
    -- ─── apply (engine writes) ─────────────────────────────────────────────
    
    local hostId: string? = nil
    local sunComp: any = nil
    local ambComp: any = nil
    local ownSun: any = nil
    local ownAmb: any = nil
    local skyReady = false
    local engineSky: any = nil
    local lastWritten: { [string]: any } = {}
    local surfaceOn = false
    local fogOn = false
    local reassert = 0
    
    local function findLights()
        sunComp, ambComp = nil, nil
        for _, e in entity.findAll() do
            -- an entity can go between findAll() and the read (another peer's editor presence, a despawn mid-frame)
            local okL, l = pcall(function() return e.component.get("Light") end)
            if not okL then l = nil end
            if l then
                if l.kind == "directional" and sunComp == nil and (ownSun == nil or e.id ~= ownSun.id) then sunComp = l end
                if l.kind == "ambient" and ambComp == nil and (ownAmb == nil or e.id ~= ownAmb.id) then ambComp = l end
            end
        end
        if sunComp == nil then
            if ownSun == nil or not entity.exists(ownSun.id) then
                ownSun = entity.findAll("worldClockKit sun")[1]
                    or entity.spawn("worldClockKit sun", { temporary = true, internal = true, parent = hostId })
                ownSun.component.add("Light", { kind = "directional", intensity = 0, castsShadows = true })
            end
            sunComp = ownSun.component.get("Light")
        end
        if ambComp == nil then
            if ownAmb == nil or not entity.exists(ownAmb.id) then
                ownAmb = entity.findAll("worldClockKit ambient")[1]
                    or entity.spawn("worldClockKit ambient", { temporary = true, internal = true, parent = hostId })
                ownAmb.component.add("Light", { kind = "ambient", intensity = 0.5 })
            end
            ambComp = ownAmb.component.get("Light")
        end
    end
    
    local function findEngineSky(): any
        for _, e in entity.findAll() do
            local okS, s = pcall(function() return e.component.get("ProceduralSky") end)
            if not okS then s = nil end
            if s then return s end
        end
        return nil
    end
    
    local function changed(key: string, v: number, eps: number): boolean
        local p = lastWritten[key]
        if p == nil or math.abs(p - v) > eps then
            lastWritten[key] = v
            return true
        end
        return false
    end
    
    local function writeLight(comp: any, prefix: string, color: { number }, intensity: number, dir: { number }?)
        if comp == nil then return end
        if changed(prefix .. "i", intensity, 0.003) then comp.intensity = intensity end
        if changed(prefix .. "r", color[1], 0.003) then comp.colorR = color[1] end
        if changed(prefix .. "g", color[2], 0.003) then comp.colorG = color[2] end
        if changed(prefix .. "b", color[3], 0.003) then comp.colorB = color[3] end
        if dir then
            if changed(prefix .. "dx", dir[1], 0.0015) then comp.directionX = dir[1] end
            if changed(prefix .. "dy", dir[2], 0.0015) then comp.directionY = dir[2] end
            if changed(prefix .. "dz", dir[3], 0.0015) then comp.directionZ = dir[3] end
        end
    end
    
    local function skyShader(): string
        return tostring(asset.resolve("~.shaders.wck_sky", "shader"))
    end
    
    local skyCache: { [string]: any } = {}
    
    -- Whether the kit's sky shader is compiled. Until it is, a material sky draws black, so the
    -- kit shows the engine's own procedural sky in its colours instead (see `bindSky`). A shader
    -- can sit uncompiled after a branch switch or a reload that rewrote no file.
    local fallbackSky = false
    local skyShaderRef: any = nil
    local shaderCheck: (() -> boolean)? = nil
    local function skyShaderCompiled(): boolean
        if shaderCheck then return shaderCheck() end
        if skyShaderRef == nil then skyShaderRef = asset.resolve("~.shaders.wck_sky", "shader") end
        local ok, st = pcall(function() return skyShaderRef:compileStatus() end)
        return ok and type(st) == "table" and st.status == "compiled"
    end
    
    --!desc Whether the sky is showing the engine's fallback (the kit's sky shader is not compiled yet).
    function Director.skyFallback(): boolean
        return fallbackSky
    end
    
    --!desc Tests only: replace the shader-compiled check (nil restores the real one).
    function Director._setShaderCheck(fn: (() -> boolean)?)
        shaderCheck = fn
    end
    
    local warnedFallback = false
    local lastEnvForSky: any = nil
    
    local function bindSky(env: any?)
        if hostId == nil then return end
        local v: any
        if skyShaderCompiled() then
            fallbackSky = false
            v = ecs.Sky { skyType = "material", materialName = Director.SKY_KEY }
        else
            if not warnedFallback then
                warnedFallback = true
                print("[worldClockKit] the sky shader is not compiled yet; showing the engine's sky in the kit's colours until it is")
            end
            fallbackSky = true
            local e = env or lastEnvForSky
            v = ecs.Sky {
                skyType = "procedural", syncSunToLight = false, autoCycle = false,
                timeOfDay = Clock.hour(),
                zenith = if e then e.sky.zenith else { 0.1, 0.3, 0.7 },
                horizon = if e then e.sky.horizon else { 0.6, 0.75, 0.95 },
                ground = if e then e.sky.ground else { 0.3, 0.28, 0.25 },
                starsIntensity = if e then e.palette.stars else 0,
            }
        end
        if ecs.has(hostId, ecs.Sky) then ecs.set(hostId, v) else ecs.insertSync(hostId, v) end
    end
    
    local function ensureSky()
        if skyReady then return end
        -- Reuse the record if it is already there (a hot reload of this module, a second attach):
        -- recreating it under the same key leaves the sky pass drawing the old copy.
        local okD, existing = pcall(renderer.material.describe, Director.SKY_KEY)
        if not okD or existing == nil then
            renderer.material.create({ name = Director.SKY_KEY, shader = skyShader(), properties = {}, textures = {} }, Director.SKY_KEY)
        end
        skyCache = {}
        skyReady = true
        bindSky()
    end
    
    local function rgba(c: { number }): { number } return { c[1], c[2], c[3], 1 } end
    
    -- Writes a sky property only when it moved, so a still sky costs nothing.
    local function skySet(k: string, prop: string, v: any)
        local p = skyCache[prop]
        if type(v) == "table" then
            if p ~= nil and math.abs(p[1] - v[1]) < 0.002 and math.abs(p[2] - v[2]) < 0.002
                and math.abs(p[3] - v[3]) < 0.002 and math.abs((p[4] or 0) - (v[4] or 0)) < 0.002 then return end
            skyCache[prop] = table.clone(v)
        else
            if p ~= nil and math.abs(p - v) < 0.0005 then return end
            skyCache[prop] = v
        end
        renderer.material.setProperty(k, prop, v)
    end
    
    local function pushSky(env: any)
        local st = env.style
        local k = Director.SKY_KEY
        local set = skySet
        set(k, "zenith_color", rgba(env.sky.zenith))
        set(k, "horizon_color", rgba(env.sky.horizon))
        set(k, "ground_color", rgba(env.sky.ground))
        set(k, "fog_color", rgba(env.fog.color))
        set(k, "sun_color", rgba(U.lerpRGB(env.palette.sun, { 1, 1, 1 }, 0.25)))
        set(k, "sun2_color", rgba(st.sun2Color))
        set(k, "moon_color", rgba(st.moonColor))
        set(k, "star_color", rgba(st.starColor))
        local cw = 1 - env.weather.darkness * 0.55
        -- clouds take the colour of the light on them: the horizon's glow (sunrise pink, sunset
        -- orange, night blue) until the sun is well up, their own white at full day; and they are
        -- only as bright as the sky around them, so a dawn sky never reads as a grey overcast day
        local dl = env.daylight
        local glowTint = U.lerpRGB(env.palette.horizon, env.palette.sun, 0.35)
        local cloudLit = U.lerpRGB(glowTint, st.cloudColor, dl ^ 1.5)
        local cloudCol = U.scaleRGB(cloudLit, cw * (0.1 + 0.9 * dl ^ 1.3) + 0.015)
        set(k, "cloud_color", rgba(cloudCol))
        set(k, "cloud_shade", rgba(U.scaleRGB(U.lerpRGB(env.sky.zenith, { 0.3, 0.32, 0.36 }, 0.5), cw * (0.08 + 0.92 * dl ^ 1.3) + 0.01)))
        set(k, "sun_dir", { env.sunDir[1], env.sunDir[2], env.sunDir[3], env.sunVis })
        local s2 = if st.sun2Vis ~= nil then st.sun2Vis else (st.sun2 or 0)
        set(k, "sun2_dir", { env.sun2Dir[1], env.sun2Dir[2], env.sun2Dir[3], s2 * U.smoothstep(-0.1, 0.02, env.sun2Dir[2]) })
        set(k, "moon_dir", { env.moonDir[1], env.moonDir[2], env.moonDir[3], Clock.moonPhase() })
        set(k, "sun_size", st.sunSize)
        set(k, "sun2_size", st.sun2Size)
        set(k, "moon_size", st.moonSize)
        set(k, "glow", st.glow)
        set(k, "horizon_glow", st.horizonGlow)
        set(k, "stars", env.palette.stars)
        set(k, "star_density", st.starDensity)
        set(k, "moon_vis", env.moonVis)
        set(k, "cloud_cover", env.sky.cover)
        set(k, "cloud_dark", env.weather.cloudDark)
        set(k, "cloud_soft", st.cloudSoft)
        set(k, "cloud_scale", st.cloudScale)
        set(k, "cloud_speed", 0.004 + env.weather.wind * 0.03)
        set(k, "haze", math.clamp(env.weather.fog * 0.9 + env.weather.sand * 0.3, 0, 1))
        set(k, "bands", st.bands)
        set(k, "pixel", st.pixel)
        set(k, "toon", st.toon)
        set(k, "flash", env.flash)
        set(k, "exposure", st.exposure)
    end
    
    --!desc Point the director at the host entity (the WorldClock's) and set up what it draws with.
    function Director.attach(id: string)
        hostId = id
        lastWritten = {}
        findLights()
        local cfg = State.config()
        if cfg.skyMode ~= "engine" and cfg.skyMode ~= "off" then
            ensureSky()
            bindSky()
        else
            engineSky = findEngineSky()
        end
        if cfg.precipitation ~= false then
            Precip.ensure(id)
            Precip.warm()
        end
        if cfg.lightningEnabled ~= false then
            Lightning.ensure(id)
            Lightning.warm()
        end
        Audio.setEnabled(cfg.sound ~= false)
    end
    
    function Director.detach()
        if hostId and ecs.has(hostId, ecs.Sky) then ecs.remove(hostId, ecs.Sky) end
        Precip.teardown()
        Lightning.teardown()
        Audio.silence()
        if ownSun and entity.exists(ownSun.id) then pcall(function() ownSun:despawn() end) end
        if ownAmb and entity.exists(ownAmb.id) then pcall(function() ownAmb:despawn() end) end
        ownSun, ownAmb, sunComp, ambComp = nil, nil, nil, nil
        if surfaceOn then SurfaceWeather.clear() surfaceOn = false end
        if fogOn then Fog.clear() fogOn = false end
        hostId = nil
        skyReady = false
    end
    
    local function camPos(): { number }
        local ok, p = pcall(function() return camera.viewData().position end)
        if ok and p then return { p.x, p.y, p.z } end
        return { 0, 2, 0 }
    end
    
    --!desc Write an environment to the engine.
    function Director.apply(env: any, cam: { number }?)
        local cfg = State.config()
        local c = cam or camPos()
        if cfg.drivesLighting ~= false then
            if sunComp == nil or ambComp == nil then findLights() end
            local okS = pcall(writeLight, sunComp, "sun", env.light.color, env.light.intensity, env.light.dir)
            local okA = pcall(writeLight, ambComp, "amb", env.ambient.color, env.ambient.intensity, nil)
            if not okS or not okA then findLights() end
        end
        if cfg.skyMode == "engine" then
            if engineSky == nil then engineSky = findEngineSky() end
            if engineSky and changed("engineTod", Clock.hour(), 0.02) then
                pcall(function() engineSky.timeOfDay = Clock.hour() end)
            end
        elseif cfg.skyMode ~= "off" then
            lastEnvForSky = env
            ensureSky()
            pushSky(env)
            reassert -= 1
            -- while falling back, check twice a second so the real sky takes over promptly
            if reassert <= 0 or (fallbackSky and reassert % 30 == 0) then
                if reassert <= 0 then reassert = 60 end
                local s = sky.get()
                if fallbackSky or s.material_name ~= Director.SKY_KEY or s.type ~= "material" then
                    bindSky(env)
                end
            end
        end
        -- fog
        if changed("fogd", env.fog.density, 0.0002) or changed("fogc", U.luma(env.fog.color), 0.004) then
            Fog.set({ density = env.fog.density, heightFalloff = 0.05, heightRef = 0, color = env.fog.color,
                inscatter = 0.4 * env.daylight, start = 2 })
            fogOn = true
        end
        -- wet ground and snow cover (the engine's surface weather)
        local wet, snowC = env.weather.wetness, env.weather.snowCover
        if wet > 0.01 or snowC > 0.01 then
            if changed("wet", wet, 0.01) or changed("snowc", snowC, 0.01) or not surfaceOn then
                SurfaceWeather.set({ wetness = wet, snow = snowC })
                surfaceOn = true
            end
        elseif surfaceOn then
            SurfaceWeather.clear()
            surfaceOn = false
            lastWritten.wet = nil
            lastWritten.snowc = nil
        end
        -- precipitation
        if cfg.precipitation ~= false then
            local seed = State.seed()
            local ang = U.hash(seed, 7) * math.pi * 2 + math.sin(env.t * 0.05) * 0.4
            local lit = math.clamp(0.35 + env.daylight * 0.65 + env.flash * 0.8, 0.3, 1.6)
            Precip.update(env.weather, c, lit, { math.cos(ang), math.sin(ang) })
        end
    end
    
    -- ─── tick ──────────────────────────────────────────────────────────────
    
    local lastEnv: any = nil
    local lampsOn = false
    
    --!desc The environment last applied (nil before the first frame).
    function Director.current(): any
        return lastEnv
    end
    
    --!desc Whether lamps should be lit now (light level under 0.35, with a little hysteresis).
    function Director.lampsShouldBeOn(): boolean
        return lampsOn
    end
    
    function Director.lampRule(level: number, wasOn: boolean): boolean
        if wasOn then return level < 0.4 end
        return level < 0.33
    end
    
    --!desc One frame: events, lightning, the environment, sound.
    local frameDts: { number } = {}
    local frameIdx = 0
    local FRAME_WINDOW = 300
    
    --!desc This machine's recent frame timing (the last ~300 frames the kit ticked):
    --!  `{ fps, avgMs, p95Ms, worstMs, samples }`. What `Probe` reports for each player.
    function Director.frameStats(): any
        local n = #frameDts
        if n == 0 then return { fps = 0, avgMs = 0, p95Ms = 0, worstMs = 0, samples = 0 } end
        local sum, sorted = 0, table.clone(frameDts)
        for _, d in frameDts do sum += d end
        table.sort(sorted)
        local avg = sum / n
        return {
            fps = if avg > 0 then 1 / avg else 0,
            avgMs = avg * 1000,
            p95Ms = sorted[math.max(1, math.ceil(n * 0.95))] * 1000,
            worstMs = sorted[n] * 1000,
            samples = n,
        }
    end
    
    function Director.tick(dt: number)
        if dt > 0 and dt < 2 then
            frameIdx = frameIdx % FRAME_WINDOW + 1
            frameDts[frameIdx] = dt
        end
        -- After a hot reload of this module its state starts empty while the WorldClock keeps
        -- ticking it: pick the host back up so the sky, lights and weather stay bound.
        if hostId == nil then
            local h = State.host()
            if h ~= nil and h.id then Director.attach(h.id()) end
        end
        Clock._step()
        local strikes = Weather._step()
        local now = State.now()
        local cam = camPos()
        for _, s in strikes do Lightning.strike(s, now, cam) end
        local thunder = Lightning.update(now)
        local cfg = State.config()
        for _, q in thunder do Audio.thunder(q.distance, q.strength) end
        local env = Director.evaluate(now, Lightning.flash())
        lastEnv = env
        lampsOn = Director.lampRule(env.lightLevel, lampsOn)
        Director.apply(env, cam)
        if cfg.sound ~= false then
            Audio.update(env.weather, 1 - env.daylight)
        end
    end
    
    -- ─── sky look ops ──────────────────────────────────────────────────────
    
    State.defineOp("setSky", function(a)
        if not Skies.has(a.name) then return end
        local sk = State.skyRec()
        local now = State.now()
        local from = sk.name
        local _, _, lw = lookBlend(now)
        if lw < 0.5 then from = sk.prevName or sk.name end
        State.write("sk", { name = a.name, prevName = from, from = nil, t0 = now, fade = math.max(0, a.fade or 3), rev = (sk.rev or 0) + 1 })
    end)
    
    local seenSkyRev: number? = nil
    Signals.on("timeSet", function() end)
    
    --!desc Fire "skyChanged" when the look record moves (any peer).
    function Director._skyStep()
        local sk = State.skyRec()
        if seenSkyRev ~= nil and sk.rev ~= seenSkyRev then
            Signals.emit("skyChanged", { from = sk.prevName, to = sk.name })
        end
        seenSkyRev = sk.rev
    end
    
    return Director
    >>>>>>> main (target)
    

9 files changed

  • Addeddeps/cc5dd9ee-b3ed-4e99-9458-cf787edc474b/versions/a2a59ccf31ccf7463abcdcb43fe82655a956bde53b3582e5e4c5385a6dfa95e5/soundstage.package/footsteps.moduleFolderAfter
  • Addeddeps/cc5dd9ee-b3ed-4e99-9458-cf787edc474b/versions/a2a59ccf31ccf7463abcdcb43fe82655a956bde53b3582e5e4c5385a6dfa95e5/soundstage.package/footsteps.module/init.luau24.2 KBAfter
  • AddedworldClockKit.packageFolderAfter
  • AddedworldClockKit.package/director.moduleFolderAfter
  • AddedworldClockKit.package/director.module/init.luau23.4 KBAfter
  • AddedworldClockKit.package/state.moduleFolderAfter
  • AddedworldClockKit.package/state.module/init.luau7.0 KBAfter
  • AddedworldClockKit.package/worldClockKitTests.testSuiteFolderAfter
  • AddedworldClockKit.package/worldClockKitTests.testSuite/init.luau38.3 KBAfter

Checks

No checks have been posted.

Reviews

No reviews yet.

Conversation

  1. claude-code @ auraAgentNov 7, 2026

    Added a second small fix to this pull request, in soundstage 2.1.3 footsteps.module: with everyPlayer on, each player's stride tracker was keyed by user id alone, so two avatars under one user id (two sessions of one account, or a second player spawned in the same session) shared one tracker; every frame it saw a different body, reset, and neither avatar ever stepped (0 steps in 8 s with two walkers). The tracker key now includes the avatar id; with it both walkers step again (32 steps in 8 s on the gravel trail). Players with different user ids are unaffected.

  2. claude-code @ auraAgentNov 7, 2026

    Third fix added, in worldClockKit's own test suite (worldClockKitTests): several tests hand the scene's WorldClock back in as the host and write to it (the precipitation and sky fallback tests set the weather, the strike test writes lightning). In edit mode the scene's autosave keeps what they wrote, so after a run the world could keep a weather and hour the tests left, and every later scene reload brought it back. The suite now keeps the scene clock's records (time anchor, weather, sky, lightning) from before the first test touches them and writes them back after every test. All 47 tests still pass.

  3. claude-code @ auraAgentNov 7, 2026

    Fourth fix, the real cause of the weather left behind after a check run: the worldClockKit test 'a non-owner's change goes to the owner' plays a guest and calls State.request('setWeather', rain). A guest's request goes out over multiplayer.send for real, so the test broadcast 'set rain' to every editor in the room; in edit mode each editor is the clock's authority and applied it to the scene's own WorldClock, and their change reached the scene's autosave overlay about 300 ms later, so the scene reopened in rain (also after a restart and for any editor opening the world). state.module gains a tests-only State._setSend(fn) beside _setNow; the test catches the request with it, now also checks the request it would have sent (channel, op, weather), and every test's restore clears it. The kit's runtime behaviour is unchanged. All 47 tests pass, and a run of the suite leaves the scene clock, its overlay and the other editors' clocks as they were.

Sign in to comment or review.