Nostalgia64 | Champions Simulation This is the viewer’s fan-made approximation, not original Pokémon Champions game code. The sections below contain the viewer’s JavaScript and embedded GLSL, with original filenames. The files use the viewer’s Three.js runtime and are not a standalone shader package. === champions-common-program.js === import {CHAMPIONS_KEY_DIRECTION} from './champions-light-camera.js'; import * as THREE from '../../public/vendor/three.module.js'; import {commonDepthDeclarations,installDepthVertex} from './champions-depth-program.js'; // Shared Champions Simulation approximation. RGB gradient/coat/status rig calibrated // offline; not a claim of native scene values or pixel parity. // Shared fixed-world lighting, self-shadow and external camera-depth rim from QA. // Not a reconstructed native runtime lighting setup; no per-model constants. const declarations = ` uniform float p9CommonActive; uniform vec4 p9Surface; uniform sampler2D p9UtilityMap; uniform float p9UtilityEnabled; uniform float p9UtilityScale; uniform float p9StatusIntensity; vec3 p9Gradient(float cosine) { return mix(vec3(0.0002828891531, 0.06090696803, 0.1681913657), vec3(1.7566824684, 1.8401981769, 1.8686905251), pow(min(p9ShadowFactor(),clamp(cosine * 0.5 + 0.5, 0.0, 1.0)), 2.3862060886)); } float p9Highlight(float cosine, float roughness, float metallic) { float exponent = pow(6.0 / clamp(roughness, 0.1, 1.0) - 1.0, 2.0); float h = clamp(cosine, 0.0, 1.0); return pow(h, exponent) * metallic + 0.5769089296 * pow(h, p9Surface.y) * p9Surface.z; } `; const response = ` if (p9CommonActive > 0.5) { vec3 p9DiffuseLight = vec3(0.0); vec3 p9SpecularLight = vec3(0.0); // Shared view-space status rig, independent of stock light count. No scene-light // mutation: Standard and unsupported materials retain their original lighting. vec3 p9Direction = p9KeyView; vec3 p9Light = vec3(2.1 * p9StatusIntensity) * RECIPROCAL_PI; vec3 p9Shade = p9Gradient(dot(normal, p9Direction)); vec3 p9Half = normalize(p9Direction + geometryViewDir); p9DiffuseLight = p9Light * p9Shade; p9SpecularLight = p9Light * p9Shade * p9Highlight(dot(normal, p9Half), roughnessFactor, metalnessFactor); float p9AO = 1.0; // Only independently identified embedded raw Utility R. Do not substitute // ordinary PBR occlusion (which Three may also apply to indirect lighting). #ifdef USE_MAP if (p9UtilityEnabled > 0.5) { float utilityR = texture2D(p9UtilityMap, vMapUv).r; p9AO = 1.0 + p9UtilityScale * (utilityR - 1.0); p9SpecularLight *= utilityR; } #endif totalDiffuse = vec3(0.9172831905 * p9StatusIntensity) * RECIPROCAL_PI * material.diffuseColor + diffuseColor.rgb * p9DiffuseLight * p9AO; // Replace the old artistic rim, never add it on top of the depth rim. vec3 p9Rim = vec3(p9DepthRim(nonPerturbedNormal, vViewPosition)); totalSpecular = p9SpecularLight + p9Rim; } `; const diffuseEnd = 'vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;'; const outgoing = 'vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;'; export function installCommonProgram(material, active, surface, unsupported, utility = {}) { const compile = material.onBeforeCompile, cacheKey = material.customProgramCacheKey; material.onBeforeCompile = function (shader, renderer) { compile.call(this, shader, renderer); if (!shader.fragmentShader.includes(diffuseEnd) || !shader.fragmentShader.includes(outgoing) || !installDepthVertex(shader)) return unsupported(); Object.assign(shader.uniforms, { p9CommonActive: active, p9Surface: { value: surface }, p9UtilityMap: utility.map || { value: null }, p9UtilityEnabled: utility.enabled || { value: 0 }, p9UtilityScale: utility.scale || { value: 0 }, p9StatusIntensity: utility.intensity || { value: 1 }, p9DepthValid: { value: 0 }, p9KeyDepth: { value: null }, p9CameraDepth: { value: null }, p9LightMatrix: { value: new THREE.Matrix4() }, p9CameraProject: { value: new THREE.Matrix4() }, p9DepthZW: { value: new THREE.Vector2() }, p9Viewport: { value: new THREE.Vector2(1,1) }, p9KeyView: { value: new THREE.Vector3(...CHAMPIONS_KEY_DIRECTION).normalize() }, ...utility.depth, }); shader.fragmentShader = commonDepthDeclarations + declarations + shader.fragmentShader .replace(diffuseEnd, diffuseEnd + response) .replace( outgoing, outgoing + '\nif(p9CommonActive>0.5 && p9Surface.w>0.5) outgoingLight=max(totalDiffuse+totalSpecular,totalEmissiveRadiance);', ); }; material.customProgramCacheKey = function () { return cacheKey.call(this) + '|p9-common-full-qa-v3'; }; material.needsUpdate = true; return () => { material.onBeforeCompile = compile; material.customProgramCacheKey = cacheKey; material.needsUpdate = true; }; } === champions-depth-program.js === // Own implementation of the frozen QA approximation, not copied compiled game code. export const commonDepthDeclarations=` uniform float p9DepthValid; uniform sampler2D p9KeyDepth; uniform sampler2D p9CameraDepth; uniform mat4 p9CameraProject; uniform vec2 p9DepthZW; uniform vec2 p9Viewport; uniform vec3 p9KeyView; varying vec4 p9ShadowPosition; float p9ShadowFactor(){ if(p9DepthValid<0.5)return 1.0; vec3 q=p9ShadowPosition.xyz/p9ShadowPosition.w*.5+.5; if(any(lessThan(q,vec3(0.0)))||any(greaterThan(q,vec3(1.0))))return 1.0; float visible=0.0; for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++)visible+=step(q.z-.0005,texture2D(p9KeyDepth,q.xy+vec2(x,y)/1024.0).r); return 1.0-.528495590339977*(1.0-visible/9.0); } float p9DepthRim(vec3 geometricNormal, vec3 viewPosition){ if(p9DepthValid<.5)return 0.0; vec4 base=p9CameraProject*vec4(-viewPosition,1.0); if(base.w<=0.0)return 0.0; vec4 shifted=base+p9CameraProject*vec4(0.,clamp(geometricNormal.y,0.,1.)*.01,0.,0.); if(shifted.w<=0.0)return 0.0; vec2 uv=gl_FragCoord.xy/p9Viewport; vec2 offset=uv+.5*(shifted.xy/shifted.w-base.xy/base.w); if(any(lessThan(offset,vec2(0.0)))||any(greaterThan(offset,vec2(1.0))))return 0.0; float farDepth=texture2D(p9CameraDepth,offset).r; if(farDepth<.999999)return 0.0; float a=dot(p9DepthZW,vec2(texture2D(p9CameraDepth,uv).r,1.0)); float b=dot(p9DepthZW,vec2(farDepth,1.0)); if(a<=0.0||b<=0.0)return 0.0; return .5*smoothstep(.5,.65,1.0/b-1.0/a); } `; export function installDepthVertex(shader){ if(!shader.vertexShader?.includes('#include '))return false; shader.vertexShader='uniform mat4 p9LightMatrix; varying vec4 p9ShadowPosition;\n'+shader.vertexShader.replace('#include ','#include \np9ShadowPosition=p9LightMatrix*modelMatrix*vec4(transformed,1.0);'); return true; } === champions-shader-program.js === const outgoing = 'vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;'; const declarations = ` uniform float championsActive; uniform sampler2D championsAlbedo; uniform sampler2D championsEmission; // Portable-sRGB compatibility approximation, not proof of source GPU color space. vec3 championsDecode(vec3 x) { return mix(pow((max(x, vec3(0.0)) + 0.055) / 1.055, vec3(2.4)), x / 12.92, lessThanEqual(x, vec3(0.04045))); } `; export function installChampionsProgram(material, maps, active, fallback) { const compile = material.onBeforeCompile; const cacheKey = material.customProgramCacheKey; material.onBeforeCompile = function (shader, renderer) { compile.call(this, shader, renderer); const chunks = [outgoing, '#include ', '#include ']; if (!chunks.every((chunk) => shader.fragmentShader.includes(chunk))) return fallback(); Object.assign(shader.uniforms, { championsActive: active, championsAlbedo: { value: maps.albedo }, championsEmission: { value: maps.emission }, }); shader.fragmentShader = declarations + shader.fragmentShader .replace( chunks[1], `${chunks[1]} if (championsActive > 0.5) diffuseColor.rgb = championsDecode(texture2D(championsAlbedo, vMapUv).rgb);`, ) .replace( chunks[2], `${chunks[2]} if (championsActive > 0.5) totalEmissiveRadiance = championsDecode(texture2D(championsEmission, vMapUv).rgb);`, ) .replace( outgoing, `${outgoing} if (championsActive > 0.5) outgoingLight = max(totalDiffuse + totalSpecular, totalEmissiveRadiance);`, ); }; material.customProgramCacheKey = function () { return cacheKey.call(this) + '|champions-source-max-v1'; }; material.needsUpdate = true; return () => { material.onBeforeCompile = compile; material.customProgramCacheKey = cacheKey; material.needsUpdate = true; }; } === champions-common.js === import {createCommonDepth} from './champions-depth-effects.js'; import * as THREE from '../../public/vendor/three.module.js'; import { installCommonProgram } from './champions-common-program.js'; // Select only opaque/cutout common surfaces with the source family signature. // Eyes, refraction, blended shells/wings and depth-only passes remain authored. export function commonMaterialParameters(material) { const f = material.userData?.bakeMetadata?.sourceProperties?.floats; if ( !material.isMeshStandardMaterial || !f || /eye|depth/i.test(material.name) || material.transparent || material.opacity !== 1 || !material.depthWrite || !material.colorWrite || f._RefractionMode !== 0 || f._EnableIceJewel !== 0 ) return null; const values = [ f._GradientExponential, f._SpecularCoatPower, f._SpecularCoatScale, f._EmissionOperation, ]; if ( !values.every(Number.isFinite) || values[0] < 0.5 || values[0] > 4 || values[1] < 0 || values[1] > 1024 || values[2] < 0 || values[2] > 10 || ![0, 1].includes(values[3]) ) return null; return new THREE.Vector4(...values); } export function createChampionsCommon({ model, modelId, game, parser, renderer, scene }) { return new CommonProfile( model, game === 'pokemon-champions' && /^champions-pm\d{4}-\d{2}-\d{2}(-rare)?$/.test(modelId), parser, renderer, scene, ); } class CommonProfile { constructor(model, supported, parser, renderer, scene) { this.depth = supported ? createCommonDepth(renderer,scene,model,m=>!!commonMaterialParameters(m)) : null; this.parser = parser; this.generation = 0; this.intensity = { value: 1 }; this.textures = new Set(); this.pending = Promise.resolve(); this.model = model; this.supported = supported; this.active = { value: 0 }; if(this.depth)this.depth.onFailure=(error)=>{this.active.value=0;this.depthFailed=true;this.onStatusChange?.(error);}; this.selected = false; this.disposed = false; this.restore = []; this.coverage = { common: 0, unchanged: 0 }; } install() { this.coverage = { common: 0, unchanged: 0 }; const generation = ++this.generation; const jobs = []; const materials = new Set(); this.model.traverse((object) => { if (object.isMesh) for (const material of [].concat(object.material)) materials.add(material); }); for (const material of materials) { const parameters = commonMaterialParameters(material); if (!parameters) { this.coverage.unchanged++; continue; } this.coverage.common++; const utility = { depth: this.depth?.uniforms, intensity: this.intensity, map: { value: null }, enabled: { value: 0 }, scale: { value: 0 } }; // Exact frozen QA recipe predates the optional native Utility R override. // Keep it OFF; do not silently combine a later experiment into this release. this.restore.push( installCommonProgram(material, this.active, parameters, () => { this.active.value = 0; this.failed = true; }, utility), ); } this.installed = true; this.pending = Promise.all(jobs); } async loadUtility(material, utility, generation) { const source = commonUtilitySource(this.parser, material); if (!source) return; try { const original = await this.parser.getDependency('texture', source.index); if (this.disposed || generation !== this.generation || !this.selected) return; const texture = original.clone(); texture.colorSpace = THREE.NoColorSpace; texture.needsUpdate = true; this.textures.add(texture); utility.map.value = texture; utility.scale.value = source.scale; utility.enabled.value = 1; } catch { // Missing/ambiguous source data never turns into invented occlusion. utility.enabled.value = 0; } } render(camera, draw) { return this.depth ? this.depth.render(camera, draw) : draw(); } setIntensity(value) { this.intensity.value = Math.max(0, Math.min(3, Number.isFinite(value) ? value : 1)); } setMode(mode) { this.selected = this.supported && !this.disposed && mode === 'champions'; // Keep one program/uniform set across mode switches. Three caches programs // per material but does not restore their custom uniforms on a cache hit. // Restoring the Standard hook here leaves Standard uniforms attached when // Champions is selected again, including stale disposed depth samplers. // Standard uses the existing inactive branch; only disposal restores hooks. if (!this.selected) this.generation++; if (this.selected && !this.installed) this.install(); this.depthFailed=false; this.active.value = this.selected && !this.failed ? 1 : 0; this.setDepthEnabled(true); } setDepthEnabled(lit) { this.depth?.setEnabled(Boolean(lit && this.selected && this.coverage.common > 0 && !this.failed && !this.depthFailed)); } get status() { if (!this.selected) return 'standard'; return this.coverage.common && !this.failed && !this.depthFailed ? 'source-lighting-approximation' : 'standard-fallback'; } uninstall() { this.active.value = 0; this.generation++; for (const texture of this.textures) texture.dispose(); this.textures.clear(); for (const restore of this.restore) restore(); this.restore = []; this.installed = false; } dispose() { if (this.disposed) return; this.depth?.dispose(); this.disposed = true; this.selected = false; this.uninstall(); } } // Resolve the original embedded source image by identity, never by filename guesses // or the material's conventional occlusionTexture. No asset fetch outside its GLB. // Legacy extras encode int64 IDs as JSON numbers: match their numeric projection // against embedded decimal IDs, but reject every multi-image collision. export function commonUtilitySource(parser, material) { const json = parser?.json; const index = parser?.associations?.get(material)?.materials; const source = json?.materials?.[index]; if (!source || source.name !== material.name || !material.map) return null; const e = source.extras; const f = e?.bakeMetadata?.sourceProperties?.floats; const uv = e?.bakeMetadata?.sourceProperties?.colors?._UVScaleOffset; const pid = e?.unityTextureProperties?._UtilityMap; if (!pid || !f || !Number.isFinite(f._AOScale) || f._AOScale < 0 || f._AOScale > 1 || f._UVIndexAO !== 0 || f._UVTransformMode !== 0 || f._UVRotation !== 0 || !uv || uv.length !== 4 || uv.some((v, i) => v !== [1, 1, 0, 0][i]) || (source.pbrMetallicRoughness?.baseColorTexture?.texCoord || 0) !== 0 || source.pbrMetallicRoughness?.baseColorTexture?.extensions?.KHR_texture_transform || material.map.channel !== 0) return null; const images = (json.images || []).map((image, i) => ({ image, i })).filter(({ image }) => String(image.extras?.sourcePathID) === String(pid) || (typeof pid === 'number' && Number.isInteger(pid) && typeof image.extras?.sourcePathID === 'string' && /^-?\d+$/.test(image.extras.sourcePathID) && Number(image.extras.sourcePathID) === pid)); if (images.length !== 1 || images[0].image.mimeType !== 'image/png' || !Number.isInteger(images[0].image.bufferView) || images[0].image.uri) return null; const textures = (json.textures || []).map((texture, i) => ({ texture, i })).filter(({ texture }) => texture.source === images[0].i); if (textures.length !== 1 || textures[0].texture.extensions) return null; return { index: textures[0].i, scale: f._AOScale }; } === champions-depth-effects.js === import * as T from '../../public/vendor/three.module.js'; import {ChampionsShadowPass} from './champions-depth-pass.js'; import {fitLightCamera, CHAMPIONS_KEY_DIRECTION} from './champions-light-camera.js'; export function createCommonDepth(renderer,scene,model,eligible) { if(!renderer?.isWebGLRenderer)return null; return new CommonDepth(renderer,scene,model,eligible); } export function boundedDepthSize(width,height,maxTextureSize) { if(![width,height,maxTextureSize].every(Number.isFinite)||width<1||height<1||maxTextureSize<1)throw Error('Invalid Champions depth dimensions'); const scale=Math.min(1,maxTextureSize/width,maxTextureSize/height,Math.sqrt(4194304/(width*height))); return [Math.max(1,Math.floor(width*scale)),Math.max(1,Math.floor(height*scale))]; } class CommonDepth { constructor(renderer,scene,model,eligible){ this.renderer=renderer;this.scene=scene;this.model=model;this.eligible=eligible;this.enabled=false;this.failed=false; this.light=new ChampionsShadowPass(renderer,scene,model,{size:1024,eligible}); this.cameraDepth=new ChampionsShadowPass(renderer,scene,model,{size:512,casterSide:T.FrontSide}); this.uniforms={p9DepthValid:{value:0},p9KeyDepth:{value:null},p9CameraDepth:{value:null},p9LightMatrix:{value:new T.Matrix4()},p9CameraProject:{value:new T.Matrix4()},p9DepthZW:{value:new T.Vector2()},p9Viewport:{value:new T.Vector2(1,1)},p9KeyView:{value:new T.Vector3()}}; } setEnabled(value){this.enabled=!!value;this.failed=false;this.light.setEnabled(value);this.cameraDepth.setEnabled(value);this.uniforms.p9DepthValid.value=0;} render(camera,draw){ if(!this.enabled||this.failed)return draw(); let colorStarted=false; try { const size=this.renderer.getDrawingBufferSize(new T.Vector2()); // Hidden canvases may also have no current visible geometry. Skip before // fitting instead of latching a failure during a transient layout change. if(size.x<1||size.y<1)return draw(); this.scene.updateMatrixWorld(true);camera.updateMatrixWorld(); this.uniforms.p9KeyView.value.set(...CHAMPIONS_KEY_DIRECTION).transformDirection(camera.matrixWorldInverse); const light=fitLightCamera(this.model,camera,this.eligible); if(this.renderer.capabilities.reverseDepthBuffer || this.renderer.capabilities.logarithmicDepthBuffer)throw Error('Champions depth projection unsupported'); // Uniformly downsample only oversized depth attachments. Sampling UV stays // normalized against the COLOR raster, never this smaller attachment. const [depthWidth,depthHeight]=boundedDepthSize(size.x,size.y,this.renderer.capabilities.maxTextureSize); this.cameraDepth.setSize(depthWidth,depthHeight); this.uniforms.p9KeyView.value.set(...CHAMPIONS_KEY_DIRECTION).transformDirection(camera.matrixWorldInverse); this.uniforms.p9CameraProject.value.copy(camera.projectionMatrix);this.uniforms.p9Viewport.value.copy(size); this.uniforms.p9DepthZW.value.set(-(camera.far-camera.near)/(camera.far*camera.near),1/camera.near); return this.light.renderFrame(camera,light.camera,s=>this.cameraDepth.renderFrame(camera,camera,d=>{ this.uniforms.p9LightMatrix.value.copy(s.matrix.value);this.uniforms.p9KeyDepth.value=s.texture.value;this.uniforms.p9CameraDepth.value=d.texture.value;this.uniforms.p9DepthValid.value=s.valid.value*d.valid.value; colorStarted=true;return draw(); })); } catch(error) { this.failed=true;this.uniforms.p9DepthValid.value=0;this.onFailure?.(error); if(colorStarted)throw error; return draw(); } finally {this.uniforms.p9DepthValid.value=0;this.uniforms.p9KeyDepth.value=null;this.uniforms.p9CameraDepth.value=null;} } dispose(){this.enabled=false;this.light.dispose();this.cameraDepth.dispose();this.uniforms.p9DepthValid.value=0;} } === champions-depth-pass.js === import * as T from '../../public/vendor/three.module.js'; // Shared isolated depth producer. No native runtime light-binding claim. export class ChampionsShadowPass { constructor(renderer, scene, model, {size=512, casterSide=T.BackSide, eligible=()=>true}={}) { this.renderer=renderer;this.scene=scene;this.model=model;this.size=Math.max(256,Math.min(1024,Math.floor(size))); this.eligible=eligible;this.height=this.size;this.casterSide=casterSide;this.enabled=false;this.disposed=false;this.bound=false;this.frame=0; this.uniforms={texture:{value:null},valid:{value:0},matrix:{value:new T.Matrix4()}}; this.hiddenDepth=new T.MeshDepthMaterial({visible:false});this.depthMaterials=new Map();this.target=null;this.inFrame=false; } setEnabled(value){this.enabled=!!value&&!this.disposed;this.invalidate();if(!this.enabled)this.release();} invalidate(){this.uniforms.valid.value=0;this.uniforms.texture.value=null;} release(){this.target?.dispose();this.target=null;for(const m of this.depthMaterials.values())m.dispose();this.depthMaterials.clear();} setSize(width,height=width){const next=Math.max(1,Math.floor(width)),h=Math.max(1,Math.floor(height));if(next!==this.size||h!==this.height){this.size=next;this.height=h;this.invalidate();this.release();}} material(source){ // Unknown blended/refractive surfaces do NOT become opaque casters. Alpha tested // opaque materials preserve their existing texture/UV transform and alpha threshold. const f=source.userData?.bakeMetadata?.sourceProperties?.floats; if(!this.eligible(source)||source.transparent||source.opacity!==1||!source.depthWrite||!source.colorWrite||f?._NoCastSelfShadow===1)return null; let d=this.depthMaterials.get(source); if(!d){d=new T.MeshDepthMaterial({depthPacking:T.BasicDepthPacking});this.depthMaterials.set(source,d);} d.vertexColors=source.vertexColors;d.map=source.map;d.alphaMap=source.alphaMap;d.alphaTest=source.alphaTest;d.side=this.casterSide; d.displacementMap=source.displacementMap;d.displacementScale=source.displacementScale;d.displacementBias=source.displacementBias; d.clippingPlanes=source.clippingPlanes;d.clipIntersection=source.clipIntersection;d.visible=source.visible; // Texture/alpha/material state can change between frames. Safe but potentially // extra compilation: production should derive a precise structural cache key. const signature=[source.map?.uuid,source.alphaMap?.uuid,source.alphaTest>0,source.vertexColors,source.displacementMap?.uuid,this.casterSide,source.clippingPlanes?.length].join('|');if(d.userData.signature!==signature){d.userData.signature=signature;d.needsUpdate=true;}return d; } fingerprint(camera,light){ const values=[...camera.matrixWorld.elements,...camera.projectionMatrix.elements,...light.matrixWorld.elements,...light.projectionMatrix.elements,this.size,this.height]; const skeletons=new Set(); this.model.traverse(o=>{values.push(o.id,Number(o.visible),...o.matrixWorld.elements);if(o.isMesh){values.push(...(o.morphTargetInfluences||[]));if(o.skeleton&&!skeletons.has(o.skeleton)){skeletons.add(o.skeleton);values.push(...o.skeleton.boneMatrices);}}}); return values; } renderFrame(viewCamera, lightCamera, drawColor){ if(this.inFrame)throw Error('Shadow frame reentrancy rejected'); this.inFrame=true;this.invalidate(); try { if(!this.enabled||this.disposed)return drawColor(this.uniforms); this.model.updateWorldMatrix(true,true);viewCamera.updateMatrixWorld();lightCamera.updateMatrixWorld(); this.model.traverse(o=>{if(o.skeleton)o.skeleton.update();}); const epoch=this.fingerprint(viewCamera,lightCamera); this.drawDepth(lightCamera); const current=this.fingerprint(viewCamera,lightCamera); if(epoch.length===current.length && epoch.every((v,i)=>v===current[i])){ this.uniforms.matrix.value.multiplyMatrices(lightCamera.projectionMatrix,lightCamera.matrixWorldInverse); this.uniforms.texture.value=this.target.depthTexture;this.uniforms.valid.value=1; } if(this.bound)throw Error('Sampling attached depth forbidden'); return drawColor(this.uniforms); } finally {this.invalidate();this.inFrame=false;this.frame++;} } drawDepth(camera){ const r=this.renderer;const saved={target:r.getRenderTarget(),face:r.getActiveCubeFace?.()||0,mip:r.getActiveMipmapLevel?.()||0,viewport:r.getViewport(new T.Vector4()),scissor:r.getScissor(new T.Vector4()),scissorTest:r.getScissorTest(),clear:r.getClearColor(new T.Color()),alpha:r.getClearAlpha(),auto:r.autoClear,xr:r.xr.enabled,shadow:r.shadowMap.autoUpdate,shadowEnabled:r.shadowMap.enabled,shadowNeedsUpdate:r.shadowMap.needsUpdate,background:this.scene.background,override:this.scene.overrideMaterial}; const members=new Set();this.model.traverse(o=>members.add(o));const restore=[]; try { this.scene.traverse(o=>{if(!o.isMesh&&!o.isLine&&!o.isPoints&&!o.isSprite)return;restore.push([o,o.material,o.visible]);if(!members.has(o)||!o.isMesh){o.visible=false;return;} const list=[].concat(o.material);const depths=list.map(m=>this.material(m)); // Mixed groups retain group order; noncasting groups use invisible depth material. o.material=depths.map(d=>d||this.hiddenDepth); if(!Array.isArray(restore.at(-1)[1]))o.material=o.material[0]; }); if(!this.target){this.target=new T.WebGLRenderTarget(this.size,this.height,{depthBuffer:true,stencilBuffer:false});this.target.scissorTest=false;this.target.texture.minFilter=this.target.texture.magFilter=T.NearestFilter;this.target.depthTexture=new T.DepthTexture(this.size,this.height,T.UnsignedShortType);} this.scene.background=null;this.scene.overrideMaterial=null;r.xr.enabled=false;r.shadowMap.autoUpdate=false;r.shadowMap.enabled=false;r.autoClear=true; this.bound=true;r.setRenderTarget(this.target);r.setClearColor(0xffffff,1);r.clear(true,true,false);r.render(this.scene,camera); } finally { // Restore target BEFORE exposing any depth sampler, even on render exceptions. r.setRenderTarget(saved.target,saved.face,saved.mip);this.bound=false;r.setClearColor(saved.clear,saved.alpha);r.autoClear=saved.auto;r.xr.enabled=saved.xr;r.shadowMap.autoUpdate=saved.shadow;r.shadowMap.enabled=saved.shadowEnabled;r.shadowMap.needsUpdate=saved.shadowNeedsUpdate;this.scene.background=saved.background;this.scene.overrideMaterial=saved.override; for(const [o,m,v]of restore){o.material=m;o.visible=v;} } } dispose(){if(this.disposed)return;this.disposed=true;this.enabled=false;this.invalidate();this.release();this.hiddenDepth.dispose();} } === champions-light-camera.js === import * as T from '../../public/vendor/three.module.js'; // Reproduce offline fitted orthographic depth volume without species constants. // Shared world-space key: upper-left in default left view and Preview Auto. // Direction only; intensity, fill, and Standard lighting are unchanged. export const CHAMPIONS_KEY_DIRECTION = Object.freeze([-5, 7, 2]); export function fitLightCamera(model, viewCamera, eligible=()=>true) { const direction=new T.Vector3(...CHAMPIONS_KEY_DIRECTION).normalize(); const x=new T.Vector3().crossVectors(new T.Vector3(0,1,0),direction).normalize(); if(x.lengthSq()<.5)throw Error('Degenerate light basis'); const y=new T.Vector3().crossVectors(direction,x);const view=new T.Matrix4().set(x.x,x.y,x.z,0,y.x,y.y,y.z,0,direction.x,direction.y,direction.z,0,0,0,0,1); const bounds=new T.Box3(),v=new T.Vector3();let vertices=0; model.traverseVisible(o=>{ if(!o.isMesh||!o.visible||![].concat(o.material).some(m=>eligible(m)&&m.userData?.bakeMetadata?.sourceProperties?.floats?._NoCastSelfShadow!==1))return; o.skeleton?.update();for(let i=0;i