Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(light): inverse-square falloff; a bake falls light off as the frame does

yhh81245689b2bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0cecf8446..bbc68988e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ published separately; it ships inside the editor.
- **The sky lights the scene.** Sky Atmosphere's **Light the Scene** makes the sky the scene's environment: every Ambient light that names no environment of its own lights with it, its diffuse light from the dome and the clouds and its reflection on metal and wet ground, scaled by the light's colour and intensity as an imported one is. The sky is worked out again as it changes (the sun moving, a weather coming in, clouds drifting), at most once a second; with clouds that takes about 20 ms on a desktop. The sun's disc is left out, since the directional light the sky follows is its direct light. Below the horizon it is the ground, lit by the sky's sun and dome and giving back **Ground Albedo** of it (0.2 by default, between asphalt and grass; Unreal's atmosphere uses 0.4), so a wall in shadow takes the sunlit ground's bounce as well as the sky's: under a high clear sun that doubles its fill, under a low hazy one it adds little. Off by default, so a scene already lit by hand looks as it did.
- **Rooms stay dark under a sky that changes (sky occlusion).** With **Sky occlusion** on in the Lighting settings (`BakedLighting.skyOcclusion`), a probe bake keeps how much of the sky each probe sees instead of the sky itself: the probes hold the lights and their bounces, and the sky the frame has now (a live Sky Atmosphere, a weather, an environment) is added through what each probe sees of it, to the diffuse light and to the sky's reflection. A ball inside a roofed room measured 119 where the baked sky gave it 150, and a ball outside kept its light. A `.esprobes` baked this way carries `skyVisibility`; one without it lights as before. Probes are read per object, as Unity's light probes are: one large mesh spanning indoors and out takes one value.
+- **Lamps can fall off as real ones do.** A Point or Spot light's **Inverse Square** falls it off as 1/distance² in metres (the project's units per metre), with `intensity` the light one metre away and `radius` only where it is let go, eased out by glTF's and three.js's window — Unreal's Use Inverse Squared Falloff. A lamp pools under itself instead of washing a room evenly; point-inverse-square checks 0.5, 0.177 and 0.045 under, 1 m and 2 m from a lamp. glTF punctual lights import this way (candela over π, range scaled with the model).
- **A sky of your own lights the scene.** `defineSkyEffect({ type, label, glsl, wgsl, ... })` turns one function, the sky's radiance along a direction, into an effect a PostProcessVolume carries: drawn behind the scene and, with **Light the Scene** on, read back from the GPU as a small panorama about once a second and made the scene's environment, diffuse light and reflections, as Sky Atmosphere's is. A stylised sky lights the world with the light it shows, as an Unreal sky material does under a real-time Sky Light; the custom-sky gate checks that a ball under a blue-above, red-below sky is blue on top and red underneath on both backends. Effect textures can tile (`wrap: 'repeat'`).
- **Direct Lighting Only and Indirect Lighting Only view modes.** Beside Clay in the viewport's Show menu (and `Renderer.setViewShading(view, 'directLighting' | 'indirectLighting')`), as Unreal's lighting components: clay lit by the lights alone, or by everything that is not a light (ambient, sky, reflections, probes, bakes). The two add up to Clay, so a dark shadow says at once whether its fill is missing or merely weak.
- **A post-process pass can read an earlier pass of its own effect.** A texture param named `u_pass_<name>` is bound to the output of the sub-pass called `<name>`, which the chain keeps alive until it has been read, so an effect can be a pyramid (down, then up, adding each level back) and not only a line of passes.
@@ -44,6 +45,7 @@ published separately; it ships inside the editor.
### Fixed
+- **A bake falls light off as the frame does.** The lightmap and probe bake (TypeScript and the C++ kernel alike) took every point and spot light as (1 - d/r)²; the frame lights them linearly by default, with Inner Radius and Falloff, so a baked room disagreed with its own lamps. Both now use the frame's falloff, inverse-square included. Bakes made before read as out of date.
- **A mesh is lit by the probe volume it draws in, not the one its origin is in.** An imported level's meshes keep the origin the file gave them, often the world's centre, so a shed's walls were in no volume and took the open sky's light indoors. The volume is now chosen by the mesh's world box (its centre, else the smallest volume it overlaps), and per pixel each pixel reads the grid where it stands.
- **Rain does not fall through a glass roof.** The rain's map of what stands overhead took only what casts a shadow, so a see-through roof set to cast none — glass, as it usually is — left the floor under it wet. A see-through surface keeps rain off whether or not light passes it; what is opaque and casts no shadow (a held gun) still stays out. Gate: ssr-shelter-glass.
- **A character controller or a 3D collider added with its defaults is a real size.** Their defaults were metres (a 0.3 radius, a 0.5 box) under a world that reads centimetres unless told otherwise: a 3 mm character, a 5 mm crate. They are a 1.6 m person and a 1 m box now, in whatever units the project uses. Every example and template stated its sizes, so none changes.
diff --git a/build-tools/lightmap/lightmap-kernel.mjs b/build-tools/lightmap/lightmap-kernel.mjs
index 01b802790..a59a60aca 100644
--- a/build-tools/lightmap/lightmap-kernel.mjs
+++ b/build-tools/lightmap/lightmap-kernel.mjs
@@ -1,2 +1,2 @@
-async function Module(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var ENVIRONMENT_IS_PTHREAD=ENVIRONMENT_IS_WORKER&&globalThis.name=="em-pthread";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url);var worker_threads=require("node:worker_threads");globalThis.Worker=worker_threads.Worker;ENVIRONMENT_IS_WORKER=!worker_threads.isMainThread;ENVIRONMENT_IS_PTHREAD=ENVIRONMENT_IS_WORKER&&worker_threads.workerData=="em-pthread"}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}if(!ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var defaultPrint=console.log.bind(console);var defaultPrintErr=console.error.bind(console);if(ENVIRONMENT_IS_NODE){var utils=require("node:util");var stringify=a=>typeof a=="object"?utils.inspect(a):a;defaultPrint=(...args)=>fs.writeSync(1,args.map(stringify).join(" ")+"\n");defaultPrintErr=(...args)=>fs.writeSync(2,args.map(stringify).join(" ")+"\n")}var out=defaultPrint;var err=defaultPrintErr;var wasmBinary;var wasmModule;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}function growMemViews(){if(wasmMemory.buffer!=HEAP8.buffer){updateMemoryViews()}}var readyPromiseResolve,readyPromiseReject;if(ENVIRONMENT_IS_NODE&&ENVIRONMENT_IS_PTHREAD){globalThis.self=globalThis;var parentPort=worker_threads.parentPort;if(!globalThis.postMessage){parentPort.on("message",msg=>globalThis.onmessage?.({data:msg}));globalThis.postMessage=msg=>parentPort.postMessage(msg)}process.on("uncaughtException",err=>{postMessage({cmd:"uncaughtException",error:err});process.exit(1)})}var startWorker;if(ENVIRONMENT_IS_PTHREAD){var initializedJS=false;self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{var msgData=e["data"];var cmd=msgData.cmd;if(cmd==="load"){let messageQueue=[];self.onmessage=e=>messageQueue.push(e);startWorker=()=>{postMessage({cmd:"loaded"});for(let msg of messageQueue){handleMessage(msg)}self.onmessage=handleMessage};for(const handler of msgData.handlers){if(!Module[handler]||Module[handler].proxy){Module[handler]=(...args)=>{postMessage({cmd:"callHandler",handler,args})};if(handler=="print")out=Module[handler];if(handler=="printErr")err=Module[handler]}}wasmMemory=msgData.wasmMemory;updateMemoryViews();wasmModule=msgData.wasmModule;createWasm();run()}else if(cmd==="run"){establishStackSpace(msgData.pthread_ptr);__emscripten_thread_init(msgData.pthread_ptr,0,0,1,0,0);PThread.threadInitTLS();__emscripten_thread_mailbox_await(msgData.pthread_ptr);if(!initializedJS){initializedJS=true}try{invokeEntryPoint(msgData.start_routine,msgData.arg)}catch(ex){if(ex!="unwind"){throw ex}}}else if(msgData.target==="setimmediate"){}else if(cmd==="checkMailbox"){if(initializedJS){checkMailbox()}}else if(cmd){err(`worker: received unknown command ${cmd}`);err(msgData)}}catch(ex){__emscripten_thread_crashed();throw ex}}self.onmessage=handleMessage}var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function initMemory(){if(ENVIRONMENT_IS_PTHREAD){return}if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:65536,shared:true})}updateMemoryViews()}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(ENVIRONMENT_IS_PTHREAD)return startWorker();wasmExports["q"]()}function postRun(){if(ENVIRONMENT_IS_PTHREAD){return}if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("lightmap-kernel.wasm")}return new URL("lightmap-kernel.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){assignWasmImports();var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmExports=applySignatureConversions(wasmExports);registerTLSInit(wasmExports["B"]);assignWasmExports(wasmExports);wasmModule=module;return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"],result["module"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}if(ENVIRONMENT_IS_PTHREAD){var instance=new WebAssembly.Instance(wasmModule,getWasmImports());return receiveInstance(instance,wasmModule)}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;var terminateWorker=worker=>{worker.terminate();worker.onmessage=e=>{}};var cleanupThread=pthread_ptr=>{var worker=PThread.pthreads[pthread_ptr];PThread.returnWorkerToPool(worker)};var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var spawnThread=threadParams=>{var worker=PThread.getNewWorker();if(!worker){return 6}PThread.runningWorkers.push(worker);PThread.pthreads[threadParams.pthread_ptr]=worker;worker.pthread_ptr=threadParams.pthread_ptr;var msg={cmd:"run",start_routine:threadParams.startRoutine,arg:threadParams.arg,pthread_ptr:threadParams.pthread_ptr};if(ENVIRONMENT_IS_NODE){worker.unref()}worker.postMessage(msg,threadParams.transferList);return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var stackSave=()=>_emscripten_stack_get_current();var stackRestore=val=>__emscripten_stack_restore(val);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var proxyToMainThread=(funcIndex,emAsmAddr,proxyMode,...callArgs)=>{var bufSize=8*callArgs.length*2;var sp=stackSave();var args=stackAlloc(bufSize);var b=args>>>3;for(var arg of callArgs){if(typeof arg=="bigint"){(growMemViews(),HEAP64)[b++>>>0]=1n;(growMemViews(),HEAP64)[b++>>>0]=arg}else{(growMemViews(),HEAP64)[b++>>>0]=0n;(growMemViews(),HEAPF64)[b++>>>0]=arg}}var rtn=__emscripten_run_js_on_main_thread(funcIndex,emAsmAddr,bufSize,args,proxyMode);stackRestore(sp);return rtn};function _proc_exit(code){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(0,0,1,code);EXITSTATUS=code;if(!keepRuntimeAlive()){PThread.terminateAllThreads();Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))}function exitOnMainThread(returnCode){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(1,0,0,returnCode);_exit(returnCode)}var exitJS=(status,implicit)=>{EXITSTATUS=status;if(ENVIRONMENT_IS_PTHREAD){exitOnMainThread(status);throw"unwind"}_proc_exit(status)};var _exit=exitJS;var waitAsyncPolyfilled=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2])<91;var PThread={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){if(!ENVIRONMENT_IS_PTHREAD){PThread.initMainThread()}},initMainThread(){var pthreadPoolSize=typeof navigator!==undefined&&navigator.hardwareConcurrency||8;while(pthreadPoolSize--){PThread.allocateUnusedWorker()}addOnPreRun(async()=>{var pthreadPoolReady=PThread.loadWasmModuleToAllWorkers();addRunDependency("loading-workers");await pthreadPoolReady;removeRunDependency("loading-workers")})},terminateAllThreads:()=>{for(var worker of PThread.runningWorkers){terminateWorker(worker)}for(var worker of PThread.unusedWorkers){terminateWorker(worker)}PThread.unusedWorkers=[];PThread.runningWorkers=[];PThread.pthreads={}},terminateRuntime:()=>{PThread.terminateAllThreads();var pthread_ptr=_pthread_self();___set_thread_state(0,0,0,1);if(!waitAsyncPolyfilled){Atomics.notify((growMemViews(),HEAP32),pthread_ptr>>>2)}},returnWorkerToPool:worker=>{var pthread_ptr=worker.pthread_ptr;delete PThread.pthreads[pthread_ptr];PThread.unusedWorkers.push(worker);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker),1);worker.pthread_ptr=0;__emscripten_thread_free_data(pthread_ptr)},threadInitTLS(){PThread.tlsInitFunctions.forEach(f=>f())},loadWasmModuleToWorker:worker=>new Promise(onFinishedLoading=>{worker.onmessage=e=>{var d=e["data"];var cmd=d.cmd;if(d.targetThread&&d.targetThread!=_pthread_self()){var targetWorker=PThread.pthreads[d.targetThread];if(targetWorker){targetWorker.postMessage(d,d.transferList)}else{err(`worker sent message (${cmd}) to pthread (${d.targetThread}) that no longer exists`)}return}if(cmd==="checkMailbox"){checkMailbox()}else if(cmd==="spawnThread"){spawnThread(d)}else if(cmd==="cleanupThread"){callUserCallback(()=>cleanupThread(d.thread))}else if(cmd==="loaded"){worker.loaded=true;if(ENVIRONMENT_IS_NODE&&!worker.pthread_ptr){worker.unref()}onFinishedLoading(worker)}else if(d.target==="setimmediate"){worker.postMessage(d)}else if(cmd==="uncaughtException"){worker.onerror(d.error)}else if(cmd==="callHandler"){Module[d.handler](...d.args)}else if(cmd){err(`worker sent an unknown command ${cmd}`)}};worker.onerror=e=>{var message="worker sent an error!";err(`${message} ${e.filename}:${e.lineno}: ${e.message}`);throw e};if(ENVIRONMENT_IS_NODE){worker.on("message",data=>worker.onmessage({data}));worker.on("error",e=>worker.onerror(e))}var handlers=[];var knownHandlers=["onExit","onAbort","print","printErr"];for(var handler of knownHandlers){if(Module.propertyIsEnumerable(handler)){handlers.push(handler)}}worker.postMessage({cmd:"load",handlers,wasmMemory,wasmModule})}),async loadWasmModuleToAllWorkers(){if(ENVIRONMENT_IS_PTHREAD){return}let pthreadPoolReady=Promise.all(PThread.unusedWorkers.map(PThread.loadWasmModuleToWorker));return pthreadPoolReady},allocateUnusedWorker(){var worker;if(Module["mainScriptUrlOrBlob"]){var pthreadMainJs=Module["mainScriptUrlOrBlob"];if(typeof pthreadMainJs!="string"){pthreadMainJs=URL.createObjectURL(pthreadMainJs)}worker=new Worker(pthreadMainJs,{type:"module",workerData:"em-pthread",name:"em-pthread"})}else worker=new Worker(new URL("lightmap-kernel.mjs",import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});PThread.unusedWorkers.push(worker)},getNewWorker(){if(PThread.unusedWorkers.length==0){PThread.allocateUnusedWorker();PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0])}return PThread.unusedWorkers.pop()}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);function establishStackSpace(pthread_ptr){var stackHigh=(growMemViews(),HEAPU32)[pthread_ptr+48>>>2>>>0];var stackSize=(growMemViews(),HEAPU32)[pthread_ptr+52>>>2>>>0];var stackLow=stackHigh-stackSize;_emscripten_stack_set_limits(stackHigh,stackLow);stackRestore(stackHigh)}var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var invokeEntryPoint=(ptr,arg)=>{runtimeKeepaliveCounter=0;noExitRuntime=0;var result=getWasmTableEntry(ptr)(arg);function finish(result){if(keepRuntimeAlive()){EXITSTATUS=result;return}__emscripten_thread_exit(result)}finish(result)};var noExitRuntime=true;var registerTLSInit=tlsInitFunc=>PThread.tlsInitFunctions.push(tlsInitFunc);var wasmMemory;var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{idx>>>=0;var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.buffer instanceof ArrayBuffer?heapOrArray.subarray(idx,endPtr):heapOrArray.slice(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>{ptr>>>=0;return ptr?UTF8ArrayToString((growMemViews(),HEAPU8),ptr,maxBytesToRead,ignoreNul):""};function ___assert_fail(condition,filename,line,func){condition>>>=0;filename>>>=0;func>>>=0;return abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){(growMemViews(),HEAPU32)[this.ptr+4>>>2>>>0]=type}get_type(){return(growMemViews(),HEAPU32)[this.ptr+4>>>2>>>0]}set_destructor(destructor){(growMemViews(),HEAPU32)[this.ptr+8>>>2>>>0]=destructor}get_destructor(){return(growMemViews(),HEAPU32)[this.ptr+8>>>2>>>0]}set_caught(caught){caught=caught?1:0;(growMemViews(),HEAP8)[this.ptr+12>>>0]=caught}get_caught(){return(growMemViews(),HEAP8)[this.ptr+12>>>0]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;(growMemViews(),HEAP8)[this.ptr+13>>>0]=rethrown}get_rethrown(){return(growMemViews(),HEAP8)[this.ptr+13>>>0]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){(growMemViews(),HEAPU32)[this.ptr+16>>>2>>>0]=adjustedPtr}get_adjusted_ptr(){return(growMemViews(),HEAPU32)[this.ptr+16>>>2>>>0]}}var uncaughtExceptionCount=0;function ___cxa_throw(ptr,type,destructor){ptr>>>=0;type>>>=0;destructor>>>=0;var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;abort()}function pthreadCreateProxied(pthread_ptr,attr,startRoutine,arg){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(2,0,1,pthread_ptr,attr,startRoutine,arg);return ___pthread_create_js(pthread_ptr,attr,startRoutine,arg)}var _emscripten_has_threading_support=()=>!!globalThis.SharedArrayBuffer;function ___pthread_create_js(pthread_ptr,attr,startRoutine,arg){pthread_ptr>>>=0;attr>>>=0;startRoutine>>>=0;arg>>>=0;if(!_emscripten_has_threading_support()){return 6}var transferList=[];var error=0;if(ENVIRONMENT_IS_PTHREAD&&(transferList.length===0||error)){return pthreadCreateProxied(pthread_ptr,attr,startRoutine,arg)}if(error)return error;var threadParams={startRoutine,pthread_ptr,arg,transferList};if(ENVIRONMENT_IS_PTHREAD){threadParams.cmd="spawnThread";postMessage(threadParams,transferList);return 0}return spawnThread(threadParams)}var __abort_js=()=>abort("");function __emscripten_init_main_thread_js(tb){tb>>>=0;__emscripten_thread_init(tb,!ENVIRONMENT_IS_WORKER,1,!ENVIRONMENT_IS_WEB,1048576,false);PThread.threadInitTLS()}var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var maybeExit=()=>{if(!keepRuntimeAlive()){try{if(ENVIRONMENT_IS_PTHREAD){if(_pthread_self())__emscripten_thread_exit(EXITSTATUS);return}_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};function __emscripten_thread_mailbox_await(pthread_ptr){pthread_ptr>>>=0;if(!waitAsyncPolyfilled){var wait=Atomics.waitAsync((growMemViews(),HEAP32),pthread_ptr>>>2,pthread_ptr);wait.value.then(checkMailbox);var waitingAsync=pthread_ptr+120;Atomics.store((growMemViews(),HEAP32),waitingAsync>>>2,1)}}var checkMailbox=()=>{var pthread_ptr=_pthread_self();if(!pthread_ptr)return;callUserCallback(()=>{__emscripten_thread_mailbox_await(pthread_ptr);__emscripten_check_mailbox()})};function __emscripten_notify_mailbox_postmessage(targetThread,currThreadId){targetThread>>>=0;currThreadId>>>=0;if(targetThread==currThreadId){setTimeout(checkMailbox)}else if(ENVIRONMENT_IS_PTHREAD){postMessage({targetThread,cmd:"checkMailbox"})}else{var worker=PThread.pthreads[targetThread];if(!worker){return}worker.postMessage({cmd:"checkMailbox"})}}var proxiedJSCallArgs=[];function __emscripten_receive_on_main_thread_js(funcIndex,emAsmAddr,callingThread,bufSize,args,ctx,ctxArgs){emAsmAddr>>>=0;callingThread>>>=0;args>>>=0;ctx>>>=0;ctxArgs>>>=0;proxiedJSCallArgs.length=0;var b=args>>>3;var end=args+bufSize>>>3;while(b<end){var arg;if((growMemViews(),HEAP64)[b++>>>0]){arg=(growMemViews(),HEAP64)[b++>>>0]}else{arg=(growMemViews(),HEAPF64)[b++>>>0]}proxiedJSCallArgs.push(arg)}var func=proxiedFunctionTable[funcIndex];PThread.currentProxiedOperationCallerThread=callingThread;var rtn=func(...proxiedJSCallArgs);PThread.currentProxiedOperationCallerThread=0;if(ctx){rtn.then(rtn=>__emscripten_run_js_on_main_thread_done(ctx,ctxArgs,rtn));return}return rtn}function __emscripten_thread_cleanup(thread){thread>>>=0;if(!ENVIRONMENT_IS_PTHREAD)cleanupThread(thread);else postMessage({cmd:"cleanupThread",thread})}function __emscripten_thread_set_strongref(thread){thread>>>=0;if(ENVIRONMENT_IS_NODE){PThread.pthreads[thread].ref()}}var _emscripten_get_now=()=>performance.timeOrigin+performance.now();var _emscripten_check_blocking_allowed=()=>{};var runtimeKeepalivePush=()=>{runtimeKeepaliveCounter+=1};var _emscripten_exit_with_live_runtime=()=>{runtimeKeepalivePush();throw"unwind"};var getHeapMax=()=>4294901760;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};function _emscripten_resize_heap(requestedSize){requestedSize>>>=0;var oldSize=(growMemViews(),HEAPU8).length;if(requestedSize<=oldSize){return false}var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false}PThread.init();{initMemory();if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["wasmMemory"]=wasmMemory;var proxiedFunctionTable=[_proc_exit,exitOnMainThread,pthreadCreateProxied];var _free,_malloc,_lm_cache_budget,_lm_cache_bytes,_lm_gather_resolved,_lm_scene,_lm_direct,_lm_gather,_lm_texture_stats,__emscripten_tls_init,_pthread_self,__emscripten_thread_init,___set_thread_state,__emscripten_thread_crashed,__emscripten_run_js_on_main_thread_done,__emscripten_run_js_on_main_thread,__emscripten_thread_free_data,__emscripten_thread_exit,__emscripten_check_mailbox,_emscripten_stack_set_limits,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,__indirect_function_table,wasmTable;function assignWasmExports(wasmExports){_free=Module["_free"]=wasmExports["r"];_malloc=Module["_malloc"]=wasmExports["s"];_lm_cache_budget=Module["_lm_cache_budget"]=wasmExports["u"];_lm_cache_bytes=Module["_lm_cache_bytes"]=wasmExports["v"];_lm_gather_resolved=Module["_lm_gather_resolved"]=wasmExports["w"];_lm_scene=Module["_lm_scene"]=wasmExports["x"];_lm_direct=Module["_lm_direct"]=wasmExports["y"];_lm_gather=Module["_lm_gather"]=wasmExports["z"];_lm_texture_stats=Module["_lm_texture_stats"]=wasmExports["A"];__emscripten_tls_init=wasmExports["B"];_pthread_self=wasmExports["C"];__emscripten_thread_init=wasmExports["D"];___set_thread_state=wasmExports["E"];__emscripten_thread_crashed=wasmExports["F"];__emscripten_run_js_on_main_thread_done=wasmExports["G"];__emscripten_run_js_on_main_thread=wasmExports["H"];__emscripten_thread_free_data=wasmExports["I"];__emscripten_thread_exit=wasmExports["J"];__emscripten_check_mailbox=wasmExports["K"];_emscripten_stack_set_limits=wasmExports["L"];__emscripten_stack_restore=wasmExports["M"];__emscripten_stack_alloc=wasmExports["N"];_emscripten_stack_get_current=wasmExports["O"];__indirect_function_table=wasmTable=wasmExports["t"]}var wasmImports;function assignWasmImports(){wasmImports={b:___assert_fail,g:___cxa_throw,h:___pthread_create_js,m:__abort_js,l:__emscripten_init_main_thread_js,o:__emscripten_notify_mailbox_postmessage,c:__emscripten_receive_on_main_thread_js,f:__emscripten_thread_cleanup,k:__emscripten_thread_mailbox_await,j:__emscripten_thread_set_strongref,d:_emscripten_check_blocking_allowed,i:_emscripten_exit_with_live_runtime,e:_emscripten_get_now,n:_emscripten_resize_heap,p:_exit,a:wasmMemory}}function applySignatureConversions(wasmExports){wasmExports=Object.assign({},wasmExports);var makeWrapper_pp=f=>a0=>f(a0)>>>0;var makeWrapper_p=f=>()=>f()>>>0;wasmExports["s"]=makeWrapper_pp(wasmExports["s"]);wasmExports["C"]=makeWrapper_p(wasmExports["C"]);wasmExports["N"]=makeWrapper_pp(wasmExports["N"]);wasmExports["O"]=makeWrapper_p(wasmExports["O"]);return wasmExports}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}if(ENVIRONMENT_IS_PTHREAD){readyPromiseResolve?.(Module);initRuntime();return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;if(!ENVIRONMENT_IS_PTHREAD){wasmExports=await (createWasm());run()}if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
-;return moduleRtn}export default Module;var isPthread=globalThis.name=="em-pthread";var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("node:worker_threads")).workerData==="em-pthread";isPthread&&Module();
+async function Module(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var ENVIRONMENT_IS_PTHREAD=ENVIRONMENT_IS_WORKER&&self.name?.startsWith("em-pthread");if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url);var worker_threads=require("node:worker_threads");global.Worker=worker_threads.Worker;ENVIRONMENT_IS_WORKER=!worker_threads.isMainThread;ENVIRONMENT_IS_PTHREAD=ENVIRONMENT_IS_WORKER&&worker_threads["workerData"]=="em-pthread"}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}if(!ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var defaultPrint=console.log.bind(console);var defaultPrintErr=console.error.bind(console);if(ENVIRONMENT_IS_NODE){var utils=require("node:util");var stringify=a=>typeof a=="object"?utils.inspect(a):a;defaultPrint=(...args)=>fs.writeSync(1,args.map(stringify).join(" ")+"\n");defaultPrintErr=(...args)=>fs.writeSync(2,args.map(stringify).join(" ")+"\n")}var out=defaultPrint;var err=defaultPrintErr;var wasmBinary;var wasmModule;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");function growMemViews(){if(wasmMemory.buffer!=HEAP8.buffer){updateMemoryViews()}}var readyPromiseResolve,readyPromiseReject;if(ENVIRONMENT_IS_NODE&&ENVIRONMENT_IS_PTHREAD){globalThis.self=globalThis;var parentPort=worker_threads["parentPort"];if(!globalThis.postMessage){parentPort.on("message",msg=>globalThis.onmessage?.({data:msg}));globalThis.postMessage=msg=>parentPort["postMessage"](msg)}process.on("uncaughtException",err=>{postMessage({cmd:"uncaughtException",error:err});process.exit(1)})}var startWorker;if(ENVIRONMENT_IS_PTHREAD){var initializedJS=false;self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{var msgData=e["data"];var cmd=msgData.cmd;if(cmd==="load"){let messageQueue=[];self.onmessage=e=>messageQueue.push(e);startWorker=()=>{postMessage({cmd:"loaded"});for(let msg of messageQueue){handleMessage(msg)}self.onmessage=handleMessage};for(const handler of msgData.handlers){if(!Module[handler]||Module[handler].proxy){Module[handler]=(...args)=>{postMessage({cmd:"callHandler",handler,args})};if(handler=="print")out=Module[handler];if(handler=="printErr")err=Module[handler]}}wasmMemory=msgData.wasmMemory;updateMemoryViews();wasmModule=msgData.wasmModule;createWasm();run()}else if(cmd==="run"){establishStackSpace(msgData.pthread_ptr);__emscripten_thread_init(msgData.pthread_ptr,0,0,1,0,0);PThread.threadInitTLS();__emscripten_thread_mailbox_await(msgData.pthread_ptr);if(!initializedJS){initializedJS=true}try{invokeEntryPoint(msgData.start_routine,msgData.arg)}catch(ex){if(ex!="unwind"){throw ex}}}else if(msgData.target==="setimmediate"){}else if(cmd==="checkMailbox"){if(initializedJS){checkMailbox()}}else if(cmd){err(`worker: received unknown command ${cmd}`);err(msgData)}}catch(ex){__emscripten_thread_crashed();throw ex}}self.onmessage=handleMessage}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function initMemory(){if(ENVIRONMENT_IS_PTHREAD){return}if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:65536,shared:true})}updateMemoryViews()}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(ENVIRONMENT_IS_PTHREAD)return startWorker();wasmExports["r"]()}function postRun(){if(ENVIRONMENT_IS_PTHREAD){return}if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("lightmap-kernel.wasm")}return new URL("lightmap-kernel.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){assignWasmImports();var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmExports=applySignatureConversions(wasmExports);registerTLSInit(wasmExports["C"]);assignWasmExports(wasmExports);wasmModule=module;return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"],result["module"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}if(ENVIRONMENT_IS_PTHREAD){var instance=new WebAssembly.Instance(wasmModule,getWasmImports());return receiveInstance(instance,wasmModule)}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var terminateWorker=worker=>{worker.terminate();worker.onmessage=e=>{}};var cleanupThread=pthread_ptr=>{var worker=PThread.pthreads[pthread_ptr];PThread.returnWorkerToPool(worker)};var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var spawnThread=threadParams=>{var worker=PThread.getNewWorker();if(!worker){return 6}PThread.runningWorkers.push(worker);PThread.pthreads[threadParams.pthread_ptr]=worker;worker.pthread_ptr=threadParams.pthread_ptr;var msg={cmd:"run",start_routine:threadParams.startRoutine,arg:threadParams.arg,pthread_ptr:threadParams.pthread_ptr};if(ENVIRONMENT_IS_NODE){worker.unref()}worker.postMessage(msg,threadParams.transferList);return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var stackSave=()=>_emscripten_stack_get_current();var stackRestore=val=>__emscripten_stack_restore(val);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var proxyToMainThread=(funcIndex,emAsmAddr,proxyMode,...callArgs)=>{var bufSize=8*callArgs.length*2;var sp=stackSave();var args=stackAlloc(bufSize);var b=args>>>3;for(var arg of callArgs){if(typeof arg=="bigint"){(growMemViews(),HEAP64)[b++>>>0]=1n;(growMemViews(),HEAP64)[b++>>>0]=arg}else{(growMemViews(),HEAP64)[b++>>>0]=0n;(growMemViews(),HEAPF64)[b++>>>0]=arg}}var rtn=__emscripten_run_js_on_main_thread(funcIndex,emAsmAddr,bufSize,args,proxyMode);stackRestore(sp);return rtn};function _proc_exit(code){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(0,0,1,code);EXITSTATUS=code;if(!keepRuntimeAlive()){PThread.terminateAllThreads();Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))}function exitOnMainThread(returnCode){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(1,0,0,returnCode);_exit(returnCode)}var exitJS=(status,implicit)=>{EXITSTATUS=status;if(ENVIRONMENT_IS_PTHREAD){exitOnMainThread(status);throw"unwind"}_proc_exit(status)};var _exit=exitJS;var PThread={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){if(!ENVIRONMENT_IS_PTHREAD){PThread.initMainThread()}},initMainThread(){var pthreadPoolSize=typeof navigator!==undefined&&navigator.hardwareConcurrency||8;while(pthreadPoolSize--){PThread.allocateUnusedWorker()}addOnPreRun(async()=>{var pthreadPoolReady=PThread.loadWasmModuleToAllWorkers();addRunDependency("loading-workers");await pthreadPoolReady;removeRunDependency("loading-workers")})},terminateAllThreads:()=>{for(var worker of PThread.runningWorkers){terminateWorker(worker)}for(var worker of PThread.unusedWorkers){terminateWorker(worker)}PThread.unusedWorkers=[];PThread.runningWorkers=[];PThread.pthreads={}},returnWorkerToPool:worker=>{var pthread_ptr=worker.pthread_ptr;delete PThread.pthreads[pthread_ptr];PThread.unusedWorkers.push(worker);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker),1);worker.pthread_ptr=0;__emscripten_thread_free_data(pthread_ptr)},threadInitTLS(){PThread.tlsInitFunctions.forEach(f=>f())},loadWasmModuleToWorker:worker=>new Promise(onFinishedLoading=>{worker.onmessage=e=>{var d=e["data"];var cmd=d.cmd;if(d.targetThread&&d.targetThread!=_pthread_self()){var targetWorker=PThread.pthreads[d.targetThread];if(targetWorker){targetWorker.postMessage(d,d.transferList)}else{err(`Internal error! Worker sent a message "${cmd}" to target pthread ${d.targetThread}, but that thread no longer exists!`)}return}if(cmd==="checkMailbox"){checkMailbox()}else if(cmd==="spawnThread"){spawnThread(d)}else if(cmd==="cleanupThread"){callUserCallback(()=>cleanupThread(d.thread))}else if(cmd==="loaded"){worker.loaded=true;if(ENVIRONMENT_IS_NODE&&!worker.pthread_ptr){worker.unref()}onFinishedLoading(worker)}else if(d.target==="setimmediate"){worker.postMessage(d)}else if(cmd==="uncaughtException"){worker.onerror(d.error)}else if(cmd==="callHandler"){Module[d.handler](...d.args)}else if(cmd){err(`worker sent an unknown command ${cmd}`)}};worker.onerror=e=>{var message="worker sent an error!";err(`${message} ${e.filename}:${e.lineno}: ${e.message}`);throw e};if(ENVIRONMENT_IS_NODE){worker.on("message",data=>worker.onmessage({data}));worker.on("error",e=>worker.onerror(e))}var handlers=[];var knownHandlers=["onExit","onAbort","print","printErr"];for(var handler of knownHandlers){if(Module.propertyIsEnumerable(handler)){handlers.push(handler)}}worker.postMessage({cmd:"load",handlers,wasmMemory,wasmModule})}),async loadWasmModuleToAllWorkers(){if(ENVIRONMENT_IS_PTHREAD){return}let pthreadPoolReady=Promise.all(PThread.unusedWorkers.map(PThread.loadWasmModuleToWorker));return pthreadPoolReady},allocateUnusedWorker(){var worker;if(Module["mainScriptUrlOrBlob"]){var pthreadMainJs=Module["mainScriptUrlOrBlob"];if(typeof pthreadMainJs!="string"){pthreadMainJs=URL.createObjectURL(pthreadMainJs)}worker=new Worker(pthreadMainJs,{type:"module",workerData:"em-pthread",name:"em-pthread"})}else worker=new Worker(new URL("lightmap-kernel.mjs",import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});PThread.unusedWorkers.push(worker)},getNewWorker(){if(PThread.unusedWorkers.length==0){PThread.allocateUnusedWorker();PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0])}return PThread.unusedWorkers.pop()}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);function establishStackSpace(pthread_ptr){var stackHigh=(growMemViews(),HEAPU32)[pthread_ptr+52>>>2>>>0];var stackSize=(growMemViews(),HEAPU32)[pthread_ptr+56>>>2>>>0];var stackLow=stackHigh-stackSize;_emscripten_stack_set_limits(stackHigh,stackLow);stackRestore(stackHigh)}var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var invokeEntryPoint=(ptr,arg)=>{runtimeKeepaliveCounter=0;noExitRuntime=0;var result=getWasmTableEntry(ptr)(arg);function finish(result){if(keepRuntimeAlive()){EXITSTATUS=result;return}__emscripten_thread_exit(result)}finish(result)};var noExitRuntime=true;var registerTLSInit=tlsInitFunc=>PThread.tlsInitFunctions.push(tlsInitFunc);var wasmMemory;var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{idx>>>=0;var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.buffer instanceof ArrayBuffer?heapOrArray.subarray(idx,endPtr):heapOrArray.slice(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>{ptr>>>=0;return ptr?UTF8ArrayToString((growMemViews(),HEAPU8),ptr,maxBytesToRead,ignoreNul):""};function ___assert_fail(condition,filename,line,func){condition>>>=0;filename>>>=0;func>>>=0;return abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){(growMemViews(),HEAPU32)[this.ptr+4>>>2>>>0]=type}get_type(){return(growMemViews(),HEAPU32)[this.ptr+4>>>2>>>0]}set_destructor(destructor){(growMemViews(),HEAPU32)[this.ptr+8>>>2>>>0]=destructor}get_destructor(){return(growMemViews(),HEAPU32)[this.ptr+8>>>2>>>0]}set_caught(caught){caught=caught?1:0;(growMemViews(),HEAP8)[this.ptr+12>>>0]=caught}get_caught(){return(growMemViews(),HEAP8)[this.ptr+12>>>0]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;(growMemViews(),HEAP8)[this.ptr+13>>>0]=rethrown}get_rethrown(){return(growMemViews(),HEAP8)[this.ptr+13>>>0]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){(growMemViews(),HEAPU32)[this.ptr+16>>>2>>>0]=adjustedPtr}get_adjusted_ptr(){return(growMemViews(),HEAPU32)[this.ptr+16>>>2>>>0]}}var exceptionLast=0;var uncaughtExceptionCount=0;function ___cxa_throw(ptr,type,destructor){ptr>>>=0;type>>>=0;destructor>>>=0;var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast}function pthreadCreateProxied(pthread_ptr,attr,startRoutine,arg){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(2,0,1,pthread_ptr,attr,startRoutine,arg);return ___pthread_create_js(pthread_ptr,attr,startRoutine,arg)}var _emscripten_has_threading_support=()=>!!globalThis.SharedArrayBuffer;function ___pthread_create_js(pthread_ptr,attr,startRoutine,arg){pthread_ptr>>>=0;attr>>>=0;startRoutine>>>=0;arg>>>=0;if(!_emscripten_has_threading_support()){return 6}var transferList=[];var error=0;if(ENVIRONMENT_IS_PTHREAD&&(transferList.length===0||error)){return pthreadCreateProxied(pthread_ptr,attr,startRoutine,arg)}if(error)return error;var threadParams={startRoutine,pthread_ptr,arg,transferList};if(ENVIRONMENT_IS_PTHREAD){threadParams.cmd="spawnThread";postMessage(threadParams,transferList);return 0}return spawnThread(threadParams)}var __abort_js=()=>abort("");function __emscripten_init_main_thread_js(tb){tb>>>=0;__emscripten_thread_init(tb,!ENVIRONMENT_IS_WORKER,1,!ENVIRONMENT_IS_WEB,1048576,false);PThread.threadInitTLS()}var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var maybeExit=()=>{if(!keepRuntimeAlive()){try{if(ENVIRONMENT_IS_PTHREAD){if(_pthread_self())__emscripten_thread_exit(EXITSTATUS);return}_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var waitAsyncPolyfilled=!Atomics.waitAsync||globalThis.Deno||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2])<91;function __emscripten_thread_mailbox_await(pthread_ptr){pthread_ptr>>>=0;if(!waitAsyncPolyfilled){var wait=Atomics.waitAsync((growMemViews(),HEAP32),pthread_ptr>>>2,pthread_ptr);wait.value.then(checkMailbox);var waitingAsync=pthread_ptr+128;Atomics.store((growMemViews(),HEAP32),waitingAsync>>>2,1)}}var checkMailbox=()=>callUserCallback(()=>{var pthread_ptr=_pthread_self();if(pthread_ptr){__emscripten_thread_mailbox_await(pthread_ptr);__emscripten_check_mailbox()}});function __emscripten_notify_mailbox_postmessage(targetThread,currThreadId){targetThread>>>=0;currThreadId>>>=0;if(targetThread==currThreadId){setTimeout(checkMailbox)}else if(ENVIRONMENT_IS_PTHREAD){postMessage({targetThread,cmd:"checkMailbox"})}else{var worker=PThread.pthreads[targetThread];if(!worker){return}worker.postMessage({cmd:"checkMailbox"})}}var proxiedJSCallArgs=[];function __emscripten_receive_on_main_thread_js(funcIndex,emAsmAddr,callingThread,bufSize,args,ctx,ctxArgs){emAsmAddr>>>=0;callingThread>>>=0;args>>>=0;ctx>>>=0;ctxArgs>>>=0;proxiedJSCallArgs.length=0;var b=args>>>3;var end=args+bufSize>>>3;while(b<end){var arg;if((growMemViews(),HEAP64)[b++>>>0]){arg=(growMemViews(),HEAP64)[b++>>>0]}else{arg=(growMemViews(),HEAPF64)[b++>>>0]}proxiedJSCallArgs.push(arg)}var func=proxiedFunctionTable[funcIndex];PThread.currentProxiedOperationCallerThread=callingThread;var rtn=func(...proxiedJSCallArgs);PThread.currentProxiedOperationCallerThread=0;if(ctx){rtn.then(rtn=>__emscripten_run_js_on_main_thread_done(ctx,ctxArgs,rtn));return}return rtn}function __emscripten_thread_cleanup(thread){thread>>>=0;if(!ENVIRONMENT_IS_PTHREAD)cleanupThread(thread);else postMessage({cmd:"cleanupThread",thread})}function __emscripten_thread_set_strongref(thread){thread>>>=0;if(ENVIRONMENT_IS_NODE){PThread.pthreads[thread].ref()}}var _emscripten_get_now=()=>performance.timeOrigin+performance.now();var _emscripten_check_blocking_allowed=()=>{};var runtimeKeepalivePush=()=>{runtimeKeepaliveCounter+=1};var _emscripten_exit_with_live_runtime=()=>{runtimeKeepalivePush();throw"unwind"};var getHeapMax=()=>4294901760;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};function _emscripten_resize_heap(requestedSize){requestedSize>>>=0;var oldSize=(growMemViews(),HEAPU8).length;if(requestedSize<=oldSize){return false}var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};function _fd_write(fd,iov,iovcnt,pnum){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(3,0,1,fd,iov,iovcnt,pnum);iov>>>=0;iovcnt>>>=0;pnum>>>=0;var num=0;for(var i=0;i<iovcnt;i++){var ptr=(growMemViews(),HEAPU32)[iov>>>2>>>0];var len=(growMemViews(),HEAPU32)[iov+4>>>2>>>0];iov+=8;for(var j=0;j<len;j++){printChar(fd,(growMemViews(),HEAPU8)[ptr+j>>>0])}num+=len}(growMemViews(),HEAPU32)[pnum>>>2>>>0]=num;return 0}PThread.init();{initMemory();if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["wasmMemory"]=wasmMemory;var proxiedFunctionTable=[_proc_exit,exitOnMainThread,pthreadCreateProxied,_fd_write];var _free,_malloc,_lm_cache_budget,_lm_cache_bytes,_lm_gather_resolved,_lm_scene,_lm_direct,_lm_gather,_lm_texture_stats,__emscripten_tls_init,_pthread_self,__emscripten_thread_init,__emscripten_thread_crashed,__emscripten_run_js_on_main_thread_done,__emscripten_run_js_on_main_thread,__emscripten_thread_free_data,__emscripten_thread_exit,__emscripten_check_mailbox,_emscripten_stack_set_limits,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,__indirect_function_table,wasmTable;function assignWasmExports(wasmExports){_free=Module["_free"]=wasmExports["s"];_malloc=Module["_malloc"]=wasmExports["t"];_lm_cache_budget=Module["_lm_cache_budget"]=wasmExports["v"];_lm_cache_bytes=Module["_lm_cache_bytes"]=wasmExports["w"];_lm_gather_resolved=Module["_lm_gather_resolved"]=wasmExports["x"];_lm_scene=Module["_lm_scene"]=wasmExports["y"];_lm_direct=Module["_lm_direct"]=wasmExports["z"];_lm_gather=Module["_lm_gather"]=wasmExports["A"];_lm_texture_stats=Module["_lm_texture_stats"]=wasmExports["B"];__emscripten_tls_init=wasmExports["C"];_pthread_self=wasmExports["D"];__emscripten_thread_init=wasmExports["E"];__emscripten_thread_crashed=wasmExports["F"];__emscripten_run_js_on_main_thread_done=wasmExports["G"];__emscripten_run_js_on_main_thread=wasmExports["H"];__emscripten_thread_free_data=wasmExports["I"];__emscripten_thread_exit=wasmExports["J"];__emscripten_check_mailbox=wasmExports["K"];_emscripten_stack_set_limits=wasmExports["L"];__emscripten_stack_restore=wasmExports["M"];__emscripten_stack_alloc=wasmExports["N"];_emscripten_stack_get_current=wasmExports["O"];__indirect_function_table=wasmTable=wasmExports["u"]}var wasmImports;function assignWasmImports(){wasmImports={b:___assert_fail,h:___cxa_throw,i:___pthread_create_js,n:__abort_js,m:__emscripten_init_main_thread_js,p:__emscripten_notify_mailbox_postmessage,d:__emscripten_receive_on_main_thread_js,g:__emscripten_thread_cleanup,l:__emscripten_thread_mailbox_await,k:__emscripten_thread_set_strongref,e:_emscripten_check_blocking_allowed,j:_emscripten_exit_with_live_runtime,c:_emscripten_get_now,o:_emscripten_resize_heap,q:_exit,f:_fd_write,a:wasmMemory}}function applySignatureConversions(wasmExports){wasmExports=Object.assign({},wasmExports);var makeWrapper_pp=f=>a0=>f(a0)>>>0;var makeWrapper_p=f=>()=>f()>>>0;wasmExports["t"]=makeWrapper_pp(wasmExports["t"]);wasmExports["D"]=makeWrapper_p(wasmExports["D"]);wasmExports["N"]=makeWrapper_pp(wasmExports["N"]);wasmExports["O"]=makeWrapper_p(wasmExports["O"]);return wasmExports}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}if(ENVIRONMENT_IS_PTHREAD){readyPromiseResolve?.(Module);initRuntime();return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;if(!ENVIRONMENT_IS_PTHREAD){wasmExports=await (createWasm());run()}if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
+;return moduleRtn}export default Module;var isPthread=globalThis.self?.name?.startsWith("em-pthread");var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("node:worker_threads")).workerData==="em-pthread";isPthread&&Module();
diff --git a/build-tools/lightmap/lightmap-kernel.wasm b/build-tools/lightmap/lightmap-kernel.wasm
index ece4be569..7c091007d 100755
Binary files a/build-tools/lightmap/lightmap-kernel.wasm and b/build-tools/lightmap/lightmap-kernel.wasm differ
diff --git a/docs/astro/src/content/docs/graphics/lighting.mdx b/docs/astro/src/content/docs/graphics/lighting.mdx
index 4a9ee0d9f..ff35f6815 100644
--- a/docs/astro/src/content/docs/graphics/lighting.mdx
+++ b/docs/astro/src/content/docs/graphics/lighting.mdx
@@ -48,6 +48,7 @@ const addSun = defineSystem([Commands()], (cmds) => {
| `radius` | `200` | Falloff reach in world units (Point / Spot). |
| `innerRadius` | `0` | Radius held at full strength before the falloff starts (Point / Spot). |
| `falloff` | `1` | Falloff shape: `1` is linear, higher pools near the light, lower reaches further. |
+| `inverseSquare` | `false` | Fall off as 1/distance² in metres, as a real lamp does (Point / Spot). |
| `shadowStrength` | `1` | How much of this light its shadows remove; `0.6` leaves a shadow that is dark rather than black. |
| `cookie` | — | A texture whose **alpha** is this light's shape (Point / Spot). |
| `cookieSize` | `{0,0}` | How big the cookie is drawn, in world units; `0` covers the light's own reach. |
@@ -161,6 +162,24 @@ entity.insert(Light, {
Both default to the straight line, so a scene written before them renders exactly as it
did.
+### A real lamp: inverse-square falloff
+
+**`inverseSquare`** makes a Point or Spot light fall off as a real one does, as the
+inverse square of the distance — Unreal's *Use Inverse Squared Falloff*, and what a glTF
+or three.js point light is. `intensity` is then the light reaching a surface **one metre**
+away (the project's units per metre say what a metre is), four times dimmer at two metres,
+and `radius` is only where the light is let go: the last of it eases to nothing over the
+far end, by the same window glTF and three.js use. A lamp pools under itself instead of
+washing a room evenly. `innerRadius` and `falloff` do not apply.
+
+```ts
+// A shed lamp: as bright 1 m away as a sun of 3.
+entity.insert(Light, { type: LightType.Point, intensity: 3, radius: 13, inverseSquare: true });
+```
+
+A glTF's punctual lights import this way (candela over π, their range scaled with the
+model), and a bake falls light off the same way the frame does.
+
## Giving a light a shape
A light is a circle, or a cone. Real ones are neither: a lantern throws a ragged glow, a
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx
index 4f7009f67..3def89c02 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx
@@ -46,6 +46,7 @@ const addSun = defineSystem([Commands()], (cmds) => {
| `radius` | `200` | 衰减半径,世界单位(Point / Spot)。 |
| `innerRadius` | `0` | 衰减开始前保持满强度的半径(Point / Spot)。 |
| `falloff` | `1` | 衰减形状:`1` 为线性,更大则光集中在光源附近,更小则照得更远。 |
+| `inverseSquare` | `false` | 按距离(米)的平方反比衰减,和真实的灯一样(Point / Spot)。 |
| `shadowStrength` | `1` | 这盏灯的阴影能去掉多少光;`0.6` 让阴影暗而不黑。 |
| `cookie` | — | 一张纹理,它的 **alpha** 就是这盏灯的形状(Point / Spot)。 |
| `cookieSize` | `{0,0}` | cookie 绘制的大小,世界单位;`0` 覆盖灯自己的照射范围。 |
@@ -151,6 +152,21 @@ entity.insert(Light, {
两者默认都是那条直线,所以在它们出现之前写的场景渲染结果与以前完全一致。
+### 真实的灯:平方反比衰减
+
+**`inverseSquare`** 让 Point 或 Spot 灯像真实的灯一样,按距离的平方反比衰减——即虚幻的
+*Use Inverse Squared Falloff*,也是 glTF 和 three.js 点光源的行为。这时 `intensity` 是照到 **1 米**
+外表面的光(1 米是多少单位由项目的"每米单位数"决定),2 米外只剩四分之一;`radius` 只是光被放掉的地方:
+最后一段以 glTF 和 three.js 相同的窗口函数平滑收到零。灯下会形成光斑,而不是把整个房间均匀照亮。
+`innerRadius` 和 `falloff` 在这种模式下不起作用。
+
+```ts
+// 一盏棚灯:1 米外和强度 3 的太阳一样亮。
+entity.insert(Light, { type: LightType.Point, intensity: 3, radius: 13, inverseSquare: true });
+```
+
+glTF 的点光源导入时就是这种模式(坎德拉除以 π,作用距离随模型缩放);烘焙时的衰减也和运行时一致。
+
## 给灯一个形状
灯是一个圆,或者一个锥。真实的灯两者都不是:提灯投出参差的光晕,窗户投出一道光柱,火把以衰减曲线描述不
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index ab46a75c1..3e3258f9d 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -3554,6 +3554,12 @@
"doc": "Falloff shape: 1 = linear, higher pools near the light, lower reaches further.",
"range": "0–8"
},
+ {
+ "key": "inverseSquare",
+ "type": "boolean",
+ "default": "false",
+ "doc": "Fall off as 1/distance² in metres (a real lamp): intensity is the light 1 m away, radius only where it ends."
+ },
{
"key": "shadowStrength",
"type": "number",
diff --git a/fixtures/scenes/point-inverse-square.esscene b/fixtures/scenes/point-inverse-square.esscene
new file mode 100644
index 000000000..217c9fbdc
--- /dev/null
+++ b/fixtures/scenes/point-inverse-square.esscene
@@ -0,0 +1,116 @@
+{
+ "version": 4,
+ "name": "PointInverseSquare",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 400,
+ "z": 0
+ },
+ "rotation": {
+ "x": -0.7071067811865476,
+ "y": 0,
+ "z": 0,
+ "w": 0.7071067811865476
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 300,
+ "nearPlane": 1,
+ "farPlane": 2000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Floor",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 8,
+ "y": 0.1,
+ "z": 8
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Lamp",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 105,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 0,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "intensity": 0.5,
+ "radius": 600,
+ "inverseSquare": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/pipeline/src/assets/lightmapKernel.ts b/pipeline/src/assets/lightmapKernel.ts
index be4daae94..8a9f6abe7 100644
--- a/pipeline/src/assets/lightmapKernel.ts
+++ b/pipeline/src/assets/lightmapKernel.ts
@@ -23,8 +23,11 @@ export function packLights(lights: readonly BakeLight[]): Float64Array<ArrayBuff
const at = i * LIGHT_DOUBLES;
const p = l.position ?? [0, 0, 0];
const d = l.direction ?? [0, 0, -1];
+ // [10] the inner radius, [15] the ramp's power — or minus the world units in a metre for an inverse-square
+ // light (a power is never negative), as the frame packs it.
+ const shape = l.metre && l.metre > 0 ? -l.metre : Math.max(l.falloff ?? 1, 0);
out.set([LIGHT_KIND[l.kind], p[0], p[1], p[2], d[0], d[1], d[2], l.color[0], l.color[1], l.color[2],
- 0, l.intensity, l.radius ?? 0, l.innerCos ?? 0.9, l.outerCos ?? 0.7, 0], at);
+ Math.max(l.innerRadius ?? 0, 0), l.intensity, l.radius ?? 0, l.innerCos ?? 0.9, l.outerCos ?? 0.7, shape], at);
});
return out;
}
diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.ts
index a830ac361..6ad58116d 100644
--- a/pipeline/src/assets/modelImport.ts
+++ b/pipeline/src/assets/modelImport.ts
@@ -1015,13 +1015,19 @@ function transformComponent(trs?: Trs, scale?: number): ComponentData {
const UNBOUNDED_LIGHT_RANGE = 4096;
const LIGHT_TYPE = { point: 0, directional: 1, spot: 3 } as const;
-function lightComponent(light: ImportedLight): ComponentData {
+/**
+ * A KHR_lights_punctual light. A point or spot one is in candela and falls off as the inverse square of the distance, so
+ * it is an inverse-square Light at candela over pi (a Light's intensity is what reaches a surface over pi, the unit a
+ * directional one's is in); its range is in metres, so it is scaled with the model.
+ */
+function lightComponent(light: ImportedLight, scale = 1): ComponentData {
const [r, g, b] = light.color;
+ const positional = light.type !== 'directional';
return { type: 'Light', data: {
type: LIGHT_TYPE[light.type],
color: { r, g, b, a: 1 },
- intensity: light.intensity,
- ...(light.type === 'directional' ? {} : { radius: light.range ?? UNBOUNDED_LIGHT_RANGE }),
+ intensity: positional ? light.intensity / Math.PI : light.intensity,
+ ...(positional ? { radius: (light.range ?? UNBOUNDED_LIGHT_RANGE) * scale, inverseSquare: true } : {}),
...(light.type === 'spot' ? { innerAngle: light.innerAngle ?? 0, outerAngle: light.outerAngle ?? 90 } : {}),
} };
}
@@ -1150,7 +1156,7 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
...morphComponent(drawn[0])] : [];
const self = entity(id, node.name, parent, [
transformComponent(node, rootScale), ...own,
- ...(node.light ? [lightComponent(node.light)] : []),
+ ...(node.light ? [lightComponent(node.light, options.scale ?? 1)] : []),
...(node.camera ? [cameraComponent(node.camera)] : []),
...(node.visibility !== undefined ? [{ type: 'NodeVisibility', data: { visible: node.visibility } }] : []),
]);
diff --git a/pipeline/tests/gltf-import.test.ts b/pipeline/tests/gltf-import.test.ts
index 39e7c7c57..09f4d5780 100644
--- a/pipeline/tests/gltf-import.test.ts
+++ b/pipeline/tests/gltf-import.test.ts
@@ -1318,7 +1318,13 @@ describe('lights and cameras', () => {
const comp = (name: string, type: string) =>
prefab.entities.find((e) => e.name === name)!.components.find((c) => c.type === type)?.data;
expect(comp('Sun', 'Light')).toEqual({ type: 1, color: { r: 1, g: 0.9, b: 0.8, a: 1 }, intensity: 3 });
- expect(comp('Lamp', 'Light')).toMatchObject({ type: 3, intensity: 20, radius: 12 });
+ // A punctual lamp is in candela and falls off as 1/d²: an inverse-square Light at candela over pi, its range in metres.
+ expect(comp('Lamp', 'Light')).toMatchObject({ type: 3, radius: 12, inverseSquare: true });
+ expect((comp('Lamp', 'Light') as { intensity: number }).intensity).toBeCloseTo(20 / Math.PI);
+ // Imported into a centimetre project, the range is scaled with the model; the falloff measures in metres anyway.
+ const scaled = assembleModelPrefab('model', meshes, { nodes, scale: 100 });
+ expect(scaled.entities.find((e) => e.name === 'Lamp')!.components.find((c) => c.type === 'Light')!.data)
+ .toMatchObject({ radius: 1200, inverseSquare: true });
// A model's camera never takes over the scene it is dropped into.
expect(comp('Eye', 'Camera')).toMatchObject({ projectionType: 0, nearPlane: 0.05, farPlane: 200, isActive: false });
expect(comp('Plan', 'Camera')).toMatchObject({ projectionType: 1, orthoSize: 3 });
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 2287ca53e..89e8628a6 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -244,6 +244,7 @@ export interface NativeEngineApi {
renderer_setViewShading?(view: number, mode: number): void;
renderer_setViewSkinWeights?(view: number, entity: number, joint: number): void;
renderer_setViewport?(x: number, y: number, w: number, h: number): void;
+ renderer_setWorldUnitsPerMeter?(units: number): void;
renderer_setYSortLayers?(mask: number): void;
renderer_shadowStatus?(entity: number, outPtr: number): number;
renderer_snapshotMatchesCapture?(): boolean;
@@ -592,6 +593,7 @@ export function createNativeEngineApi(
bind('renderer_setViewShading', 'es_renderer_setViewShading', false);
bind('renderer_setViewSkinWeights', 'es_renderer_setViewSkinWeights', false);
bind('renderer_setViewport', 'es_renderer_setViewport', false);
+ bind('renderer_setWorldUnitsPerMeter', 'es_renderer_setWorldUnitsPerMeter', false);
bind('renderer_setYSortLayers', 'es_renderer_setYSortLayers', false);
bind('renderer_shadowStatus', 'es_renderer_shadowStatus', false);
bind('renderer_snapshotMatchesCapture', 'es_renderer_snapshotMatchesCapture', false);
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 959227c6c..15baf0e5b 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -932,6 +932,7 @@ export interface LightPtrData {
radius: number;
innerRadius: number;
falloff: number;
+ inverseSquare: boolean;
shadowStrength: number;
layerMin: number;
layerMax: number;
@@ -967,29 +968,30 @@ export function fillLight(
out.radius = f32[(ptr + 24) >> 2];
out.innerRadius = f32[(ptr + 28) >> 2];
out.falloff = f32[(ptr + 32) >> 2];
- out.shadowStrength = f32[(ptr + 36) >> 2];
- out.layerMin = u32[(ptr + 40) >> 2] | 0;
- out.layerMax = u32[(ptr + 44) >> 2] | 0;
- out.cookie = u32[(ptr + 48) >> 2];
- const cookieSize_ = out.cookieSize; cookieSize_.x = f32[(ptr + 52) >> 2]; cookieSize_.y = f32[((ptr + 52) >> 2) + 1];
- out.innerAngle = f32[(ptr + 60) >> 2];
- out.outerAngle = f32[(ptr + 64) >> 2];
- out.shadowSoftness = f32[(ptr + 68) >> 2];
- out.sourceAngle = f32[(ptr + 72) >> 2];
- out.shadowDistance = f32[(ptr + 76) >> 2];
- out.meshShadows = u8[ptr + 80] !== 0;
- out.shadowExtent = f32[(ptr + 84) >> 2];
- out.followEnvironmentSun = u8[ptr + 88] !== 0;
- out.aimFollowedSun = u8[ptr + 89] !== 0;
- out.environment = u32[(ptr + 92) >> 2];
- out.environmentRotation = f32[(ptr + 96) >> 2];
- out.drawEnvironment = u8[ptr + 100] !== 0;
- out.reflectionScale = f32[(ptr + 104) >> 2];
- out.reflectionSaturation = f32[(ptr + 108) >> 2];
- const bakedTint_ = out.bakedTint; bakedTint_.r = f32[(ptr + 112) >> 2]; bakedTint_.g = f32[((ptr + 112) >> 2) + 1]; bakedTint_.b = f32[((ptr + 112) >> 2) + 2]; bakedTint_.a = f32[((ptr + 112) >> 2) + 3];
- out.hemisphere = u8[ptr + 128] !== 0;
- const groundColor_ = out.groundColor; groundColor_.r = f32[(ptr + 132) >> 2]; groundColor_.g = f32[((ptr + 132) >> 2) + 1]; groundColor_.b = f32[((ptr + 132) >> 2) + 2]; groundColor_.a = f32[((ptr + 132) >> 2) + 3];
- out.enabled = u8[ptr + 148] !== 0;
+ out.inverseSquare = u8[ptr + 36] !== 0;
+ out.shadowStrength = f32[(ptr + 40) >> 2];
+ out.layerMin = u32[(ptr + 44) >> 2] | 0;
+ out.layerMax = u32[(ptr + 48) >> 2] | 0;
+ out.cookie = u32[(ptr + 52) >> 2];
+ const cookieSize_ = out.cookieSize; cookieSize_.x = f32[(ptr + 56) >> 2]; cookieSize_.y = f32[((ptr + 56) >> 2) + 1];
+ out.innerAngle = f32[(ptr + 64) >> 2];
+ out.outerAngle = f32[(ptr + 68) >> 2];
+ out.shadowSoftness = f32[(ptr + 72) >> 2];
+ out.sourceAngle = f32[(ptr + 76) >> 2];
+ out.shadowDistance = f32[(ptr + 80) >> 2];
+ out.meshShadows = u8[ptr + 84] !== 0;
+ out.shadowExtent = f32[(ptr + 88) >> 2];
+ out.followEnvironmentSun = u8[ptr + 92] !== 0;
+ out.aimFollowedSun = u8[ptr + 93] !== 0;
+ out.environment = u32[(ptr + 96) >> 2];
+ out.environmentRotation = f32[(ptr + 100) >> 2];
+ out.drawEnvironment = u8[ptr + 104] !== 0;
+ out.reflectionScale = f32[(ptr + 108) >> 2];
+ out.reflectionSaturation = f32[(ptr + 112) >> 2];
+ const bakedTint_ = out.bakedTint; bakedTint_.r = f32[(ptr + 116) >> 2]; bakedTint_.g = f32[((ptr + 116) >> 2) + 1]; bakedTint_.b = f32[((ptr + 116) >> 2) + 2]; bakedTint_.a = f32[((ptr + 116) >> 2) + 3];
+ out.hemisphere = u8[ptr + 132] !== 0;
+ const groundColor_ = out.groundColor; groundColor_.r = f32[(ptr + 136) >> 2]; groundColor_.g = f32[((ptr + 136) >> 2) + 1]; groundColor_.b = f32[((ptr + 136) >> 2) + 2]; groundColor_.a = f32[((ptr + 136) >> 2) + 3];
+ out.enabled = u8[ptr + 152] !== 0;
}
export function writeLight(
@@ -1002,29 +1004,30 @@ export function writeLight(
f32[(ptr + 24) >> 2] = data.radius;
f32[(ptr + 28) >> 2] = data.innerRadius;
f32[(ptr + 32) >> 2] = data.falloff;
- f32[(ptr + 36) >> 2] = data.shadowStrength;
- u32[(ptr + 40) >> 2] = data.layerMin | 0;
- u32[(ptr + 44) >> 2] = data.layerMax | 0;
- u32[(ptr + 48) >> 2] = data.cookie;
- f32[(ptr + 52) >> 2] = data.cookieSize.x; f32[((ptr + 52) >> 2) + 1] = data.cookieSize.y;
- f32[(ptr + 60) >> 2] = data.innerAngle;
- f32[(ptr + 64) >> 2] = data.outerAngle;
- f32[(ptr + 68) >> 2] = data.shadowSoftness;
- f32[(ptr + 72) >> 2] = data.sourceAngle;
- f32[(ptr + 76) >> 2] = data.shadowDistance;
- u8[ptr + 80] = data.meshShadows ? 1 : 0;
- f32[(ptr + 84) >> 2] = data.shadowExtent;
- u8[ptr + 88] = data.followEnvironmentSun ? 1 : 0;
- u8[ptr + 89] = data.aimFollowedSun ? 1 : 0;
- u32[(ptr + 92) >> 2] = data.environment;
- f32[(ptr + 96) >> 2] = data.environmentRotation;
- u8[ptr + 100] = data.drawEnvironment ? 1 : 0;
- f32[(ptr + 104) >> 2] = data.reflectionScale;
- f32[(ptr + 108) >> 2] = data.reflectionSaturation;
- f32[(ptr + 112) >> 2] = data.bakedTint.r; f32[((ptr + 112) >> 2) + 1] = data.bakedTint.g; f32[((ptr + 112) >> 2) + 2] = data.bakedTint.b; f32[((ptr + 112) >> 2) + 3] = data.bakedTint.a;
- u8[ptr + 128] = data.hemisphere ? 1 : 0;
- f32[(ptr + 132) >> 2] = data.groundColor.r; f32[((ptr + 132) >> 2) + 1] = data.groundColor.g; f32[((ptr + 132) >> 2) + 2] = data.groundColor.b; f32[((ptr + 132) >> 2) + 3] = data.groundColor.a;
- u8[ptr + 148] = data.enabled ? 1 : 0;
+ u8[ptr + 36] = data.inverseSquare ? 1 : 0;
+ f32[(ptr + 40) >> 2] = data.shadowStrength;
+ u32[(ptr + 44) >> 2] = data.layerMin | 0;
+ u32[(ptr + 48) >> 2] = data.layerMax | 0;
+ u32[(ptr + 52) >> 2] = data.cookie;
+ f32[(ptr + 56) >> 2] = data.cookieSize.x; f32[((ptr + 56) >> 2) + 1] = data.cookieSize.y;
+ f32[(ptr + 64) >> 2] = data.innerAngle;
+ f32[(ptr + 68) >> 2] = data.outerAngle;
+ f32[(ptr + 72) >> 2] = data.shadowSoftness;
+ f32[(ptr + 76) >> 2] = data.sourceAngle;
+ f32[(ptr + 80) >> 2] = data.shadowDistance;
+ u8[ptr + 84] = data.meshShadows ? 1 : 0;
+ f32[(ptr + 88) >> 2] = data.shadowExtent;
+ u8[ptr + 92] = data.followEnvironmentSun ? 1 : 0;
+ u8[ptr + 93] = data.aimFollowedSun ? 1 : 0;
+ u32[(ptr + 96) >> 2] = data.environment;
+ f32[(ptr + 100) >> 2] = data.environmentRotation;
+ u8[ptr + 104] = data.drawEnvironment ? 1 : 0;
+ f32[(ptr + 108) >> 2] = data.reflectionScale;
+ f32[(ptr + 112) >> 2] = data.reflectionSaturation;
+ f32[(ptr + 116) >> 2] = data.bakedTint.r; f32[((ptr + 116) >> 2) + 1] = data.bakedTint.g; f32[((ptr + 116) >> 2) + 2] = data.bakedTint.b; f32[((ptr + 116) >> 2) + 3] = data.bakedTint.a;
+ u8[ptr + 132] = data.hemisphere ? 1 : 0;
+ f32[(ptr + 136) >> 2] = data.groundColor.r; f32[((ptr + 136) >> 2) + 1] = data.groundColor.g; f32[((ptr + 136) >> 2) + 2] = data.groundColor.b; f32[((ptr + 136) >> 2) + 3] = data.groundColor.a;
+ u8[ptr + 152] = data.enabled ? 1 : 0;
}
export function createLightData(): LightPtrData {
@@ -1035,6 +1038,7 @@ export function createLightData(): LightPtrData {
radius: 0,
innerRadius: 0,
falloff: 0,
+ inverseSquare: false,
shadowStrength: 0,
layerMin: 0,
layerMax: 0,
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 0d277caf7..7e80cad9c 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BillboardMode, BodyType, Canv
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '5e943b68bf754ab0';
+export const ABI_LAYOUT_HASH = '04486d0b29ae33ae';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -526,6 +526,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
radius: 200,
innerRadius: 0,
falloff: 1,
+ inverseSquare: false,
shadowStrength: 1,
layerMin: -128,
layerMax: 127,
@@ -561,6 +562,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
radius: { min: 0, tooltip: "Falloff reach in world units (Point / Spot).", shownWhen: { field: "type", values: [0, 3] } },
innerRadius: { min: 0, tooltip: "Radius held at full strength before the falloff starts.", shownWhen: { field: "type", values: [0, 3] } },
falloff: { min: 0, max: 8, tooltip: "Falloff shape: 1 = linear, higher pools near the light, lower reaches further.", shownWhen: { field: "type", values: [0, 3] } },
+ inverseSquare: { tooltip: "Fall off as 1/distance² in metres (a real lamp): intensity is the light 1 m away, radius only where it ends.", shownWhen: { field: "type", values: [0, 3] } },
shadowStrength: { min: 0, max: 1, slider: true, tooltip: "How much of this light its shadows remove (1 = all of it).", shownWhen: { field: "type", values: [0, 1, 3] } },
layerMin: { min: -128, max: 127, step: 1, tooltip: "The lowest sprite layer this light reaches (default: every layer).", shownWhen: { field: "type", values: [0, 1, 3] } },
layerMax: { min: -128, max: 127, step: 1, tooltip: "The highest sprite layer this light reaches (default: every layer).", shownWhen: { field: "type", values: [0, 1, 3] } },
@@ -1728,6 +1730,7 @@ export interface LightData {
radius: number;
innerRadius: number;
falloff: number;
+ inverseSquare: boolean;
shadowStrength: number;
layerMin?: number;
layerMax?: number;
diff --git a/sdk/src/ecs/worldUnits.ts b/sdk/src/ecs/worldUnits.ts
index 395ea94fe..e38d55cda 100644
--- a/sdk/src/ecs/worldUnits.ts
+++ b/sdk/src/ecs/worldUnits.ts
@@ -20,6 +20,14 @@ export const REFERENCE_UNITS_PER_METER = 100;
let unitsPerMeter = REFERENCE_UNITS_PER_METER;
let epoch = 0;
+const listeners = new Set<(unitsPerMeter: number) => void>();
+
+/** Calls `fn` now and on every change: how the renderer learns what a metre is (inverse-square lights measure in it). */
+export function onWorldUnitsPerMeter(fn: (unitsPerMeter: number) => void): () => void {
+ listeners.add(fn);
+ fn(unitsPerMeter);
+ return () => listeners.delete(fn);
+}
/**
* Set the project's units per metre. Called before a scene loads (by the runtime from the project's config, by the
@@ -30,6 +38,7 @@ export function setWorldUnitsPerMeter(value: number): void {
if (v === unitsPerMeter) return;
unitsPerMeter = v;
epoch++;
+ for (const fn of listeners) fn(v);
}
/** The project's units per metre. */
diff --git a/sdk/src/lightmap/fingerprint.ts b/sdk/src/lightmap/fingerprint.ts
index 5800b6eb9..5fe1efef1 100644
--- a/sdk/src/lightmap/fingerprint.ts
+++ b/sdk/src/lightmap/fingerprint.ts
@@ -79,6 +79,7 @@ export function bakeFingerprint(inputs: BakeInputs): string {
for (const l of inputs.lights) {
lines.push(`l|${l.kind}|${nums(l.position)}|${nums(l.direction)}|${nums(l.color)}`
+ `|${num(l.intensity)}|${num(l.radius)}|${num(l.innerCos)}|${num(l.outerCos)}`
+ + `|${num(l.innerRadius)}|${num(l.falloff)}|${num(l.metre)}`
+ `${l.followsEnvironmentSun ? '|sun' : ''}`);
}
for (const v of inputs.volumes) {
diff --git a/sdk/src/lightmap/lights.ts b/sdk/src/lightmap/lights.ts
index 2ec67071c..e46fc50cf 100644
--- a/sdk/src/lightmap/lights.ts
+++ b/sdk/src/lightmap/lights.ts
@@ -13,6 +13,7 @@
import { LightType } from '../wasm/wasm.generated';
import { COMPONENT_META } from './metaAccess';
import type { BakeLight } from './solve';
+import { worldUnitsPerMeter } from '../ecs/worldUnits';
/** A Light's authored fields, as loosely as a document may state them. */
export interface AuthoredLight {
@@ -20,6 +21,9 @@ export interface AuthoredLight {
color?: { r?: number; g?: number; b?: number };
intensity?: number;
radius?: number;
+ innerRadius?: number;
+ falloff?: number;
+ inverseSquare?: boolean;
innerAngle?: number;
outerAngle?: number;
followEnvironmentSun?: boolean;
@@ -77,6 +81,10 @@ export function bakeLightOf(authored: AuthoredLight | undefined,
color: rgb,
intensity,
radius: kind === 'directional' ? undefined : (v.radius ?? 200),
+ // How it ends, as the frame lights it: the bake must agree, or a lamp lights its room twice over.
+ ...(kind === 'directional' ? {} : v.inverseSquare
+ ? { metre: worldUnitsPerMeter() }
+ : { innerRadius: v.innerRadius ?? 0, falloff: v.falloff ?? 1 }),
innerCos: cos(v.innerAngle ?? 30),
outerCos: cos(v.outerAngle ?? 45),
...(kind === 'directional' && v.followEnvironmentSun ? { followsEnvironmentSun: true } : {}),
diff --git a/sdk/src/lightmap/solve.ts b/sdk/src/lightmap/solve.ts
index 6ca8c1acf..66423a8f0 100644
--- a/sdk/src/lightmap/solve.ts
+++ b/sdk/src/lightmap/solve.ts
@@ -25,6 +25,12 @@ export interface BakeLight {
intensity: number;
/** Reach, in world units. Past it a point or spot light contributes nothing. */
radius?: number;
+ /** How the light ends, as the frame lights it (distanceFalloff): held at full out to `innerRadius`, then ramped to
+ * `radius` raised to `falloff` (1 = linear) — or, with `metre` set, 1/d² in metres (`metre` world units to one)
+ * let go over the reach by (1 - (d/r)^4)^2. A bake that disagreed with the frame lit a lamp's room twice over. */
+ innerRadius?: number;
+ falloff?: number;
+ metre?: number;
/** Cosines of the half angles a spot falls off between. */
innerCos?: number;
outerCos?: number;
@@ -33,6 +39,22 @@ export interface BakeLight {
followsEnvironmentSun?: boolean;
}
+/** How much of a point or spot light reaches `distance` away: the frame's distanceFalloff, so a bake and the frame agree. */
+export function lightFalloff(distance: number, light: BakeLight): number {
+ const radius = light.radius ?? 0;
+ if (radius > 0 && distance >= radius) return 0;
+ if (light.metre && light.metre > 0) {
+ const m = distance / light.metre;
+ const q = radius > 0 ? distance / radius : 0;
+ const w = Math.min(Math.max(1 - q * q * q * q, 0), 1);
+ return (w * w) / Math.max(m * m, 0.01);
+ }
+ if (!(radius > 0)) return 1;
+ const inner = Math.max(light.innerRadius ?? 0, 0);
+ const ramp = Math.min(Math.max((radius - distance) / Math.max(radius - inner, 1e-4), 0), 1);
+ return Math.pow(ramp, Math.max(light.falloff ?? 1, 1e-3));
+}
+
/** Where a ray that hit triangle `t` lands in the atlas, and what it reflects. */
export interface HitLookup {
/** UV of each triangle's three corners, six floats each. */
@@ -175,12 +197,8 @@ export function solveDirect(lumels: LumelField, bvh: Bvh, lookup: HitLookup,
distance = Math.hypot(lx, ly, lz);
if (distance < 1e-6) continue;
lx /= distance; ly /= distance; lz /= distance;
- const radius = light.radius ?? 0;
- if (radius > 0) {
- if (distance >= radius) continue;
- const k = 1 - distance / radius;
- falloff = k * k;
- }
+ falloff = lightFalloff(distance, light);
+ if (falloff <= 0) continue;
if (light.kind === 'spot') {
const d = light.direction ?? [0, 0, -1];
const len = Math.hypot(d[0], d[1], d[2]) || 1;
diff --git a/sdk/src/render/renderer.ts b/sdk/src/render/renderer.ts
index b259ff1b4..9d3325912 100644
--- a/sdk/src/render/renderer.ts
+++ b/sdk/src/render/renderer.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { onWorldUnitsPerMeter } from '../ecs/worldUnits';
import type { ESEngineModule, CppRegistry } from '../wasm';
import { CoreApiBridge } from '../wasm/CoreApiBridge';
import { handleWasmError } from '../wasm/wasmError';
@@ -529,7 +530,14 @@ function installContextLossGuard(m: ESEngineModule): void {
}
/** @internal Wired by the engine plugins — not part of the public API. */
+let unitsSubscription: (() => void) | null = null;
+
export function initRendererAPI(wasmModule: ESEngineModule): void {
+ // The frame measures inverse-square lights in metres: it is told what one is, now and whenever the project says.
+ unitsSubscription?.();
+ unitsSubscription = onWorldUnitsPerMeter((units) => {
+ (wasmModule as unknown as { renderer_setWorldUnitsPerMeter?(u: number): void }).renderer_setWorldUnitsPerMeter?.(units);
+ });
bridge.connect(wasmModule);
module = bridge.module;
installContextLossGuard(module);
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index fe3b9a439..16c9b5cfc 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -559,6 +559,7 @@ export interface ESEngineModule {
postprocess_setPassScale(name: string, scale: number): void;
postprocess_setPassContinuesEffect(name: string): void;
postprocess_requestSkyCapture?(passName: string, width: number, height: number): void;
+ renderer_setWorldUnitsPerMeter?(units: number): void;
postprocess_pollSkyCapture?(): number;
postprocess_takeSkyCapture?(dst: number, bytes: number): boolean;
postprocess_setMsaaSamples(samples: number): void;
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index d0b7db61a..5dc860023 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -265,29 +265,30 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'radius', type: 'f32', offset: 24 },
{ name: 'innerRadius', type: 'f32', offset: 28 },
{ name: 'falloff', type: 'f32', offset: 32 },
- { name: 'shadowStrength', type: 'f32', offset: 36 },
- { name: 'layerMin', type: 'i32', offset: 40 },
- { name: 'layerMax', type: 'i32', offset: 44 },
- { name: 'cookie', type: 'u32', offset: 48 },
- { name: 'cookieSize', type: 'vec2', offset: 52 },
- { name: 'innerAngle', type: 'f32', offset: 60 },
- { name: 'outerAngle', type: 'f32', offset: 64 },
- { name: 'shadowSoftness', type: 'f32', offset: 68 },
- { name: 'sourceAngle', type: 'f32', offset: 72 },
- { name: 'shadowDistance', type: 'f32', offset: 76 },
- { name: 'meshShadows', type: 'bool', offset: 80 },
- { name: 'shadowExtent', type: 'f32', offset: 84 },
- { name: 'followEnvironmentSun', type: 'bool', offset: 88 },
- { name: 'aimFollowedSun', type: 'bool', offset: 89 },
- { name: 'environment', type: 'u32', offset: 92 },
- { name: 'environmentRotation', type: 'f32', offset: 96 },
- { name: 'drawEnvironment', type: 'bool', offset: 100 },
- { name: 'reflectionScale', type: 'f32', offset: 104 },
- { name: 'reflectionSaturation', type: 'f32', offset: 108 },
- { name: 'bakedTint', type: 'color', offset: 112 },
- { name: 'hemisphere', type: 'bool', offset: 128 },
- { name: 'groundColor', type: 'color', offset: 132 },
- { name: 'enabled', type: 'bool', offset: 148 },
+ { name: 'inverseSquare', type: 'bool', offset: 36 },
+ { name: 'shadowStrength', type: 'f32', offset: 40 },
+ { name: 'layerMin', type: 'i32', offset: 44 },
+ { name: 'layerMax', type: 'i32', offset: 48 },
+ { name: 'cookie', type: 'u32', offset: 52 },
+ { name: 'cookieSize', type: 'vec2', offset: 56 },
+ { name: 'innerAngle', type: 'f32', offset: 64 },
+ { name: 'outerAngle', type: 'f32', offset: 68 },
+ { name: 'shadowSoftness', type: 'f32', offset: 72 },
+ { name: 'sourceAngle', type: 'f32', offset: 76 },
+ { name: 'shadowDistance', type: 'f32', offset: 80 },
+ { name: 'meshShadows', type: 'bool', offset: 84 },
+ { name: 'shadowExtent', type: 'f32', offset: 88 },
+ { name: 'followEnvironmentSun', type: 'bool', offset: 92 },
+ { name: 'aimFollowedSun', type: 'bool', offset: 93 },
+ { name: 'environment', type: 'u32', offset: 96 },
+ { name: 'environmentRotation', type: 'f32', offset: 100 },
+ { name: 'drawEnvironment', type: 'bool', offset: 104 },
+ { name: 'reflectionScale', type: 'f32', offset: 108 },
+ { name: 'reflectionSaturation', type: 'f32', offset: 112 },
+ { name: 'bakedTint', type: 'color', offset: 116 },
+ { name: 'hemisphere', type: 'bool', offset: 132 },
+ { name: 'groundColor', type: 'color', offset: 136 },
+ { name: 'enabled', type: 'bool', offset: 152 },
],
},
LightProbeVolume: {
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index bf81ca591..6fd643726 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -688,6 +688,7 @@ export interface Light {
radius: number;
innerRadius: number;
falloff: number;
+ inverseSquare: boolean;
shadowStrength: number;
layerMin: number;
layerMax: number;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 53abd11f3..377fcc03d 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -400,6 +400,16 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"min": 0,
"tooltip": "Brightness multiplier of the light.",
},
+ "inverseSquare": {
+ "shownWhen": {
+ "field": "type",
+ "values": [
+ 0,
+ 3,
+ ],
+ },
+ "tooltip": "Fall off as 1/distance² in metres (a real lamp): intensity is the light 1 m away, radius only where it ends.",
+ },
"layerMax": {
"max": 127,
"min": -128,
diff --git a/sdk/tests/lightmap-falloff.test.ts b/sdk/tests/lightmap-falloff.test.ts
new file mode 100644
index 000000000..15ebff3a4
--- /dev/null
+++ b/sdk/tests/lightmap-falloff.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect } from 'vitest';
+import { lightFalloff, type BakeLight } from '../src/lightmap/solve';
+
+const lamp = (over: Partial<BakeLight>): BakeLight => ({ kind: 'point', color: [1, 1, 1], intensity: 1, radius: 600, ...over });
+
+describe('a bake falls light off as the frame does', () => {
+ it('ramps linearly by default, from the inner radius, by the authored power', () => {
+ expect(lightFalloff(300, lamp({}))).toBeCloseTo(0.5);
+ expect(lightFalloff(300, lamp({ falloff: 2 }))).toBeCloseTo(0.25);
+ expect(lightFalloff(100, lamp({ innerRadius: 200 }))).toBeCloseTo(1);
+ expect(lightFalloff(700, lamp({}))).toBe(0);
+ });
+
+ it('falls as 1/d² in metres for an inverse-square lamp, held at 10 cm, let go at its reach', () => {
+ const l = lamp({ metre: 100 });
+ expect(lightFalloff(100, l)).toBeCloseTo(1 * (1 - (100 / 600) ** 4) ** 2, 5);
+ expect(lightFalloff(200, l)).toBeCloseTo(0.25 * (1 - (200 / 600) ** 4) ** 2, 5);
+ expect(lightFalloff(1, l)).toBeCloseTo(100, 0); // 1 cm: held at the 10 cm floor, not 10000
+ expect(lightFalloff(600, l)).toBe(0);
+ });
+});
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 5f495a476..c3c6773fa 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash c6adadad4db185c0
+ * @schema_hash 8ca490aabded77bf
*/
-#define ES_EDITOR_API_SCHEMA_HASH "c6adadad4db185c0"
+#define ES_EDITOR_API_SCHEMA_HASH "8ca490aabded77bf"
#include <emscripten/bind.h>
#include <string>
@@ -384,6 +384,7 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"radius","type":"float","group":"Light"},
{"key":"innerRadius","type":"float","group":"Light"},
{"key":"falloff","type":"float","group":"Light"},
+ {"key":"inverseSquare","type":"bool","group":"Light"},
{"key":"shadowStrength","type":"float","group":"Light"},
{"key":"layerMin","type":"int","group":"Light"},
{"key":"layerMax","type":"int","group":"Light"},
@@ -3273,7 +3274,8 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return false;
auto& c = reg.get<esengine::ecs::Light>(entity);
- if (field == "meshShadows") { c.meshShadows = value; }
+ if (field == "inverseSquare") { c.inverseSquare = value; }
+ else if (field == "meshShadows") { c.meshShadows = value; }
else if (field == "followEnvironmentSun") { c.followEnvironmentSun = value; }
else if (field == "aimFollowedSun") { c.aimFollowedSun = value; }
else if (field == "drawEnvironment") { c.drawEnvironment = value; }
@@ -3565,7 +3567,8 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return false;
const auto& c = reg.get<esengine::ecs::Light>(entity);
- if (field == "meshShadows") { return c.meshShadows; }
+ if (field == "inverseSquare") { return c.inverseSquare; }
+ else if (field == "meshShadows") { return c.meshShadows; }
else if (field == "followEnvironmentSun") { return c.followEnvironmentSun; }
else if (field == "aimFollowedSun") { return c.aimFollowedSun; }
else if (field == "drawEnvironment") { return c.drawEnvironment; }
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index d38986a9e..13e362f7c 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -1413,6 +1413,10 @@ void renderer_setLodPreview(u32 view, u32 entity, i32 level) {
g_renderFrame->setLodPreview(view, Entity::fromRaw(entity), held);
}
+void renderer_setWorldUnitsPerMeter(f32 units) {
+ if (g_renderFrame) g_renderFrame->setWorldUnitsPerMeter(units);
+}
+
void renderer_setViewShading(u32 view, i32 mode) {
if (!g_renderFrame) return;
// An unknown mode is the authored look, not a crash: a newer editor may ask for
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 544e57fd0..03dba42db 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -324,8 +324,12 @@ void renderer_setImpostorAtlas(u32 entity, u32 texture, u32 frames);
*/
std::string renderer_takeTextureWants();
+/** How many world units make a metre: what an inverse-square light measures distance in. */
+void renderer_setWorldUnitsPerMeter(f32 units);
+
/**
- * @brief Shade a view's meshes as authored (0), as neutral clay (1) or as flat albedo (2).
+ * @brief Shade a view's meshes as authored (0), as neutral clay (1), as flat albedo (2), as wireframe (3), or as clay
+ * lit by the lights alone (4) or by everything that is not a light (5).
* @details View state, like the LOD preview beside it: the same scene drawn through
* another view keeps its own look. Out-of-range modes mean authored.
*/
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 769894de3..50fcc4040 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -660,6 +660,7 @@ struct LightJS {
f32 radius;
f32 innerRadius;
f32 falloff;
+ bool inverseSquare;
f32 shadowStrength;
i32 layerMin;
i32 layerMax;
@@ -692,6 +693,7 @@ void lightApplyJS(esengine::ecs::Light& c, const LightJS& js) {
c.radius = js.radius;
c.innerRadius = js.innerRadius;
c.falloff = js.falloff;
+ c.inverseSquare = js.inverseSquare;
c.shadowStrength = js.shadowStrength;
c.layerMin = js.layerMin;
c.layerMax = js.layerMax;
@@ -731,6 +733,7 @@ LightJS lightToJS(const esengine::ecs::Light& c) {
js.radius = c.radius;
js.innerRadius = c.innerRadius;
js.falloff = c.falloff;
+ js.inverseSquare = c.inverseSquare;
js.shadowStrength = c.shadowStrength;
js.layerMin = c.layerMin;
js.layerMax = c.layerMax;
@@ -2048,6 +2051,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("radius", &LightJS::radius)
.field("innerRadius", &LightJS::innerRadius)
.field("falloff", &LightJS::falloff)
+ .field("inverseSquare", &LightJS::inverseSquare)
.field("shadowStrength", &LightJS::shadowStrength)
.field("layerMin", &LightJS::layerMin)
.field("layerMax", &LightJS::layerMax)
@@ -4087,29 +4091,30 @@ static_assert(offsetof(esengine::ecs::Light, intensity) == 20, "ABI offset drift
static_assert(offsetof(esengine::ecs::Light, radius) == 24, "ABI offset drift: esengine::ecs::Light.radius (EHT expected 24)");
static_assert(offsetof(esengine::ecs::Light, innerRadius) == 28, "ABI offset drift: esengine::ecs::Light.innerRadius (EHT expected 28)");
static_assert(offsetof(esengine::ecs::Light, falloff) == 32, "ABI offset drift: esengine::ecs::Light.falloff (EHT expected 32)");
-static_assert(offsetof(esengine::ecs::Light, shadowStrength) == 36, "ABI offset drift: esengine::ecs::Light.shadowStrength (EHT expected 36)");
-static_assert(offsetof(esengine::ecs::Light, layerMin) == 40, "ABI offset drift: esengine::ecs::Light.layerMin (EHT expected 40)");
-static_assert(offsetof(esengine::ecs::Light, layerMax) == 44, "ABI offset drift: esengine::ecs::Light.layerMax (EHT expected 44)");
-static_assert(offsetof(esengine::ecs::Light, cookie) == 48, "ABI offset drift: esengine::ecs::Light.cookie (EHT expected 48)");
-static_assert(offsetof(esengine::ecs::Light, cookieSize) == 52, "ABI offset drift: esengine::ecs::Light.cookieSize (EHT expected 52)");
-static_assert(offsetof(esengine::ecs::Light, innerAngle) == 60, "ABI offset drift: esengine::ecs::Light.innerAngle (EHT expected 60)");
-static_assert(offsetof(esengine::ecs::Light, outerAngle) == 64, "ABI offset drift: esengine::ecs::Light.outerAngle (EHT expected 64)");
-static_assert(offsetof(esengine::ecs::Light, shadowSoftness) == 68, "ABI offset drift: esengine::ecs::Light.shadowSoftness (EHT expected 68)");
-static_assert(offsetof(esengine::ecs::Light, sourceAngle) == 72, "ABI offset drift: esengine::ecs::Light.sourceAngle (EHT expected 72)");
-static_assert(offsetof(esengine::ecs::Light, shadowDistance) == 76, "ABI offset drift: esengine::ecs::Light.shadowDistance (EHT expected 76)");
-static_assert(offsetof(esengine::ecs::Light, meshShadows) == 80, "ABI offset drift: esengine::ecs::Light.meshShadows (EHT expected 80)");
-static_assert(offsetof(esengine::ecs::Light, shadowExtent) == 84, "ABI offset drift: esengine::ecs::Light.shadowExtent (EHT expected 84)");
-static_assert(offsetof(esengine::ecs::Light, followEnvironmentSun) == 88, "ABI offset drift: esengine::ecs::Light.followEnvironmentSun (EHT expected 88)");
-static_assert(offsetof(esengine::ecs::Light, aimFollowedSun) == 89, "ABI offset drift: esengine::ecs::Light.aimFollowedSun (EHT expected 89)");
-static_assert(offsetof(esengine::ecs::Light, environment) == 92, "ABI offset drift: esengine::ecs::Light.environment (EHT expected 92)");
-static_assert(offsetof(esengine::ecs::Light, environmentRotation) == 96, "ABI offset drift: esengine::ecs::Light.environmentRotation (EHT expected 96)");
-static_assert(offsetof(esengine::ecs::Light, drawEnvironment) == 100, "ABI offset drift: esengine::ecs::Light.drawEnvironment (EHT expected 100)");
-static_assert(offsetof(esengine::ecs::Light, reflectionScale) == 104, "ABI offset drift: esengine::ecs::Light.reflectionScale (EHT expected 104)");
-static_assert(offsetof(esengine::ecs::Light, reflectionSaturation) == 108, "ABI offset drift: esengine::ecs::Light.reflectionSaturation (EHT expected 108)");
-static_assert(offsetof(esengine::ecs::Light, bakedTint) == 112, "ABI offset drift: esengine::ecs::Light.bakedTint (EHT expected 112)");
-static_assert(offsetof(esengine::ecs::Light, hemisphere) == 128, "ABI offset drift: esengine::ecs::Light.hemisphere (EHT expected 128)");
-static_assert(offsetof(esengine::ecs::Light, groundColor) == 132, "ABI offset drift: esengine::ecs::Light.groundColor (EHT expected 132)");
-static_assert(offsetof(esengine::ecs::Light, enabled) == 148, "ABI offset drift: esengine::ecs::Light.enabled (EHT expected 148)");
+static_assert(offsetof(esengine::ecs::Light, inverseSquare) == 36, "ABI offset drift: esengine::ecs::Light.inverseSquare (EHT expected 36)");
+static_assert(offsetof(esengine::ecs::Light, shadowStrength) == 40, "ABI offset drift: esengine::ecs::Light.shadowStrength (EHT expected 40)");
+static_assert(offsetof(esengine::ecs::Light, layerMin) == 44, "ABI offset drift: esengine::ecs::Light.layerMin (EHT expected 44)");
+static_assert(offsetof(esengine::ecs::Light, layerMax) == 48, "ABI offset drift: esengine::ecs::Light.layerMax (EHT expected 48)");
+static_assert(offsetof(esengine::ecs::Light, cookie) == 52, "ABI offset drift: esengine::ecs::Light.cookie (EHT expected 52)");
+static_assert(offsetof(esengine::ecs::Light, cookieSize) == 56, "ABI offset drift: esengine::ecs::Light.cookieSize (EHT expected 56)");
+static_assert(offsetof(esengine::ecs::Light, innerAngle) == 64, "ABI offset drift: esengine::ecs::Light.innerAngle (EHT expected 64)");
+static_assert(offsetof(esengine::ecs::Light, outerAngle) == 68, "ABI offset drift: esengine::ecs::Light.outerAngle (EHT expected 68)");
+static_assert(offsetof(esengine::ecs::Light, shadowSoftness) == 72, "ABI offset drift: esengine::ecs::Light.shadowSoftness (EHT expected 72)");
+static_assert(offsetof(esengine::ecs::Light, sourceAngle) == 76, "ABI offset drift: esengine::ecs::Light.sourceAngle (EHT expected 76)");
+static_assert(offsetof(esengine::ecs::Light, shadowDistance) == 80, "ABI offset drift: esengine::ecs::Light.shadowDistance (EHT expected 80)");
+static_assert(offsetof(esengine::ecs::Light, meshShadows) == 84, "ABI offset drift: esengine::ecs::Light.meshShadows (EHT expected 84)");
+static_assert(offsetof(esengine::ecs::Light, shadowExtent) == 88, "ABI offset drift: esengine::ecs::Light.shadowExtent (EHT expected 88)");
+static_assert(offsetof(esengine::ecs::Light, followEnvironmentSun) == 92, "ABI offset drift: esengine::ecs::Light.followEnvironmentSun (EHT expected 92)");
+static_assert(offsetof(esengine::ecs::Light, aimFollowedSun) == 93, "ABI offset drift: esengine::ecs::Light.aimFollowedSun (EHT expected 93)");
+static_assert(offsetof(esengine::ecs::Light, environment) == 96, "ABI offset drift: esengine::ecs::Light.environment (EHT expected 96)");
+static_assert(offsetof(esengine::ecs::Light, environmentRotation) == 100, "ABI offset drift: esengine::ecs::Light.environmentRotation (EHT expected 100)");
+static_assert(offsetof(esengine::ecs::Light, drawEnvironment) == 104, "ABI offset drift: esengine::ecs::Light.drawEnvironment (EHT expected 104)");
+static_assert(offsetof(esengine::ecs::Light, reflectionScale) == 108, "ABI offset drift: esengine::ecs::Light.reflectionScale (EHT expected 108)");
+static_assert(offsetof(esengine::ecs::Light, reflectionSaturation) == 112, "ABI offset drift: esengine::ecs::Light.reflectionSaturation (EHT expected 112)");
+static_assert(offsetof(esengine::ecs::Light, bakedTint) == 116, "ABI offset drift: esengine::ecs::Light.bakedTint (EHT expected 116)");
+static_assert(offsetof(esengine::ecs::Light, hemisphere) == 132, "ABI offset drift: esengine::ecs::Light.hemisphere (EHT expected 132)");
+static_assert(offsetof(esengine::ecs::Light, groundColor) == 136, "ABI offset drift: esengine::ecs::Light.groundColor (EHT expected 136)");
+static_assert(offsetof(esengine::ecs::Light, enabled) == 152, "ABI offset drift: esengine::ecs::Light.enabled (EHT expected 152)");
static_assert(offsetof(esengine::ecs::LightProbeVolume, probes) == 0, "ABI offset drift: esengine::ecs::LightProbeVolume.probes (EHT expected 0)");
static_assert(offsetof(esengine::ecs::LightProbeVolume, halfExtents) == 4, "ABI offset drift: esengine::ecs::LightProbeVolume.halfExtents (EHT expected 4)");
static_assert(offsetof(esengine::ecs::LightProbeVolume, spacing) == 16, "ABI offset drift: esengine::ecs::LightProbeVolume.spacing (EHT expected 16)");
@@ -4421,7 +4426,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "5e943b68bf754ab0";
+static const char* kEsAbiLayoutHash = "04486d0b29ae33ae";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 0377e27b1..1792e3fca 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -817,6 +817,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_setImpostorAtlas", &esengine::renderer_setImpostorAtlas);
emscripten::function("renderer_takeTextureWants", &esengine::renderer_takeTextureWants);
emscripten::function("renderer_setViewShading", &esengine::renderer_setViewShading);
+ emscripten::function("renderer_setWorldUnitsPerMeter", &esengine::renderer_setWorldUnitsPerMeter);
emscripten::function("renderer_setMeshEdgeBuffers", &esengine::renderer_setMeshEdgeBuffers);
emscripten::function("renderer_setViewSkinWeights", &esengine::renderer_setViewSkinWeights);
emscripten::function("renderer_lightStatus", &esengine::renderer_lightStatus);
diff --git a/src/esengine/ecs/components/Light.hpp b/src/esengine/ecs/components/Light.hpp
index b704df713..d6c503950 100644
--- a/src/esengine/ecs/components/Light.hpp
+++ b/src/esengine/ecs/components/Light.hpp
@@ -87,6 +87,15 @@ struct Light {
tooltip="Falloff shape: 1 = linear, higher pools near the light, lower reaches further.")
f32 falloff{1.0f};
+ /** @brief Falls off as the inverse square of the distance, in metres, as a real light does (Unreal's Use Inverse
+ * Squared Falloff, glTF's and three.js's point lights): `intensity` is then what reaches a surface one metre
+ * away, and @ref radius is only where it is let go — the last of it eased to nothing over the far end — so
+ * a lamp pools under itself rather than washing a room evenly. Off, the light ramps from @ref innerRadius to
+ * @ref radius by @ref falloff. Point and Spot only. */
+ ES_PROPERTY(shown_when=type:Point|Spot,
+ tooltip="Fall off as 1/distance² in metres (a real lamp): intensity is the light 1 m away, radius only where it ends.")
+ bool inverseSquare{false};
+
/** @brief How much of this light a shadow takes away, 0..1. 1 (the default) is the
* whole of it; 0.7 leaves a shadow that is dark rather than black, which is
* what a 2D scene with bounce light in it looks like. Applies to both kinds
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 19fecd9fd..ce047f57e 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -1743,8 +1743,10 @@ void RenderFrame::collectLights(ecs::Registry& registry) {
// Clamped where it is PACKED: a shader given a negative exponent lights the far
// side of the radius, and a fragment cannot say who authored it. The shader
// floors the exponent too — pow(0, 0) is 1, which lights the whole screen.
+ // y: the ramp's power, or for an inverse-square light minus the world units in a metre (a power is never
+ // negative, so the sign says which; distanceFalloff reads both).
gpu.falloff = glm::vec4(std::max(light.innerRadius, 0.0f),
- std::max(light.falloff, 0.0f),
+ light.inverseSquare ? -world_units_per_meter_ : std::max(light.falloff, 0.0f),
// w: the shape mask channel, -1 for a light with no shape of its own. A zero would read channel 0 of whatever sits on that unit.
std::clamp(light.shadowStrength, 0.0f, 1.0f), -1.0f);
// The sprite layers it reaches ride above the tile count the shadow atlas fills in later.
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index 2b3bae144..4b2d30da8 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -405,6 +405,8 @@ public:
* window they are looking through.
*/
void setViewShading(u32 view, ShadingMode mode) { view_shading_.set(view, mode); }
+ /** @brief How many world units make a metre (the project's setting): what an inverse-square light measures in. */
+ void setWorldUnitsPerMeter(f32 units) { world_units_per_meter_ = units > 0.0f ? units : 100.0f; }
/**
* @brief Colour @p entity in @p view by how much @p joint moves each of its vertices.
@@ -787,6 +789,7 @@ private:
};
std::unordered_map<u32, PlanarCapture> planar_captures_;
TransientBufferPool planar_pool_{device_};
+ f32 world_units_per_meter_ = 100.0f;
/// The probe volumes' grids, packed for the per-pixel read (ProbeStore::layoutAtlas). Remade only when a grid
/// or the set of grids changes, so a still scene uploads it once.
Unique<Texture> probe_atlas_;
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 66d27da8f..f572512ff 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -2149,7 +2149,12 @@ fn towardLight(toLight : vec3f, N : vec3f) -> vec3f {
// a light that reaches nowhere would light everything.
fn distanceFalloff(dist : f32, reach : f32, fo : vec4f) -> f32 {
let ramp = clamp((reach - dist) / max(reach - fo.x, 1e-4), 0.0, 1.0);
- return pow(ramp, max(fo.y, 1e-3));
+ let shaped = pow(ramp, max(fo.y, 1e-3));
+ // See the GLSL twin: fo.y < 0 is an inverse-square light, -fo.y world units to the metre.
+ let metres = dist / max(-fo.y, 1e-4);
+ let q = dist / max(reach, 1e-4);
+ let w = clamp(1.0 - q * q * q * q, 0.0, 1.0);
+ return select(shaped, w * w / max(metres * metres, 0.01), fo.y < 0.0);
}
)"
// Split again for the same reason: the surface layers and the lighting that reads them.
@@ -3643,7 +3648,14 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
"highp float distanceFalloff(in highp float dist, in highp float reach,\n"
" in highp vec4 fo) {\n"
" highp float ramp = clamp((reach - dist) / max(reach - fo.x, 1e-4), 0.0, 1.0);\n"
- " return pow(ramp, max(fo.y, 1e-3));\n"
+ " highp float shaped = pow(ramp, max(fo.y, 1e-3));\n"
+ // An inverse-square light (fo.y < 0, -fo.y world units to the metre): 1/d^2 in metres, held at 10 cm so a
+ // surface on the lamp is bright and not infinite, and let go over the reach by (1 - (d/r)^4)^2 — three.js's
+ // and glTF's window, so a lamp brought over from either lights the same. One exit: this inlines into the light loop.
+ " highp float metres = dist / max(-fo.y, 1e-4);\n"
+ " highp float q = dist / max(reach, 1e-4);\n"
+ " highp float w = clamp(1.0 - q * q * q * q, 0.0, 1.0);\n"
+ " return fo.y < 0.0 ? w * w / max(metres * metres, 0.01) : shaped;\n"
"}\n"
// What a surface has beyond a base colour and a metal/rough pair: a clear coat over it, a sheen on it, grooves that stretch
// its highlight, light that scatters into it or passes through it, a thin film that tints its reflection. All zero is the
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index daef73efe..5edaee3c6 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0x979ff0f0e2eab4b6ULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0xfbd6360662f44589ULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index 4247c1b6e..fd41e38af 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x979ff0f0e2eab4b6ULL
+#define ES_ABI_ENGINE_DIGEST 0xfbd6360662f44589ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tools/lightmap-wasm/kernel.cpp b/tools/lightmap-wasm/kernel.cpp
index 97fb2dc39..025e1ffd3 100644
--- a/tools/lightmap-wasm/kernel.cpp
+++ b/tools/lightmap-wasm/kernel.cpp
@@ -433,8 +433,9 @@ void lm_scene(const float* pos, int triCount, const float* triUV, const int* tri
/**
* Direct light at every lumel. `lights` is 16 doubles each: kind (0 directional,
- * 1 point, 2 spot), position 3, direction 3, colour 3, intensity, radius,
- * inner cos, outer cos, unused.
+ * 1 point, 2 spot), position 3, direction 3, colour 3, inner radius, intensity, radius,
+ * inner cos, outer cos, and the falloff: the ramp's power, or minus the world units in a
+ * metre for an inverse-square light — the frame's distanceFalloff, so bake and frame agree.
*/
void lm_direct(const float* position, const float* normal, int count,
const double* lights, int lightCount, float* out, int threads) {
@@ -457,11 +458,17 @@ void lm_direct(const float* position, const float* normal, int count,
if (distance < 1e-6) continue;
lx /= distance; ly /= distance; lz /= distance;
const double radius = L[12];
- if (radius > 0) {
- if (distance >= radius) continue;
- const double k = 1 - distance / radius;
- falloff = k * k;
+ if (radius > 0 && distance >= radius) continue;
+ if (L[15] < 0) {
+ const double m = distance / -L[15];
+ const double q = radius > 0 ? distance / radius : 0.0;
+ const double w = std::min(std::max(1.0 - q * q * q * q, 0.0), 1.0);
+ falloff = w * w / std::max(m * m, 0.01);
+ } else if (radius > 0) {
+ const double ramp = std::min(std::max((radius - distance) / std::max(radius - std::max(L[10], 0.0), 1e-4), 0.0), 1.0);
+ falloff = std::pow(ramp, std::max(L[15], 1e-3));
}
+ if (falloff <= 0) continue;
if (kind == 2) {
const double len = lengthOr1(L[4], L[5], L[6]);
const double cosA = -(lx * L[4] + ly * L[5] + lz * L[6]) / len;
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index f4c267ed7..e871ee96c 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -917,6 +917,9 @@ export const SCENES = [
// A sky the project wrote (defineSkyEffect): blue above the horizon, red below. It is drawn behind the ball, and with Light
// the Scene the engine reads back a panorama of it and lights the ball with it: blue on top, red underneath. Upside
// down, the two swap; never captured, the ball is the Ambient light's flat white.
+ // An inverse-square lamp (0.5) 1 m over a white floor, seen from above: 0.5 under it, 0.5 x cos45 / 2 one metre out,
+ // 0.5 x 0.45 / 5 two metres out (0.5, 0.177, 0.045 linear) — the pool a real lamp throws; the ramp falls off far more gently.
+ { id: "point-inverse-square", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_SCENE: "/scenes/point-inverse-square.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "3", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[187,187,187],\"tol\":8},{\"x\":0.667,\"y\":0.5,\"rgb\":[117,117,117],\"tol\":8},{\"x\":0.833,\"y\":0.5,\"rgb\":[58,58,58],\"tol\":8}]" } },
{ id: "custom-sky", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SETTLE_MS: "1500", ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_SCENE: "/scenes/custom-sky.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.08,\"y\":0.08,\"rgb\":[89,124,243],\"tol\":10},{\"x\":0.08,\"y\":0.92,\"rgb\":[231,108,63],\"tol\":10},{\"x\":0.5,\"y\":0.32,\"rgb\":[127,121,226],\"tol\":20},{\"x\":0.5,\"y\":0.68,\"rgb\":[217,111,118],\"tol\":20}]" } },
{ id: "sky-fog", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/sky-fog.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/depth-outline.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.2, \"y\": 0.1, \"rgb\": [144, 175, 187], \"tol\": 12}, {\"x\": 0.5, \"y\": 0.1, \"rgb\": [141, 174, 183], \"tol\": 12}, {\"x\": 0.8, \"y\": 0.2, \"rgb\": [143, 174, 186], \"tol\": 12}, {\"x\": 0.5, \"y\": 0.4, \"rgb\": [139, 171, 180], \"tol\": 12}, {\"x\": 0.2, \"y\": 0.8, \"rgb\": [62, 70, 70], \"tol\": 12}, {\"x\": 0.8, \"y\": 0.8, \"rgb\": [57, 64, 67], \"tol\": 12}]" } },
// SSAO: one unlit grey floor read at seven places. Contact, corner and