diff --git a/apps/web-console/README.md b/apps/web-console/README.md index 766e8e9..bc4eb27 100755 --- a/apps/web-console/README.md +++ b/apps/web-console/README.md @@ -1,16 +1,15 @@ # Web Console -Web 控制台提供一句话、快捷功能模式与手势控制入口,不在浏览器中生成 CAN。所有动作统一提交给后端编排、配置校验、安全门禁和执行链路。 +Web 控制台是车机端的远程自编排与同步显示界面。网页保留一句话指令和预设功能模式入口,请求通过同源服务发送至车机执行;同时同步显示车机任务、编排结果、设备反馈和 USB 扩展能力。真实 CAN 与硬件执行权限仍由服务端安全门禁控制。 当前页面包括: -- 顶部“自编排 / 自标定 / 自扩展 / 自修复 / 自进化”模块切换;user 进入自标定或自修复时自动切换为 admin,自修复停留期间不能降级为 user;自扩展包含外设学习与统一控制两种工作模式,自进化同时面向 user 与 admin,以版本时间轴、改进证据和下一步计划呈现能力演进过程。 -- 六类外设玩具的添加、红外能力学习、测试发射、单动作执行与本地能力目录。 -- 基于已学习外设能力和车端能力的 GPT 联动计划,车端步骤复用现有安全编排链路。 -- 一句话联动座椅、空调、天幕和氛围灯,支持 Enter 执行和 GPT/本地规则切换。 -- 观影、午休、零重力快捷模式,以及当前副驾驶姿态的命名保存入口。 -- 六阶段执行链路、整车联合孪生、领域状态、配置、CAN 计划和执行结果。 -- 右侧手势控制抽屉,包含摄像头画面、关键点骨架、保持进度、动作速查与自定义映射。 +- 自编排和自扩展合并为一个实时界面,登录身份固定为 `user`,不再提供模块切换。 +- 网页端可输入一句话指令或点击预设模式,车机端同样可发起任务;两端任务与结果统一同步。 +- 整车数字孪生位于工作区中央,点击或悬停热点可查看车窗、遮阳帘、主/副驾座椅、阅读灯、氛围灯、前大灯和空调的完整状态。 +- 车端设备状态与外设能力板块均可独立隐藏或恢复,面板状态在当前浏览器会话中保留。 +- USB 外设接入后同步显示 GSCU 链路、外设名称、类型、已学习能力和最近一次跨设备联动。 +- 左侧运行日志集中显示网页/车机任务、链路、设备与外设同步事件。 UI 只展示可审计的“决策摘要”和“处理轨迹”,不展示模型私有思维过程。 @@ -54,49 +53,12 @@ TCP 模式下本服务是服务器,GSCU1B 是客户端:设备配网页中的 自动重试。`/api/extension/health` 的 `listening` 表示服务器已监听,只有收到 真实设备会话后 `connected`/`peer_connected` 才会变为 `true`。 -## N7 自标定 +车机与网页同步使用以下同源接口: -自标定前端、原始 Android `n7_seat.glb`、四轴 Hall 标定协议以及 -CAN/MQTT/RTSP 后端均由当前服务同源提供,不再启动原 `8766` 工作站或使用 -iframe。左侧“执行目标”复用自编排下拉控件,默认显示“真实台架”,也可以 -切换到“标定仿真台架”。选择目标后仍需显式点击连接,服务启动不会自动打开 -真实 CAN 适配器。 - -标定 API 位于 `/api/calibration/*`,包含状态流、CAN 连接、四轴/单轴标定、 -绝对位置、端点、全轴 STOP、MQTT、RTSP 和连接设置。仿真台架实现同一套 -CRC、ACK、ARM、心跳租约和 STOP 协议边界,并生成双目位姿数据;它与自编排 -的 `dry_run`、`simulated_hardware` 执行模式相互独立。真实 ZLG CAN 连接复用 -仓库现有的 ZCANPRO 32 位 bridge,实机运动接口另外限制为台架本机访问。 - -MQTT 与通用 CAN 依赖可安装为: - -```powershell -python -m pip install -e ".[can,ir]" -``` - -RTSP 画面需要将 `ffmpeg.exe` 加入 `PATH`;未安装 FFmpeg 时,CAN、MQTT、 -标定和 3D 数字孪生不受影响。 - -## 座椅自修复 - -原 `manual_hil` 工程中的六项量产软件故障闭环、硬件支路诊断、72 针连接器 -定义(其中 21 针启用)、ZCANPRO bridge 以及固件资格检查已迁入当前服务, -统一使用 `/api/self-repair/*`,不再启动独立前端或 HTTP 服务。自修复入口始终 -显示;user 点击入口后自动切换为 admin,停留在自修复期间权限选择器锁定。 -后端对所有自修复 API 再次执行 admin 校验,实物诊断、实物故障注入、归零、 -STOP ALL、日志目录和固件操作还要求台架本机决策点。 - -软件自修复默认使用 `shadow`,仅推进内存中的故障注入、AI 诊断、恢复和复测 -状态机,不会写入 ECU。页面左侧显示六项量产故障用例及总体进度,中间程序化 -3D 座椅同步四轴与热管理状态,右侧五节点以深蓝、浅蓝、灰色分别表示已完成、 -进行中和待执行。硬件视图提供 CAN 分层状态、功能支路、JA1/JB1/JC1 物理针脚 -排布与证据详情。 - -所有机器相关路径均通过环境变量配置,完整清单及示例见 -[`config/self-repair/README.md`](../../config/self-repair/README.md)。未配置固件、 -IAR 或 ZCANPRO 路径时,对应实物操作保持禁用;服务导入与启动不会自动拉起 -ZCANPRO。只有显式设置 `SELF_REPAIR_AUTO_START_BRIDGE=true`,或管理员启动 -需要 bridge 的实物操作时,服务才会尝试运行配置的扩展脚本。 +- `GET /api/vehicle-display-sync`:网页轮询最新车机任务、结果、外设目录与扩展链路状态。 +- `POST /api/requests`:车机执行时附带 `client_type: "head_unit"`;网页控制台附带 `client_type: "web_console"`。两类任务的执行结果都会写入同步快照。 +- `POST /api/extension/display-sync`:车机刚识别 USB 外设时上报 `device` 与 `peripherals` 能力目录,无需等待首次执行。 +- `POST /api/extension/assistant/plan` 和 `/api/extension/vehicle/execute`:联动规划与车端执行结果同样写入同步快照。 公网入口由后端统一认证,前端不保存密码或 API Key。未认证访问自动进入 `/login`,主控制台提供退出按钮。固定入口是 diff --git a/apps/web-console/app.js b/apps/web-console/app.js index b0bde15..7e3ce7d 100755 --- a/apps/web-console/app.js +++ b/apps/web-console/app.js @@ -1553,44 +1553,8 @@ const TWIN_THEME_PALETTES = { lampEmissive: 0x16aaa1, lampEdge: 0x096d67, }, - admin: { - accent: 0x315eaa, - accentStrong: 0x234785, - accentSoft: 0xe1e9fa, - sceneBackground: 0xe8eef8, - floor: 0xdfe6f3, - gridStrong: 0x7190c2, - gridSoft: 0xbdc9df, - fillLight: 0xa9bfe4, - vehicleOutline: 0x315eaa, - vehicleOccluded: 0x9eafd0, - seatShell: 0x315eaa, - seatInsert: 0xc9d8f2, - seatThermal: 0x91b2e4, - seatBolster: 0x234785, - seatStructure: 0x1d2f52, - seatEdge: 0x88a9df, - seatSeam: 0xe1e9fa, - glass: 0x477bc4, - glassEmissive: 0x1f427c, - glassEdge: 0x234f91, - glassGlow: 0x86b3ff, - roofClear: 0x7299d5, - roofDark: 0x1d3c72, - lamp: 0x315eaa, - lampEmissive: 0x5688dc, - lampEdge: 0x244a86, - }, }; -function currentTwinThemeRole() { - if (document.body.dataset.module === "self-extension") return "user"; - return document.body.dataset.demoRole === "admin" - || sessionStorage.getItem("cognitive-agent.demo-role") === "admin" - ? "admin" - : "user"; -} - function createTwinGroundTexture(THREE, palette, size = 768) { const textureCanvas = document.createElement("canvas"); textureCanvas.width = size; @@ -1685,11 +1649,10 @@ function applyTwinGroundTheme(twin, palette) { if (previousTexture && previousTexture !== nextTexture) previousTexture.dispose(); } -function applyTwinVehicleTheme(systems, role = currentTwinThemeRole()) { +function applyTwinVehicleTheme(systems) { if (!systems) return; - const themeRole = role === "admin" ? "admin" : "user"; - const palette = TWIN_THEME_PALETTES[themeRole]; - systems.themeRole = themeRole; + const palette = TWIN_THEME_PALETTES.user; + systems.themeRole = "user"; systems.themePalette = palette; systems.colors.roofClear.setHex(palette.roofClear); systems.colors.roofDark.setHex(palette.roofDark); @@ -1774,13 +1737,10 @@ function applyTwinSeatTheme(model, palette) { }); } -function applyTwinSceneTheme(twin, role = currentTwinThemeRole()) { +function applyTwinSceneTheme(twin) { if (!twin) return; - const themeRole = document.body.dataset.module === "self-extension" - ? "user" - : role === "admin" ? "admin" : "user"; - const palette = TWIN_THEME_PALETTES[themeRole]; - applyTwinVehicleTheme(twin.vehicleSystems, themeRole); + const palette = TWIN_THEME_PALETTES.user; + applyTwinVehicleTheme(twin.vehicleSystems); twin.scene.background.setHex(palette.sceneBackground); if (twin.scene.fog?.color) twin.scene.fog.color.setHex(palette.sceneBackground); applyTwinGroundTheme(twin, palette); @@ -1797,11 +1757,11 @@ function applyTwinSceneTheme(twin, role = currentTwinThemeRole()) { } })); // Controllable glass and lamp entities use stronger semantic variants from - // the same role palette after the neutral vehicle outline pass above. - applyTwinVehicleTheme(twin.vehicleSystems, themeRole); + // the same palette after the neutral vehicle outline pass above. + applyTwinVehicleTheme(twin.vehicleSystems); const canvas = twin.renderer?.domElement; if (canvas) { - canvas.dataset.themeRole = themeRole; + canvas.dataset.themeRole = "user"; canvas.dataset.themeAccent = `#${palette.accent.toString(16).padStart(6, "0")}`; } } @@ -3942,9 +3902,6 @@ function initSeatTwin() { pointer: { x: 0, y: 0 }, }; applyTwinSceneTheme(state.seatTwin); - window.addEventListener("cognitive-agent:demo-role-change", (event) => { - applyTwinSceneTheme(state.seatTwin, event.detail?.role); - }); window.addEventListener("cognitive-agent:module-change", () => { applyTwinSceneTheme(state.seatTwin); }); @@ -6495,6 +6452,7 @@ async function submitRequest(event) { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ utterance, + client_type: "web_console", provider: state.provider, conversation_id: state.conversationId, vehicle_id: state.vehicleId || state.runtime?.default_vehicle_id, @@ -6657,6 +6615,17 @@ window.CognitiveAgentConsole = { getResult() { return state.result; }, + applySyncedResult(result, { utterance = "" } = {}) { + if (!result || typeof result !== "object") return false; + if (result.conversation_id) { + state.conversationId = String(result.conversation_id); + sessionStorage.setItem("cognitive-agent.conversation-id", state.conversationId); + } + const input = $("#utterance"); + if (input && utterance && document.activeElement !== input) input.value = String(utterance); + renderResult(result); + return true; + }, notify(message) { showToast(String(message)); }, diff --git a/apps/web-console/assets/models/n7_seat.glb b/apps/web-console/assets/models/n7_seat.glb deleted file mode 100644 index d718356..0000000 Binary files a/apps/web-console/assets/models/n7_seat.glb and /dev/null differ diff --git a/apps/web-console/assets/pets/self-extension-cat-entrance.png b/apps/web-console/assets/pets/self-extension-cat-entrance.png new file mode 100644 index 0000000..e5ed9ce Binary files /dev/null and b/apps/web-console/assets/pets/self-extension-cat-entrance.png differ diff --git a/apps/web-console/assets/pets/self-extension-cat.png b/apps/web-console/assets/pets/self-extension-cat.png new file mode 100644 index 0000000..fb79ed8 Binary files /dev/null and b/apps/web-console/assets/pets/self-extension-cat.png differ diff --git a/apps/web-console/assets/self-calibration-model.bundle.js b/apps/web-console/assets/self-calibration-model.bundle.js deleted file mode 100644 index a615b9e..0000000 --- a/apps/web-console/assets/self-calibration-model.bundle.js +++ /dev/null @@ -1,4113 +0,0 @@ -(()=>{var fi={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},gi={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},rd=0,jl=1,sd=2;var Oi=1,ad=2,Cr=3,_i=0,Gt=1,tn=2,Pn=0,Ls=1,ql=2,Yl=3,Kl=4,od=5;var Pr=100,ld=101,cd=102,hd=103,ud=104,dd=200,pd=201,md=202,fd=203,gd=204,_d=205,vd=206,yd=207,xd=208,Md=209,Sd=210,bd=211,Td=212,Ed=213,Ad=214,Zl=0,Jl=1,$l=2,fo=3,Ql=4,ec=5,tc=6,nc=7,wd=0,Rd=1,Cd=2,fn=0,ic=1,rc=2,sc=3,Ns=4,ac=5,oc=6,lc=7,Pl="attached",Pd="detached",cc=300,Ir=301,Fi=302,go=303,_o=304,Ds=306,hi=1e3,Tn=1001,hr=1002,Nt=1003,vo=1004;var Bi=1005;var vt=1006,Lr=1007;var In=1008;var Yt=1009,hc=1010,uc=1011,Nr=1012,yo=1013,ti=1014,Kt=1015,Ln=1016,xo=1017,Mo=1018,Dr=1020,dc=35902,pc=35899,Id=1021,Ld=1022,nn=1023,vi=1026,zi=1027,So=1028,bo=1029,Gi=1030,mc=1031;var fc=1033,To=33776,Eo=33777,Ao=33778,wo=33779,gc=35840,_c=35841,vc=35842,yc=35843,xc=36196,Mc=37492,Sc=37496,bc=37488,Tc=37489,Ro=37490,Ec=37491,Ac=37808,wc=37809,Rc=37810,Cc=37811,Pc=37812,Ic=37813,Lc=37814,Nc=37815,Dc=37816,Uc=37817,Oc=37818,Fc=37819,Bc=37820,zc=37821,Gc=36492,kc=36494,Vc=36495,Hc=36283,Wc=36284,Co=36285,Xc=36286;var Ci=2300,Pi=2301,ba=2302,Il=2303,Ll=2400,Nl=2401,Dl=2402;var jc=0,Us=1,Ur=2;var qc=0,Nd=1,ki="",lt="srgb",Dt="srgb-linear",Qr="linear",je="srgb";var wi=7680;var Dd=512,Ud=513,Od=514,Po=515,Fd=516,Bd=517,Io=518,zd=519,Ta=35044;var Yc="300 es",qn=2e3,ur=2001;function zp(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function dr(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function Gd(){let r=dr("canvas");return r.style.display="block",r}var pu={},pr=null;function es(...r){let e="THREE."+r.shift();pr?pr("log",e,...r):console.log(e,...r)}function kd(r){let e=r[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=r[1];t&&t.isStackTrace?r[0]+=" "+t.getLocation():r[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return r}function ge(...r){let e="THREE."+(r=kd(r)).shift();if(pr)pr("warn",e,...r);else{let t=r[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...r)}}function we(...r){let e="THREE."+(r=kd(r)).shift();if(pr)pr("error",e,...r);else{let t=r[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...r)}}function Ri(...r){let e=r.join(" ");e in pu||(pu[e]=!0,ge(...r))}function Vd(r,e,t){return new Promise(function(n,i){setTimeout(function s(){switch(r.clientWaitSync(e,r.SYNC_FLUSH_COMMANDS_BIT,0)){case r.WAIT_FAILED:i();break;case r.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}},t)})}var Hd={[Zl]:1,[$l]:6,[Ql]:7,[fo]:5,[Jl]:0,[tc]:2,[nc]:4,[ec]:3},pn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let i=n[e];if(i!==void 0){let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let i=n.slice(0);for(let s=0,a=i.length;s>8&255]+Rt[r>>16&255]+Rt[r>>24&255]+"-"+Rt[255&e]+Rt[e>>8&255]+"-"+Rt[e>>16&15|64]+Rt[e>>24&255]+"-"+Rt[63&t|128]+Rt[t>>8&255]+"-"+Rt[t>>16&255]+Rt[t>>24&255]+Rt[255&n]+Rt[n>>8&255]+Rt[n>>16&255]+Rt[n>>24&255]).toLowerCase()}function Oe(r,e,t){return Math.max(e,Math.min(t,r))}function Ul(r,e){return(r%e+e)%e}function Zr(r,e,t){return(1-t)*r+t*e}function dn(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function Ye(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(4294967295*r);case Uint16Array:return Math.round(65535*r);case Uint8Array:return Math.round(255*r);case Int32Array:return Math.round(2147483647*r);case Int16Array:return Math.round(32767*r);case Int8Array:return Math.round(127*r);default:throw new Error("THREE.MathUtils: Invalid component type.")}}var gn={DEG2RAD:lr,RAD2DEG:Ii,generateUUID:en,clamp:Oe,euclideanModulo:Ul,mapLinear:function(r,e,t,n,i){return n+(r-e)*(i-n)/(t-e)},inverseLerp:function(r,e,t){return r!==e?(t-r)/(e-r):0},lerp:Zr,damp:function(r,e,t,n){return Zr(r,e,1-Math.exp(-t*n))},pingpong:function(r,e=1){return e-Math.abs(Ul(r,2*e)-e)},smoothstep:function(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e))*r*(3-2*r)},smootherstep:function(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e))*r*r*(r*(6*r-15)+10)},randInt:function(r,e){return r+Math.floor(Math.random()*(e-r+1))},randFloat:function(r,e){return r+Math.random()*(e-r)},randFloatSpread:function(r){return r*(.5-Math.random())},seededRandom:function(r){r!==void 0&&(mu=r);let e=mu+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(r){return r*lr},radToDeg:function(r){return r*Ii},isPowerOfTwo:function(r){return!(r&r-1)&&r!==0},ceilPowerOfTwo:function(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))},floorPowerOfTwo:function(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))},setQuaternionFromProperEuler:function(r,e,t,n,i){let s=Math.cos,a=Math.sin,o=s(t/2),c=a(t/2),l=s((e+n)/2),h=a((e+n)/2),u=s((e-n)/2),p=a((e-n)/2),d=s((n-e)/2),f=a((n-e)/2);switch(i){case"XYX":r.set(o*h,c*u,c*p,o*l);break;case"YZY":r.set(c*p,o*h,c*u,o*l);break;case"ZXZ":r.set(c*u,c*p,o*h,o*l);break;case"XZX":r.set(o*h,c*f,c*d,o*l);break;case"YXY":r.set(c*d,o*h,c*f,o*l);break;case"ZYZ":r.set(c*f,c*d,o*h,o*l);break;default:ge("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}},normalize:Ye,denormalize:dn},Qc=class Qc{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Oe(this.x,e.x,t.x),this.y=Oe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Oe(this.x,e,t),this.y=Oe(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Oe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Oe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),i=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*n-a*i+e.x,this.y=s*i+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};Qc.prototype.isVector2=!0;var $=Qc,ct=class{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,s,a,o){let c=n[i+0],l=n[i+1],h=n[i+2],u=n[i+3],p=s[a+0],d=s[a+1],f=s[a+2],m=s[a+3];if(u!==m||c!==p||l!==d||h!==f){let v=c*p+l*d+h*f+u*m;v<0&&(p=-p,d=-d,f=-f,m=-m,v=-v);let g=1-o;if(v<.9995){let _=Math.acos(v),y=Math.sin(_);g=Math.sin(g*_)/y,c=c*g+p*(o=Math.sin(o*_)/y),l=l*g+d*o,h=h*g+f*o,u=u*g+m*o}else{c=c*g+p*o,l=l*g+d*o,h=h*g+f*o,u=u*g+m*o;let _=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=_,l*=_,h*=_,u*=_}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,s,a){let o=n[i],c=n[i+1],l=n[i+2],h=n[i+3],u=s[a],p=s[a+1],d=s[a+2],f=s[a+3];return e[t]=o*f+h*u+c*d-l*p,e[t+1]=c*f+h*p+l*u-o*d,e[t+2]=l*f+h*d+o*p-c*u,e[t+3]=h*f-o*u-c*p-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,i=e._y,s=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),h=o(i/2),u=o(s/2),p=c(n/2),d=c(i/2),f=c(s/2);switch(a){case"XYZ":this._x=p*h*u+l*d*f,this._y=l*d*u-p*h*f,this._z=l*h*f+p*d*u,this._w=l*h*u-p*d*f;break;case"YXZ":this._x=p*h*u+l*d*f,this._y=l*d*u-p*h*f,this._z=l*h*f-p*d*u,this._w=l*h*u+p*d*f;break;case"ZXY":this._x=p*h*u-l*d*f,this._y=l*d*u+p*h*f,this._z=l*h*f+p*d*u,this._w=l*h*u-p*d*f;break;case"ZYX":this._x=p*h*u-l*d*f,this._y=l*d*u+p*h*f,this._z=l*h*f-p*d*u,this._w=l*h*u+p*d*f;break;case"YZX":this._x=p*h*u+l*d*f,this._y=l*d*u+p*h*f,this._z=l*h*f-p*d*u,this._w=l*h*u-p*d*f;break;case"XZY":this._x=p*h*u-l*d*f,this._y=l*d*u-p*h*f,this._z=l*h*f+p*d*u,this._w=l*h*u+p*d*f;break;default:ge("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],s=t[8],a=t[1],o=t[5],c=t[9],l=t[2],h=t[6],u=t[10],p=n+o+u;if(p>0){let d=.5/Math.sqrt(p+1);this._w=.25/d,this._x=(h-c)*d,this._y=(s-l)*d,this._z=(a-i)*d}else if(n>o&&n>u){let d=2*Math.sqrt(1+n-o-u);this._w=(h-c)/d,this._x=.25*d,this._y=(i+a)/d,this._z=(s+l)/d}else if(o>u){let d=2*Math.sqrt(1+o-n-u);this._w=(s-l)/d,this._x=(i+a)/d,this._y=.25*d,this._z=(c+h)/d}else{let d=2*Math.sqrt(1+u-n-o);this._w=(a-i)/d,this._x=(s+l)/d,this._y=(c+h)/d,this._z=.25*d}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Oe(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,i=e._y,s=e._z,a=e._w,o=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+a*o+i*l-s*c,this._y=i*h+a*c+s*o-n*l,this._z=s*h+a*l+n*c-i*o,this._w=a*h-n*o-i*c-s*l,this._onChangeCallback(),this}slerp(e,t){let n=e._x,i=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,i=-i,s=-s,a=-a,o=-o);let c=1-t;if(o<.9995){let l=Math.acos(o),h=Math.sin(l);c=Math.sin(c*l)/h,t=Math.sin(t*l)/h,this._x=this._x*c+n*t,this._y=this._y*c+i*t,this._z=this._z*c+s*t,this._w=this._w*c+a*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+i*t,this._z=this._z*c+s*t,this._w=this._w*c+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},eh=class eh{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(fu.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(fu.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*i,this.y=s[1]*t+s[4]*n+s[7]*i,this.z=s[2]*t+s[5]*n+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=e.elements,a=1/(s[3]*t+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*i+s[12])*a,this.y=(s[1]*t+s[5]*n+s[9]*i+s[13])*a,this.z=(s[2]*t+s[6]*n+s[10]*i+s[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,s=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*i-o*n),h=2*(o*t-s*i),u=2*(s*n-a*t);return this.x=t+c*l+a*u-o*h,this.y=n+c*h+o*l-s*u,this.z=i+c*u+s*h-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i,this.y=s[1]*t+s[5]*n+s[9]*i,this.z=s[2]*t+s[6]*n+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Oe(this.x,e.x,t.x),this.y=Oe(this.y,e.y,t.y),this.z=Oe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Oe(this.x,e,t),this.y=Oe(this.y,e,t),this.z=Oe(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Oe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,i=e.y,s=e.z,a=t.x,o=t.y,c=t.z;return this.x=i*c-s*o,this.y=s*a-n*c,this.z=n*o-i*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Qo.copy(this).projectOnVector(e),this.sub(Qo)}reflect(e){return this.sub(Qo.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Oe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=2*Math.random()-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};eh.prototype.isVector3=!0;var A=eh,Qo=new A,fu=new ct,th=class th{constructor(e,t,n,i,s,a,o,c,l){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,a,o,c,l)}set(e,t,n,i,s,a,o,c,l){let h=this.elements;return h[0]=e,h[1]=i,h[2]=o,h[3]=t,h[4]=s,h[5]=c,h[6]=n,h[7]=a,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],h=n[4],u=n[7],p=n[2],d=n[5],f=n[8],m=i[0],v=i[3],g=i[6],_=i[1],y=i[4],S=i[7],T=i[2],M=i[5],P=i[8];return s[0]=a*m+o*_+c*T,s[3]=a*v+o*y+c*M,s[6]=a*g+o*S+c*P,s[1]=l*m+h*_+u*T,s[4]=l*v+h*y+u*M,s[7]=l*g+h*S+u*P,s[2]=p*m+d*_+f*T,s[5]=p*v+d*y+f*M,s[8]=p*g+d*S+f*P,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8];return t*a*h-t*o*l-n*s*h+n*o*c+i*s*l-i*a*c}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],u=h*a-o*l,p=o*c-h*s,d=l*s-a*c,f=t*u+n*p+i*d;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/f;return e[0]=u*m,e[1]=(i*l-h*n)*m,e[2]=(o*n-i*a)*m,e[3]=p*m,e[4]=(h*t-i*c)*m,e[5]=(i*s-o*t)*m,e[6]=d*m,e[7]=(n*c-l*t)*m,e[8]=(a*t-n*s)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,s,a,o){let c=Math.cos(s),l=Math.sin(s);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-i*l,i*c,-i*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return Ri("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(el.makeScale(e,t)),this}rotate(e){return Ri("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(el.makeRotation(-e)),this}translate(e,t){return Ri("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(el.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}};th.prototype.isMatrix3=!0;var Ne=th,el=new Ne,gu=new Ne().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),_u=new Ne().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Gp(){let r={enabled:!0,workingColorSpace:Dt,spaces:{},convert:function(i,s,a){return this.enabled!==!1&&s!==a&&s&&a&&(this.spaces[s].transfer===je&&(i.r=jn(i.r),i.g=jn(i.g),i.b=jn(i.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(i.applyMatrix3(this.spaces[s].toXYZ),i.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===je&&(i.r=cr(i.r),i.g=cr(i.g),i.b=cr(i.b))),i},workingToColorSpace:function(i,s){return this.convert(i,this.workingColorSpace,s)},colorSpaceToWorking:function(i,s){return this.convert(i,s,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===""?Qr:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,s=this.workingColorSpace){return i.fromArray(this.spaces[s].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,s,a){return i.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,s){return Ri("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),r.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return Ri("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),r.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return r.define({[Dt]:{primaries:e,whitePoint:n,transfer:Qr,toXYZ:gu,fromXYZ:_u,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:lt},outputColorSpaceConfig:{drawingBufferColorSpace:lt}},[lt]:{primaries:e,whitePoint:n,transfer:je,toXYZ:gu,fromXYZ:_u,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:lt}}}),r}var ze=Gp();function jn(r){return r<.04045?.0773993808*r:Math.pow(.9478672986*r+.0521327014,2.4)}function cr(r){return r<.0031308?12.92*r:1.055*Math.pow(r,.41666)-.055}var Ki,Ea=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Ki===void 0&&(Ki=dr("canvas")),Ki.width=e.width,Ki.height=e.height;let i=Ki.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=Ki}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=dr("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),s=i.data;for(let a=0;a1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(nl).x}get height(){return this.source.getSize(nl).y}get depth(){return this.source.getSize(nl).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){ge(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];i!==void 0?i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n:ge(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==cc)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case hi:e.x=e.x-Math.floor(e.x);break;case Tn:e.x=e.x<0?0:1;break;case hr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case hi:e.y=e.y-Math.floor(e.y);break;case Tn:e.y=e.y<0?0:1;break;case hr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Et.DEFAULT_IMAGE=null,Et.DEFAULT_MAPPING=cc,Et.DEFAULT_ANISOTROPY=1;var nh=class nh{constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*i+a[12]*s,this.y=a[1]*t+a[5]*n+a[9]*i+a[13]*s,this.z=a[2]*t+a[6]*n+a[10]*i+a[14]*s,this.w=a[3]*t+a[7]*n+a[11]*i+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,s,c=e.elements,l=c[0],h=c[4],u=c[8],p=c[1],d=c[5],f=c[9],m=c[2],v=c[6],g=c[10];if(Math.abs(h-p)<.01&&Math.abs(u-m)<.01&&Math.abs(f-v)<.01){if(Math.abs(h+p)<.1&&Math.abs(u+m)<.1&&Math.abs(f+v)<.1&&Math.abs(l+d+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let y=(l+1)/2,S=(d+1)/2,T=(g+1)/2,M=(h+p)/4,P=(u+m)/4,O=(f+v)/4;return y>S&&y>T?y<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(y),i=M/n,s=P/n):S>T?S<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(S),n=M/i,s=O/i):T<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(T),n=P/s,i=O/s),this.set(n,i,s,t),this}let _=Math.sqrt((v-f)*(v-f)+(u-m)*(u-m)+(p-h)*(p-h));return Math.abs(_)<.001&&(_=1),this.x=(v-f)/_,this.y=(u-m)/_,this.z=(p-h)/_,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Oe(this.x,e.x,t.x),this.y=Oe(this.y,e.y,t.y),this.z=Oe(this.z,e.z,t.z),this.w=Oe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Oe(this.x,e,t),this.y=Oe(this.y,e,t),this.z=Oe(this.z,e,t),this.w=Oe(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Oe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};nh.prototype.isVector4=!0;var Ke=nh,Aa=class extends pn{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:vt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ke(0,0,e,t),this.scissorTest=!1,this.viewport=new Ke(0,0,e,t),this.textures=[];let i={width:e,height:t,depth:n.depth},s=new Et(i),a=n.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null&&(i.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let c=o.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l0){i.children=[];for(let o=0;o0){i.animations=[];for(let o=0;o0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),p.length>0&&(n.skeletons=p),d.length>0&&(n.animations=d),f.length>0&&(n.nodes=f)}return n.object=i,n;function a(o){let c=[];for(let l in o){let h=o[l];delete h.metadata,c.push(h)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;nd+f?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&p<=d-f&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1,c.eventsEnabled&&c.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Kp)))}return o!==null&&(o.visible=i!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Wt;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},Wd={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},si={h:0,s:0,l:0},Ys={h:0,s:0,l:0};function rl(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+6*(e-r)*t:t<.5?e:t<2/3?r+6*(e-r)*(2/3-t):r}var Te=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=lt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,ze.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=ze.workingColorSpace){return this.r=e,this.g=t,this.b=n,ze.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=ze.workingColorSpace){if(e=Ul(e,1),t=Oe(t,0,1),n=Oe(n,0,1),t===0)this.r=this.g=this.b=n;else{let s=n<=.5?n*(1+t):n+t-n*t,a=2*n-s;this.r=rl(a,s,e+1/3),this.g=rl(a,s,e),this.b=rl(a,s,e-1/3)}return ze.colorSpaceToWorking(this,i),this}setStyle(e,t=lt){function n(s){s!==void 0&&parseFloat(s)<1&&ge("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:ge("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=i[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);ge("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=lt){let n=Wd[e.toLowerCase()];return n!==void 0?this.setHex(n,t):ge("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=jn(e.r),this.g=jn(e.g),this.b=jn(e.b),this}copyLinearToSRGB(e){return this.r=cr(e.r),this.g=cr(e.g),this.b=cr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=lt){return ze.workingToColorSpace(Ct.copy(this),e),65536*Math.round(Oe(255*Ct.r,0,255))+256*Math.round(Oe(255*Ct.g,0,255))+Math.round(Oe(255*Ct.b,0,255))}getHexString(e=lt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ze.workingColorSpace){ze.workingToColorSpace(Ct.copy(this),t);let n=Ct.r,i=Ct.g,s=Ct.b,a=Math.max(n,i,s),o=Math.min(n,i,s),c,l,h=(o+a)/2;if(o===a)c=0,l=0;else{let u=a-o;switch(l=h<=.5?u/(a+o):u/(2-a-o),a){case n:c=(i-s)/u+(i0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},hn=new A,Bn=new A,sl=new A,zn=new A,Qi=new A,er=new A,Eu=new A,al=new A,ol=new A,ll=new A,cl=new Ke,hl=new Ke,ul=new Ke,Hn=class r{constructor(e=new A,t=new A,n=new A){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),hn.subVectors(e,t),i.cross(hn);let s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,n,i,s){hn.subVectors(i,t),Bn.subVectors(n,t),sl.subVectors(e,t);let a=hn.dot(hn),o=hn.dot(Bn),c=hn.dot(sl),l=Bn.dot(Bn),h=Bn.dot(sl),u=a*l-o*o;if(u===0)return s.set(0,0,0),null;let p=1/u,d=(l*c-o*h)*p,f=(a*h-o*c)*p;return s.set(1-d-f,f,d)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,zn)!==null&&zn.x>=0&&zn.y>=0&&zn.x+zn.y<=1}static getInterpolation(e,t,n,i,s,a,o,c){return this.getBarycoord(e,t,n,i,zn)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,zn.x),c.addScaledVector(a,zn.y),c.addScaledVector(o,zn.z),c)}static getInterpolatedAttribute(e,t,n,i,s,a){return cl.setScalar(0),hl.setScalar(0),ul.setScalar(0),cl.fromBufferAttribute(e,t),hl.fromBufferAttribute(e,n),ul.fromBufferAttribute(e,i),a.setScalar(0),a.addScaledVector(cl,s.x),a.addScaledVector(hl,s.y),a.addScaledVector(ul,s.z),a}static isFrontFacing(e,t,n,i){return hn.subVectors(n,t),Bn.subVectors(e,t),hn.cross(Bn).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return hn.subVectors(this.c,this.b),Bn.subVectors(this.a,this.b),.5*hn.cross(Bn).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return r.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return r.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,s){return r.getInterpolation(e,this.a,this.b,this.c,t,n,i,s)}containsPoint(e){return r.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return r.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,s=this.c,a,o;Qi.subVectors(i,n),er.subVectors(s,n),al.subVectors(e,n);let c=Qi.dot(al),l=er.dot(al);if(c<=0&&l<=0)return t.copy(n);ol.subVectors(e,i);let h=Qi.dot(ol),u=er.dot(ol);if(h>=0&&u<=h)return t.copy(i);let p=c*u-h*l;if(p<=0&&c>=0&&h<=0)return a=c/(c-h),t.copy(n).addScaledVector(Qi,a);ll.subVectors(e,s);let d=Qi.dot(ll),f=er.dot(ll);if(f>=0&&d<=f)return t.copy(s);let m=d*l-c*f;if(m<=0&&l>=0&&f<=0)return o=l/(l-f),t.copy(n).addScaledVector(er,o);let v=h*f-d*u;if(v<=0&&u-h>=0&&d-f>=0)return Eu.subVectors(s,i),o=(u-h)/(u-h+(d-f)),t.copy(i).addScaledVector(Eu,o);let g=1/(v+m+p);return a=m*g,o=p*g,t.copy(n).addScaledVector(Qi,a).addScaledVector(er,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Ut=class{constructor(e=new A(1/0,1/0,1/0),t=new A(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,un),un.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Vr),Zs.subVectors(this.max,Vr),tr.subVectors(e.a,Vr),nr.subVectors(e.b,Vr),ir.subVectors(e.c,Vr),ai.subVectors(nr,tr),oi.subVectors(ir,nr),bi.subVectors(tr,ir);let t=[0,-ai.z,ai.y,0,-oi.z,oi.y,0,-bi.z,bi.y,ai.z,0,-ai.x,oi.z,0,-oi.x,bi.z,0,-bi.x,-ai.y,ai.x,0,-oi.y,oi.x,0,-bi.y,bi.x,0];return!!dl(t,tr,nr,ir,Zs)&&(t=[1,0,0,0,1,0,0,0,1],!!dl(t,tr,nr,ir,Zs)&&(Js.crossVectors(ai,oi),t=[Js.x,Js.y,Js.z],dl(t,tr,nr,ir,Zs)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,un).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(un).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Gn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Gn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Gn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Gn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Gn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Gn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Gn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Gn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Gn)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Gn=[new A,new A,new A,new A,new A,new A,new A,new A],un=new A,Ks=new Ut,tr=new A,nr=new A,ir=new A,ai=new A,oi=new A,bi=new A,Vr=new A,Zs=new A,Js=new A,Ti=new A;function dl(r,e,t,n,i){for(let s=0,a=r.length-3;s<=a;s+=3){Ti.fromArray(r,s);let o=i.x*Math.abs(Ti.x)+i.y*Math.abs(Ti.y)+i.z*Math.abs(Ti.z),c=e.dot(Ti),l=t.dot(Ti),h=n.dot(Ti);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>o)return!1}return!0}var Fg=Zp();function Zp(){let r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),n=new Uint32Array(512),i=new Uint32Array(512);for(let c=0;c<256;++c){let l=c-127;l<-27?(n[c]=0,n[256|c]=32768,i[c]=24,i[256|c]=24):l<-14?(n[c]=1024>>-l-14,n[256|c]=1024>>-l-14|32768,i[c]=-l-1,i[256|c]=-l-1):l<=15?(n[c]=l+15<<10,n[256|c]=l+15<<10|32768,i[c]=13,i[256|c]=13):l<128?(n[c]=31744,n[256|c]=64512,i[c]=24,i[256|c]=24):(n[c]=31744,n[256|c]=64512,i[c]=13,i[256|c]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;!(8388608&l);)l<<=1,h-=8388608;l&=-8388609,h+=947912704,s[c]=l|h}for(let c=1024;c<2048;++c)s[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)a[c]=c<<23;a[31]=1199570944,a[32]=2147483648;for(let c=33;c<63;++c)a[c]=2147483648+(c-32<<23);a[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(o[c]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:i,mantissaTable:s,exponentTable:a,offsetTable:o}}var ft=new A,$s=new $,Jp=0,_t=class extends pn{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Jp++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Ta,this.updateRanges=[],this.gpuType=Kt,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,s=this.itemSize;ithis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Hr.subVectors(e,this.center);let t=Hr.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=.5*(n-this.radius);this.center.addScaledVector(Hr,i/n),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(pl.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Hr.copy(e.center).add(pl)),this.expandByPoint(Hr.copy(e.center).sub(pl))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},Qp=0,$t=new be,ml=new tt,rr=new A,Ht=new Ut,Wr=new Ut,Tt=new A,Ze=class r extends pn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Qp++}),this.uuid=en(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new((function(t){for(let n=t.length-1;n>=0;--n)if(t[n]>=65535)return!0;return!1})(e)?ss:rs)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let s=new Ne().getNormalMatrix(e);n.applyNormalMatrix(s),n.needsUpdate=!0}let i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return $t.makeRotationFromQuaternion(e),this.applyMatrix4($t),this}rotateX(e){return $t.makeRotationX(e),this.applyMatrix4($t),this}rotateY(e){return $t.makeRotationY(e),this.applyMatrix4($t),this}rotateZ(e){return $t.makeRotationZ(e),this.applyMatrix4($t),this}translate(e,t,n){return $t.makeTranslation(e,t,n),this.applyMatrix4($t),this}scale(e,t,n){return $t.makeScale(e,t,n),this.applyMatrix4($t),this}lookAt(e){return ml.lookAt(e),ml.updateMatrix(),this.applyMatrix4(ml.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(rr).negate(),this.translate(rr.x,rr.y,rr.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let i=0,s=e.length;it.count&&ge("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ut);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return we("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new A(-1/0,-1/0,-1/0),new A(1/0,1/0,1/0));if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let c=this.parameters;for(let l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let c in n){let l=n[c];e.data.attributes[c]=l.toJSON(e.data)}let i={},s=!1;for(let c in this.morphAttributes){let l=this.morphAttributes[c],h=[];for(let u=0,p=l.length;u0&&(i[c]=h,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let i=e.attributes;for(let l in i){let h=i[l];this.setAttribute(l,h.clone(t))}let s=e.morphAttributes;for(let l in s){let h=[],u=s[l];for(let p=0,d=u.length;p0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){ge(`Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];i!==void 0?i&&i.isColor?i.set(n):i&&i.isVector2&&n&&n.isVector2||i&&i.isEuler&&n&&n.isEuler||i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:ge(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(s){let a=[];for(let o in s){let c=s[o];delete c.metadata,a.push(c)}return a}if(n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==wi&&(n.stencilFail=this.stencilFail),this.stencilZFail!==wi&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==wi&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){let s=i(e.textures),a=i(e.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new Te().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let n=e.normalScale;Array.isArray(n)===!1&&(n=[n,n]),this.normalScale=new $().fromArray(n)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new $().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let i=t.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}};var Bg=new A,zg=new A,Gg=new A,kg=new $,Vg=new $,Hg=new be,Wg=new A,Xg=new A,jg=new A,qg=new $,Yg=new $,Kg=new $;var Zg=new A,Jg=new A;var kn=new A,fl=new A,Qs=new A,li=new A,gl=new A,ea=new A,_l=new A,Kn=class{constructor(e=new A,t=new A(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,kn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=kn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(kn.copy(this.origin).addScaledVector(this.direction,t),kn.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){fl.copy(e).add(t).multiplyScalar(.5),Qs.copy(t).sub(e).normalize(),li.copy(this.origin).sub(fl);let s=.5*e.distanceTo(t),a=-this.direction.dot(Qs),o=li.dot(this.direction),c=-li.dot(Qs),l=li.lengthSq(),h=Math.abs(1-a*a),u,p,d,f;if(h>0)if(u=a*c-o,p=a*o-c,f=s*h,u>=0)if(p>=-f)if(p<=f){let m=1/h;u*=m,p*=m,d=u*(u+a*p+2*o)+p*(a*u+p+2*c)+l}else p=s,u=Math.max(0,-(a*p+o)),d=-u*u+p*(p+2*c)+l;else p=-s,u=Math.max(0,-(a*p+o)),d=-u*u+p*(p+2*c)+l;else p<=-f?(u=Math.max(0,-(-a*s+o)),p=u>0?-s:Math.min(Math.max(-s,-c),s),d=-u*u+p*(p+2*c)+l):p<=f?(u=0,p=Math.min(Math.max(-s,-c),s),d=p*(p+2*c)+l):(u=Math.max(0,-(a*s+o)),p=u>0?s:Math.min(Math.max(-s,-c),s),d=-u*u+p*(p+2*c)+l);else p=a>0?-s:s,u=Math.max(0,-(a*p+o)),d=-u*u+p*(p+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(fl).addScaledVector(Qs,p),d}intersectSphere(e,t){kn.subVectors(e.center,this.origin);let n=kn.dot(this.direction),i=kn.dot(kn)-n*n,s=e.radius*e.radius;if(i>s)return null;let a=Math.sqrt(s-i),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0?!0:e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,s,a,o,c,l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,p=this.origin;return l>=0?(n=(e.min.x-p.x)*l,i=(e.max.x-p.x)*l):(n=(e.max.x-p.x)*l,i=(e.min.x-p.x)*l),h>=0?(s=(e.min.y-p.y)*h,a=(e.max.y-p.y)*h):(s=(e.max.y-p.y)*h,a=(e.min.y-p.y)*h),n>a||s>i?null:((s>n||isNaN(n))&&(n=s),(a=0?(o=(e.min.z-p.z)*u,c=(e.max.z-p.z)*u):(o=(e.max.z-p.z)*u,c=(e.min.z-p.z)*u),n>c||o>i?null:((o>n||n!=n)&&(n=o),(c=0?n:i,t)))}intersectsBox(e){return this.intersectBox(e,kn)!==null}intersectTriangle(e,t,n,i,s){gl.subVectors(t,e),ea.subVectors(n,e),_l.crossVectors(gl,ea);let a,o=this.direction.dot(_l);if(o>0){if(i)return null;a=1}else{if(!(o<0))return null;a=-1,o=-o}li.subVectors(this.origin,e);let c=a*this.direction.dot(ea.crossVectors(li,ea));if(c<0)return null;let l=a*this.direction.dot(gl.cross(li));if(l<0||c+l>o)return null;let h=-a*li.dot(_l);return h<0?null:this.at(h/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},mn=class extends Bt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Te(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Au=new be,Ei=new Kn,ta=new Ot,wu=new A,na=new A,ia=new A,ra=new A,vl=new A,sa=new A,Ru=new A,aa=new A,ht=class extends tt{constructor(e=new Ze,t=new mn){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,s=n.length;i(e.far-e.near)**2))return;Au.copy(s).invert(),Ei.copy(e.ray).applyMatrix4(Au),n.boundingBox!==null&&Ei.intersectsBox(n.boundingBox)===!1||this._computeIntersections(e,t,Ei)}}_computeIntersections(e,t,n){let i,s=this.geometry,a=this.material,o=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,p=s.groups,d=s.drawRange;if(o!==null)if(Array.isArray(a))for(let f=0,m=p.length;fd.far?null:{distance:S,point:aa.clone(),object:u}})(r,e,t,n,na,ia,ra,Ru);if(h){let u=new A;Hn.getBarycoord(Ru,na,ia,ra,u),i&&(h.uv=Hn.getInterpolatedAttribute(i,o,c,l,u,new $)),s&&(h.uv1=Hn.getInterpolatedAttribute(s,o,c,l,u,new $)),a&&(h.normal=Hn.getInterpolatedAttribute(a,o,c,l,u,new A),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let p={a:o,b:c,c:l,normal:new A,materialIndex:0};Hn.getNormal(na,ia,ra,p.normal),h.face=p,h.barycoord=u}return h}var Xr=new Ke,Cu=new Ke,Pu=new Ke,tm=new Ke,Iu=new be,la=new A,yl=new Ot,Lu=new be,xl=new Kn,as=class extends ht{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Pl,this.bindMatrix=new be,this.bindMatrixInverse=new be,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Ut),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n1)?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||sm.getNormalMatrix(e),i=this.coplanarPoint(Ml).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Ai=new Ot,am=new $(.5,.5),ha=new A,Zn=class{constructor(e=new Qt,t=new Qt,n=new Qt,i=new Qt,s=new Qt,a=new Qt){this.planes=[e,t,n,i,s,a]}set(e,t,n,i,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){let i=this.planes,s=e.elements,a=s[0],o=s[1],c=s[2],l=s[3],h=s[4],u=s[5],p=s[6],d=s[7],f=s[8],m=s[9],v=s[10],g=s[11],_=s[12],y=s[13],S=s[14],T=s[15];if(i[0].setComponents(l-a,d-h,g-f,T-_).normalize(),i[1].setComponents(l+a,d+h,g+f,T+_).normalize(),i[2].setComponents(l+o,d+u,g+m,T+y).normalize(),i[3].setComponents(l-o,d-u,g-m,T-y).normalize(),n)i[4].setComponents(c,p,v,S).normalize(),i[5].setComponents(l-c,d-p,g-v,T-S).normalize();else if(i[4].setComponents(l-c,d-p,g-v,T-S).normalize(),t===qn)i[5].setComponents(l+c,d+p,g+v,T+S).normalize();else{if(t!==ur)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(c,p,v,S).normalize()}return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ai.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ai.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ai)}intersectsSprite(e){Ai.center.set(0,0,0);let t=am.distanceTo(e.center);return Ai.radius=.7071067811865476+t,Ai.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ai)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)0?e.max.x:e.min.x,ha.y=i.normal.y>0?e.max.y:e.min.y,ha.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ha)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Ou=new be,Ra=class r{constructor(){this.coordinateSystem=qn,this._frustums=[],this._count=0}setFromArrayCamera(e){let t=e.cameras,n=this._frustums;for(let i=0;i=s.length&&s.push({start:-1,count:-1,z:-1,index:-1});let o=s[this.index];a.push(o),this.index++,o.start=e,o.count=t,o.z=n,o.index=i}reset(){this.list.length=0,this.index=0}},$g=new be,Qg=new Te(1,1,1),e_=new Zn,t_=new Ra,n_=new Ut,i_=new Ot,r_=new A,s_=new A,a_=new A,o_=new Ol,l_=new ht;var xr=class extends Bt{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Te(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},Ca=new A,Pa=new A,Fu=new be,Yr=new Kn,ua=new Ot,Sl=new A,Bu=new A,Li=class extends tt{constructor(e=new Ze,t=new xr){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let i=1,s=t.count;i0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,s=n.length;in)return;Sl.applyMatrix4(r.matrixWorld);let c=e.ray.origin.distanceTo(Sl);return ce.far?void 0:{distance:c,point:Bu.clone().applyMatrix4(r.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:r}}var zu=new A,Gu=new A,cs=class extends Li{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let i=0,s=t.count;i0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,s=n.length;ii.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}var ds=class extends Et{constructor(e=[],t=301,n,i,s,a,o,c,l,h){super(e,t,n,i,s,a,o,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}};var Jn=class extends Et{constructor(e,t,n=1014,i,s,a,o=1003,c=1003,l,h=1026,u=1){if(h!==vi&&h!==1027)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},i,s,a,o,c,h,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new mr(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},Ia=class extends Jn{constructor(e,t=1014,n=301,i,s,a=1003,o=1003,c,l=1026){let h={width:e,height:e,depth:1},u=[h,h,h,h,h,h];super(e,e,t,n,i,s,a,o,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},ps=class extends Et{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},En=class r extends Ze{constructor(e=1,t=1,n=1,i=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:s,depthSegments:a};let o=this;i=Math.floor(i),s=Math.floor(s),a=Math.floor(a);let c=[],l=[],h=[],u=[],p=0,d=0;function f(m,v,g,_,y,S,T,M,P,O,I){let N=S/P,k=T/O,F=S/2,X=T/2,H=M/2,z=P+1,Y=O+1,W=0,ne=0,de=new A;for(let Ee=0;Ee0?1:-1,h.push(de.x,de.y,de.z),u.push(ve/P),u.push(1-Ee/O),W+=1}}for(let Ee=0;Ee0){let I=(_-1)*m;for(let N=0;N0||O!==0)&&(h.push(I,N,F),T+=3),(t>0||O!==s-1)&&(h.push(N,k,F),T+=3)}l.addGroup(g,T,0),g+=T})(),a===!1&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(h),this.setAttribute("position",new Ae(u,3)),this.setAttribute("normal",new Ae(p,3)),this.setAttribute("uv",new Ae(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}},Da=class r extends ms{constructor(e=1,t=1,n=32,i=1,s=!1,a=0,o=2*Math.PI){super(0,e,t,n,i,s,a,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:s,thetaStart:a,thetaLength:o}}static fromJSON(e){return new r(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}},di=class r extends Ze{constructor(e=[],t=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:i};let s=[],a=[];function o(d,f,m,v){let g=v+1,_=[];for(let y=0;y<=g;y++){_[y]=[];let S=d.clone().lerp(m,y/g),T=f.clone().lerp(m,y/g),M=g-y;for(let P=0;P<=M;P++)_[y][P]=P===0&&y===g?S:S.clone().lerp(T,P/M)}for(let y=0;y.9&&y<.1&&(m<.2&&(a[f+0]+=1),v<.2&&(a[f+2]+=1),g<.2&&(a[f+4]+=1))}})()})(),this.setAttribute("position",new Ae(s,3)),this.setAttribute("normal",new Ae(s.slice(),3)),this.setAttribute("uv",new Ae(a,2)),i===0?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.vertices,e.indices,e.radius,e.detail)}},Ua=class r extends di{constructor(e=1,t=0){let n=(1+Math.sqrt(5))/2,i=1/n;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new r(e.radius,e.detail)}},fa=new A,ga=new A,bl=new A,_a=new Hn,Oa=class extends Ze{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},e!==null){let i=Math.pow(10,4),s=Math.cos(lr*t),a=e.getIndex(),o=e.getAttribute("position"),c=a?a.count:o.count,l=[0,0,0],h=["a","b","c"],u=new Array(3),p={},d=[];for(let f=0;f0)){l=i;break}l=i-1}if(i=l,n[i]===a)return i/(s-1);let h=n[i];return(i+(a-h)/(n[i+1]-h))/(s-1)}getTangent(e,t){let i=e-1e-4,s=e+1e-4;i<0&&(i=0),s>1&&(s=1);let a=this.getPoint(i),o=this.getPoint(s),c=t||(a.isVector2?new $:new A);return c.copy(o).sub(a).normalize(),c}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){let n=new A,i=[],s=[],a=[],o=new A,c=new be;for(let d=0;d<=e;d++){let f=d/e;i[d]=this.getTangentAt(f,new A)}s[0]=new A,a[0]=new A;let l=Number.MAX_VALUE,h=Math.abs(i[0].x),u=Math.abs(i[0].y),p=Math.abs(i[0].z);h<=l&&(l=h,n.set(1,0,0)),u<=l&&(l=u,n.set(0,1,0)),p<=l&&n.set(0,0,1),o.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],o),a[0].crossVectors(i[0],s[0]);for(let d=1;d<=e;d++){if(s[d]=s[d-1].clone(),a[d]=a[d-1].clone(),o.crossVectors(i[d-1],i[d]),o.length()>Number.EPSILON){o.normalize();let f=Math.acos(Oe(i[d-1].dot(i[d]),-1,1));s[d].applyMatrix4(c.makeRotationAxis(o,f))}a[d].crossVectors(i[d],s[d])}if(t===!0){let d=Math.acos(Oe(s[0].dot(s[e]),-1,1));d/=e,i[0].dot(o.crossVectors(s[0],s[e]))>0&&(d=-d);for(let f=1;f<=e;f++)s[f].applyMatrix4(c.makeRotationAxis(i[f],d*f)),a[f].crossVectors(i[f],s[f])}return{tangents:i,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},Sr=class extends jt{constructor(e=0,t=0,n=1,i=1,s=0,a=2*Math.PI,o=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=c}getPoint(e,t=new $){let n=t,i=2*Math.PI,s=this.aEndAngle-this.aStartAngle,a=Math.abs(s)i;)s-=i;s0?0:(Math.floor(Math.abs(l)/s)+1)*s:h===0&&l===s-1&&(l=s-2,h=1),this.closed||l>0?o=i[(l-1)%s]:(Wu.subVectors(i[0],i[1]).add(i[0]),o=Wu);let u=i[l%s],p=i[(l+1)%s];if(this.closed||l+2i.length-2?i.length-1:a+1],u=i[a>i.length-3?i.length-1:a+2];return n.set(Xu(o,c.x,l.x,h.x,u.x),Xu(o,c.y,l.y,h.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){let a=i[s]-n,o=this.curves[s],c=o.getLength(),l=c===0?0:1-a/c;return o.getPointAt(l,t)}s++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let n=0,i=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){let u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);let h=l.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},Ms=class extends xs{constructor(e){super(e),this.uuid=en(),this.type="Shape",this.holes=[]}getPointsHoles(e){let t=[];for(let n=0,i=this.holes.length;n80*t){o=r[0],c=r[1];let h=o,u=c;for(let p=t;ph&&(h=d),f>u&&(u=f)}l=Math.max(h-o,u-c),l=l!==0?32767/l:0}return Ss(s,a,t,o,c,l,0),a}function ju(r,e,t,n,i){let s;if(i===(function(a,o,c,l){let h=0;for(let u=o,p=c-l;u0)for(let a=e;a=e;a-=n)s=qu(a/n|0,r[a],r[a+1],s);return s&&br(s,s.next)&&(Ts(s),s=s.next),s}function Ni(r,e){if(!r)return r;e||(e=r);let t,n=r;do if(t=!1,n.steiner||!br(n,n.next)&&st(n.prev,n,n.next)!==0)n=n.next;else{if(Ts(n),n=e=n.prev,n===n.next)break;t=!0}while(t||n!==e);return e}function Ss(r,e,t,n,i,s,a){if(!r)return;!a&&s&&(function(c,l,h,u){let p=c;do p.z===0&&(p.z=Bl(p.x,p.y,l,h,u)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next;while(p!==c);p.prevZ.nextZ=null,p.prevZ=null,(function(d){let f,m=1;do{let v,g=d;d=null;let _=null;for(f=0;g;){f++;let y=g,S=0;for(let M=0;M0||T>0&&y;)S!==0&&(T===0||!y||g.z<=y.z)?(v=g,g=g.nextZ,S--):(v=y,y=y.nextZ,T--),_?_.nextZ=v:d=v,v.prevZ=_,_=v;g=y}_.nextZ=null,m*=2}while(f>1)})(p)})(r,n,i,s);let o=r;for(;r.prev!==r.next;){let c=r.prev,l=r.next;if(s?cm(r,n,i,s):lm(r))e.push(c.i,r.i,l.i),Ts(r),r=l.next,o=l.next;else if((r=l)===o){a?a===1?Ss(r=hm(Ni(r),e),e,t,n,i,s,2):a===2&&um(r,e,t,n,i,s):Ss(Ni(r),e,t,n,i,s,1);break}}}function lm(r){let e=r.prev,t=r,n=r.next;if(st(e,t,n)>=0)return!1;let i=e.x,s=t.x,a=n.x,o=e.y,c=t.y,l=n.y,h=Math.min(i,s,a),u=Math.min(o,c,l),p=Math.max(i,s,a),d=Math.max(o,c,l),f=n.next;for(;f!==e;){if(f.x>=h&&f.x<=p&&f.y>=u&&f.y<=d&&Kr(i,o,s,c,a,l,f.x,f.y)&&st(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function cm(r,e,t,n){let i=r.prev,s=r,a=r.next;if(st(i,s,a)>=0)return!1;let o=i.x,c=s.x,l=a.x,h=i.y,u=s.y,p=a.y,d=Math.min(o,c,l),f=Math.min(h,u,p),m=Math.max(o,c,l),v=Math.max(h,u,p),g=Bl(d,f,e,t,n),_=Bl(m,v,e,t,n),y=r.prevZ,S=r.nextZ;for(;y&&y.z>=g&&S&&S.z<=_;){if(y.x>=d&&y.x<=m&&y.y>=f&&y.y<=v&&y!==i&&y!==a&&Kr(o,h,c,u,l,p,y.x,y.y)&&st(y.prev,y,y.next)>=0||(y=y.prevZ,S.x>=d&&S.x<=m&&S.y>=f&&S.y<=v&&S!==i&&S!==a&&Kr(o,h,c,u,l,p,S.x,S.y)&&st(S.prev,S,S.next)>=0))return!1;S=S.nextZ}for(;y&&y.z>=g;){if(y.x>=d&&y.x<=m&&y.y>=f&&y.y<=v&&y!==i&&y!==a&&Kr(o,h,c,u,l,p,y.x,y.y)&&st(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;S&&S.z<=_;){if(S.x>=d&&S.x<=m&&S.y>=f&&S.y<=v&&S!==i&&S!==a&&Kr(o,h,c,u,l,p,S.x,S.y)&&st(S.prev,S,S.next)>=0)return!1;S=S.nextZ}return!0}function hm(r,e){let t=r;do{let n=t.prev,i=t.next.next;!br(n,i)&&jd(n,t,t.next,i)&&bs(n,i)&&bs(i,n)&&(e.push(n.i,t.i,i.i),Ts(t),Ts(t.next),t=r=i),t=t.next}while(t!==r);return Ni(t)}function um(r,e,t,n,i,s){let a=r;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&gm(a,o)){let c=qd(a,o);return a=Ni(a,a.next),c=Ni(c,c.next),Ss(a,e,t,n,i,s,0),void Ss(c,e,t,n,i,s,0)}o=o.next}a=a.next}while(a!==r)}function dm(r,e){let t=r.x-e.x;return t===0&&(t=r.y-e.y,t===0)&&(t=(r.next.y-r.y)/(r.next.x-r.x)-(e.next.y-e.y)/(e.next.x-e.x)),t}function pm(r,e){let t=(function(i,s){let a=s,o=i.x,c=i.y,l,h=-1/0;if(br(i,a))return a;do{if(br(i,a.next))return a.next;if(c<=a.y&&c>=a.next.y&&a.next.y!==a.y){let m=a.x+(c-a.y)*(a.next.x-a.x)/(a.next.y-a.y);if(m<=o&&m>h&&(h=m,l=a.x=a.x&&a.x>=p&&o!==a.x&&Xd(cl.x||a.x===l.x&&mm(l,a)))&&(l=a,f=m)}a=a.next}while(a!==u);return l})(r,e);if(!t)return e;let n=qd(t,r);return Ni(n,n.next),Ni(t,t.next)}function mm(r,e){return st(r.prev,r,e.prev)<0&&st(e.next,r,r.next)<0}function Bl(r,e,t,n,i){return(r=1431655765&((r=858993459&((r=252645135&((r=16711935&((r=(r-t)*i|0)|r<<8))|r<<4))|r<<2))|r<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function fm(r){let e=r,t=r;do(e.x=(r-a)*(s-o)&&(r-a)*(n-o)>=(t-a)*(e-o)&&(t-a)*(s-o)>=(i-a)*(n-o)}function Kr(r,e,t,n,i,s,a,o){return!(r===a&&e===o)&&Xd(r,e,t,n,i,s,a,o)}function gm(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!(function(t,n){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==n.i&&i.next.i!==n.i&&jd(i,i.next,t,n))return!0;i=i.next}while(i!==t);return!1})(r,e)&&(bs(r,e)&&bs(e,r)&&(function(t,n){let i=t,s=!1,a=(t.x+n.x)/2,o=(t.y+n.y)/2;do i.y>o!=i.next.y>o&&i.next.y!==i.y&&a<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next;while(i!==t);return s})(r,e)&&(st(r.prev,r,e.prev)||st(r,e.prev,e))||br(r,e)&&st(r.prev,r,r.next)>0&&st(e.prev,e,e.next)>0)}function st(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function br(r,e){return r.x===e.x&&r.y===e.y}function jd(r,e,t,n){let i=ya(st(r,e,t)),s=ya(st(r,e,n)),a=ya(st(t,n,r)),o=ya(st(t,n,e));return i!==s&&a!==o||!(i!==0||!va(r,t,e))||!(s!==0||!va(r,n,e))||!(a!==0||!va(t,r,n))||!(o!==0||!va(t,e,n))}function va(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function ya(r){return r>0?1:r<0?-1:0}function bs(r,e){return st(r.prev,r,r.next)<0?st(r,e,r.next)>=0&&st(r,r.prev,e)>=0:st(r,e,r.prev)<0||st(r,r.next,e)<0}function qd(r,e){let t=zl(r.i,r.x,r.y),n=zl(e.i,e.x,e.y),i=r.next,s=e.prev;return r.next=e,e.prev=r,t.next=i,i.prev=t,n.next=t,t.prev=n,s.next=n,n.prev=s,n}function qu(r,e,t,n){let i=zl(r,e,t);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Ts(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function zl(r,e,t){return{i:r,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}var Gl=class{static triangulate(e,t,n=2){return om(e,t,n)}},Sn=class r{static area(e){let t=e.length,n=0;for(let i=t-1,s=0;s2&&r[e-1].equals(r[0])&&r.pop()}function Ku(r,e){for(let t=0;tNumber.EPSILON){let he=Math.sqrt(ye),Ce=Math.sqrt(K*K+re*re),ee=U.x-j/he,se=U.y+V/he,ie=((x.x-re/Ce-ee)*re-(x.y+K/Ce-se)*K)/(V*re-j*K);D=ee+V*ie-R.x,L=se+j*ie-R.y;let pe=D*D+L*L;if(pe<=2)return new $(D,L);w=Math.sqrt(pe/2)}else{let he=!1;V>Number.EPSILON?K>Number.EPSILON&&(he=!0):V<-Number.EPSILON?K<-Number.EPSILON&&(he=!0):Math.sign(j)===Math.sign(re)&&(he=!0),he?(D=-j,L=V,w=Math.sqrt(ye)):(D=V,L=j,w=Math.sqrt(ye/2))}return new $(D/w,L/w)}let ne=[];for(let R=0,U=H.length,x=U-1,D=R+1;R=0;R--){let U=R/v,x=d*Math.cos(U*Math.PI/2),D=f*Math.sin(U*Math.PI/2)+m;for(let L=0,w=H.length;L=0;){let D=x,L=x-1;L<0&&(L=R.length-1);for(let w=0,V=h+2*v;w0)&&d.push(y,S,M),(g!==n-1||c0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let i=e.uniforms[n];switch(this.uniforms[n]={},i.type){case"t":this.uniforms[n].value=t[i.value]||null;break;case"c":this.uniforms[n].value=new Te().setHex(i.value);break;case"v2":this.uniforms[n].value=new $().fromArray(i.value);break;case"v3":this.uniforms[n].value=new A().fromArray(i.value);break;case"v4":this.uniforms[n].value=new Ke().fromArray(i.value);break;case"m3":this.uniforms[n].value=new Ne().fromArray(i.value);break;case"m4":this.uniforms[n].value=new be().fromArray(i.value);break;default:this.uniforms[n].value=i.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let n in e.extensions)this.extensions[n]=e.extensions[n];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},to=class extends qt{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},An=class extends Bt{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Te(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Te(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},zt=class extends An{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new $(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Oe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Te(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Te(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Te(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}};var no=class extends Bt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},io=class extends Bt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function xa(r,e){return r&&r.constructor!==e?typeof e.BYTES_PER_ELEMENT=="number"?new e(r):Array.prototype.slice.call(r):r}function vm(r){let e=r.length,t=new Array(e);for(let n=0;n!==e;++n)t[n]=n;return t.sort(function(n,i){return r[n]-r[i]}),t}function $u(r,e,t){let n=r.length,i=new r.constructor(n);for(let s=0,a=0;a!==n;++s){let o=t[s]*e;for(let c=0;c!==e;++c)i[a++]=r[o+c]}return i}function ym(r,e,t,n){let i=1,s=r[0];for(;s!==void 0&&s[n]===void 0;)s=r[i++];if(s===void 0)return;let a=s[n];if(a!==void 0)if(Array.isArray(a))do a=s[n],a!==void 0&&(e.push(s.time),t.push(...a)),s=r[i++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[n],a!==void 0&&(e.push(s.time),a.toArray(t,t.length)),s=r[i++];while(s!==void 0);else do a=s[n],a!==void 0&&(e.push(s.time),t.push(a)),s=r[i++];while(s!==void 0)}var wn=class{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],s=t[n-1];n:{e:{let a;t:{i:if(!(e=s)){let o=t[1];e=s)break e}a=n,n=0;break t}break n}for(;n>>1;et;)--a;if(++a,s!==0||a!==i){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=n.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(we("KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,i=this.values,s=n.length;s===0&&(we("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let c=n[o];if(typeof c=="number"&&isNaN(c)){we("KeyframeTrack: Time is not a valid number.",this,o,c),e=!1;break}if(a!==null&&a>c){we("KeyframeTrack: Out of order keys.",this,o,c,a),e=!1;break}a=c}if(i!==void 0&&zp(i))for(let o=0,c=i.length;o!==c;++o){let l=i[o];if(isNaN(l)){we("KeyframeTrack: Value is not a valid number.",this,o,l),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===ba,s=e.length-1,a=1;for(let o=1;o0){e[a]=e[s];for(let o=s*n,c=a*n,l=0;l!==n;++l)t[c+l]=t[o+l];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=new this.constructor(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}};Ft.prototype.ValueTypeName="",Ft.prototype.TimeBufferType=Float32Array,Ft.prototype.ValueBufferType=Float32Array,Ft.prototype.DefaultInterpolation=Pi;var Wn=class extends Ft{constructor(e,t,n){super(e,t,n)}};Wn.prototype.ValueTypeName="bool",Wn.prototype.ValueBufferType=Array,Wn.prototype.DefaultInterpolation=Ci,Wn.prototype.InterpolantFactoryMethodLinear=void 0,Wn.prototype.InterpolantFactoryMethodSmooth=void 0;var Es=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}};Es.prototype.ValueTypeName="color";var $n=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}};$n.prototype.ValueTypeName="number";var lo=class extends wn{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=(n-t)/(i-t),l=e*o;for(let h=l+o;l!==h;l+=4)ct.slerpFlat(s,0,a,l-o,a,l,c);return s}},Rn=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new lo(this.times,this.values,this.getValueSize(),e)}};Rn.prototype.ValueTypeName="quaternion",Rn.prototype.InterpolantFactoryMethodSmooth=void 0;var Xn=class extends Ft{constructor(e,t,n){super(e,t,n)}};Xn.prototype.ValueTypeName="string",Xn.prototype.ValueBufferType=Array,Xn.prototype.DefaultInterpolation=Ci,Xn.prototype.InterpolantFactoryMethodLinear=void 0,Xn.prototype.InterpolantFactoryMethodSmooth=void 0;var Qn=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}};Qn.prototype.ValueTypeName="vector";var Er=class{constructor(e="",t=-1,n=[],i=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=en(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let a=0,o=n.length;a!==o;++a)t.push(xm(n[a]).scale(i));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=n.length;s!==a;++s)t.push(Ft.toJSON(n[s]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let s=t.length,a=[];for(let o=0;o1){let u=h[1],p=i[u];p||(i[u]=p=[]),p.push(l)}}let a=[];for(let o in i)a.push(this.CreateFromMorphTargetSequence(o,i[o],t,n));return a}resetDuration(){let e=0;for(let t=0,n=this.tracks.length;t!==n;++t){let i=this.tracks[t];e=Math.max(e,i.times[i.times.length-1])}return this.duration=e,this}trim(){for(let e=0;e{t&&t(s),this.manager.itemEnd(e)},0);if(Vn[e]!==void 0)return void Vn[e].push({onLoad:t,onProgress:n,onError:i});Vn[e]=[],Vn[e].push({onLoad:t,onProgress:n,onError:i});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,c=this.responseType;fetch(a).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&ge("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;let h=Vn[e],u=l.body.getReader(),p=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),d=p?parseInt(p):0,f=d!==0,m=0,v=new ReadableStream({start(g){(function _(){u.read().then(({done:y,value:S})=>{if(y)g.close();else{m+=S.byteLength;let T=new ProgressEvent("progress",{lengthComputable:f,loaded:m,total:d});for(let M=0,P=h.length;M{g.error(y)})})()}});return new Response(v)}throw new kl(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return l.json();default:if(o==="")return l.text();{let h=/charset="?([^;"\s]*)"?/i.exec(o),u=h&&h[1]?h[1].toLowerCase():void 0,p=new TextDecoder(u);return l.arrayBuffer().then(d=>p.decode(d))}}}).then(l=>{bn.add(`file:${e}`,l);let h=Vn[e];delete Vn[e];for(let u=0,p=h.length;u{let h=Vn[e];if(h===void 0)throw this.manager.itemError(e),l;delete Vn[e];for(let u=0,p=h.length;u{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};var ar=new WeakMap,ho=class extends Cn{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=bn.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);else{let u=ar.get(a);u===void 0&&(u=[],ar.set(a,u)),u.push({onLoad:t,onError:i})}return a}let o=dr("img");function c(){h(),t&&t(this);let u=ar.get(this)||[];for(let p=0;p"u"&&ge("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&ge("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=bn.get(`image-bitmap:${e}`);if(a!==void 0)return s.manager.itemStart(e),a.then?void a.then(l=>{Rl.has(a)===!0?(i&&i(Rl.get(a)),s.manager.itemError(e),s.manager.itemEnd(e)):(t&&t(l),s.manager.itemEnd(e))}):void setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);let o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let c=fetch(e,o).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(l){bn.add(`image-bitmap:${e}`,l),t&&t(l),s.manager.itemEnd(e)}).catch(function(l){i&&i(l),Rl.set(c,l),bn.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});bn.add(`image-bitmap:${e}`,c),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};var h_=new be,u_=new be,d_=new be;var or=-90,uo=class extends tt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new gt(or,1,e,t);i.layers=this.layers,this.add(i);let s=new gt(or,1,e,t);s.layers=this.layers,this.add(s);let a=new gt(or,1,e,t);a.layers=this.layers,this.add(a);let o=new gt(or,1,e,t);o.layers=this.layers,this.add(o);let c=new gt(or,1,e,t);c.layers=this.layers,this.add(c);let l=new gt(or,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,s,a,o,c]=t;for(let l of t)this.remove(l);if(e===qn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else{if(e!==ur)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1)}for(let l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,c,l,h]=this.children,u=e.getRenderTarget(),p=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let v=!1;v=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,i),v&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,1,i),v&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,i),v&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,i),v&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),e.setRenderTarget(n,4,i),v&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,i),v&&e.autoClear===!1&&e.clearDepth(),e.render(t,h),e.setRenderTarget(u,p,d),e.xr.enabled=f,n.texture.needsPMREMUpdate=!0}},po=class extends gt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}};var p_=new A,m_=new ct,f_=new A,g_=new A,__=new A;var v_=new A,y_=new ct,x_=new A,M_=new A;var Jc="\\[\\]\\.:\\/",Mm=new RegExp("["+Jc+"]","g"),Cl="[^"+Jc+"]",Sm="[^"+Jc.replace("\\.","")+"]",bm=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Cl)+/(WCOD+)?/.source.replace("WCOD",Sm)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Cl)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Cl)+"$"),Tm=["material","materials","bones","map"],$e=class r{constructor(e,t,n){this.path=t,this.parsedPath=n||r.parseTrackName(t),this.node=r.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new r.Composite(e,t,n):new r(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Mm,"")}static parseTrackName(e){let t=bm.exec(e);if(t===null)throw new Error("THREE.PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let s=n.nodeName.substring(i+1);Tm.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let a=0;au.start-p.start);let h=0;for(let u=1;u 0 - vec4 plane; - #ifdef ALPHA_TO_COVERAGE - float distanceToPlane, distanceGradient; - float clipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - if ( clipOpacity == 0.0 ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - float unionClipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - } - #pragma unroll_loop_end - clipOpacity *= 1.0 - unionClipOpacity; - #endif - diffuseColor.a *= clipOpacity; - if ( diffuseColor.a == 0.0 ) discard; - #else - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - bool clipped = true; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; - } - #pragma unroll_loop_end - if ( clipped ) discard; - #endif - #endif -#endif`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,color_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#endif`,color_pars_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#endif`,color_pars_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec4 vColor; -#endif`,color_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - vColor = vec4( 1.0 ); -#endif -#ifdef USE_COLOR_ALPHA - vColor *= color; -#elif defined( USE_COLOR ) - vColor.rgb *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.rgb *= instanceColor.rgb; -#endif -#ifdef USE_BATCHING_COLOR - vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); -#endif`,common:`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -#define inverseTransformDirection transformDirectionByInverseViewMatrix -vec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) { - return normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz ); -} -vec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) { - return normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz ); -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,cube_uv_reflection_fragment:`#ifdef ENVMAP_TYPE_CUBE_UV - #define cubeUV_minMipLevel 4.0 - #define cubeUV_minTileSize 16.0 - float getFace( vec3 direction ) { - vec3 absDirection = abs( direction ); - float face = - 1.0; - if ( absDirection.x > absDirection.z ) { - if ( absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0.0 : 3.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } else { - if ( absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2.0 : 5.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } - return face; - } - vec2 getUV( vec3 direction, float face ) { - vec2 uv; - if ( face == 0.0 ) { - uv = vec2( direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 1.0 ) { - uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); - } else if ( face == 2.0 ) { - uv = vec2( - direction.x, direction.y ) / abs( direction.z ); - } else if ( face == 3.0 ) { - uv = vec2( - direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 4.0 ) { - uv = vec2( - direction.x, direction.z ) / abs( direction.y ); - } else { - uv = vec2( direction.x, direction.y ) / abs( direction.z ); - } - return 0.5 * ( uv + 1.0 ); - } - vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { - float face = getFace( direction ); - float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); - mipInt = max( mipInt, cubeUV_minMipLevel ); - float faceSize = exp2( mipInt ); - highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; - if ( face > 2.0 ) { - uv.y += faceSize; - face -= 3.0; - } - uv.x += face * faceSize; - uv.x += filterInt * 3.0 * cubeUV_minTileSize; - uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); - uv.x *= CUBEUV_TEXEL_WIDTH; - uv.y *= CUBEUV_TEXEL_HEIGHT; - #ifdef texture2DGradEXT - return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; - #else - return texture2D( envMap, uv ).rgb; - #endif - } - #define cubeUV_r0 1.0 - #define cubeUV_m0 - 2.0 - #define cubeUV_r1 0.8 - #define cubeUV_m1 - 1.0 - #define cubeUV_r4 0.4 - #define cubeUV_m4 2.0 - #define cubeUV_r5 0.305 - #define cubeUV_m5 3.0 - #define cubeUV_r6 0.21 - #define cubeUV_m6 4.0 - float roughnessToMip( float roughness ) { - float mip = 0.0; - if ( roughness >= cubeUV_r1 ) { - mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; - } else if ( roughness >= cubeUV_r4 ) { - mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; - } else if ( roughness >= cubeUV_r5 ) { - mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; - } else if ( roughness >= cubeUV_r6 ) { - mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; - } else { - mip = - 2.0 * log2( 1.16 * roughness ); } - return mip; - } - vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { - float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); - float mipF = fract( mip ); - float mipInt = floor( mip ); - vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); - if ( mipF == 0.0 ) { - return vec4( color0, 1.0 ); - } else { - vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); - return vec4( mix( color0, color1, mipF ), 1.0 ); - } - } -#endif`,defaultnormal_vertex:`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; -#endif`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:`vec4 LinearTransferOETF( in vec4 value ) { - return value; -} -vec4 sRGBTransferEOTF( in vec4 value ) { - return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); -} -vec4 sRGBTransferOETF( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,envmap_fragment:`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif - #endif -#endif`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform mat3 envMapRotation; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif -#endif`,envmap_pars_fragment:`#ifdef USE_ENVMAP - uniform float reflectivity; - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - varying vec3 vWorldPosition; - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif -#endif`,envmap_pars_vertex:`#ifdef USE_ENVMAP - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - - varying vec3 vWorldPosition; - #else - varying vec3 vReflect; - uniform float refractionRatio; - #endif -#endif`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); - reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,envmap_vertex:`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,fog_vertex:`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,fog_pars_vertex:`#ifdef USE_FOG - varying float vFogDepth; -#endif`,fog_fragment:`#ifdef USE_FOG - #ifdef FOG_EXP2 - float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); - #else - float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,fog_pars_fragment:`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,gradientmap_pars_fragment:`#ifdef USE_GRADIENTMAP - uniform sampler2D gradientMap; -#endif -vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { - float dotNL = dot( normal, lightDirection ); - vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); - #ifdef USE_GRADIENTMAP - return vec3( texture2D( gradientMap, coord ).r ); - #else - vec2 fw = fwidth( coord ) * 0.5; - return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); - #endif -}`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,lights_lambert_fragment:`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`varying vec3 vViewPosition; -struct LambertMaterial { - vec3 diffuseColor; - float specularStrength; -}; -void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,lights_pars_begin:`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif -#include `,lights_toon_fragment:`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`varying vec3 vViewPosition; -struct ToonMaterial { - vec3 diffuseColor; -}; -void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,lights_phong_fragment:`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`varying vec3 vViewPosition; -struct BlinnPhongMaterial { - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; -}; -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; -} -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,lights_physical_fragment:`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -material.metalness = metalnessFactor; -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; - material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = vec3( 0.04 ); - material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_DISPERSION - material.dispersion = dispersion; -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,lights_physical_pars_fragment:`uniform sampler2D dfgLUT; -struct PhysicalMaterial { - vec3 diffuseColor; - vec3 diffuseContribution; - vec3 specularColor; - vec3 specularColorBlended; - float roughness; - float metalness; - float specularF90; - float dispersion; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - vec3 iridescenceFresnelDielectric; - vec3 iridescenceFresnelMetallic; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColorBlended; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float rInv = 1.0 / ( roughness + 0.1 ); - float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; - float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; - float DG = exp( a * dotNV + b ); - return saturate( DG ); -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - float dotNV = saturate( dot( normal, viewDir ) ); - vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; - vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; - vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; - vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; - float Ess_V = dfgV.x + dfgV.y; - float Ess_L = dfgL.x + dfgL.y; - float Ems_V = 1.0 - Ess_V; - float Ems_L = 1.0 - Ess_L; - vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; - vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); - float compensationFactor = Ems_V * Ems_L; - vec3 multiScatter = Fms * compensationFactor; - return singleScatter + multiScatter; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - #ifdef USE_CLEARCOAT - vec3 Ncc = geometryClearcoatNormal; - vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); - vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); - vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); - mat3 mInvClearcoat = mat3( - vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), - vec3( 0, 1, 0 ), - vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) - ); - vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; - clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); - #endif - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - - float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); - - float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); - - irradiance *= sheenEnergyComp; - - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); - #ifdef USE_SHEEN - float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; - diffuse *= sheenEnergyComp; - #endif - reflectedLight.indirectDiffuse += diffuse; -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; - #endif - vec3 singleScatteringDielectric = vec3( 0.0 ); - vec3 multiScatteringDielectric = vec3( 0.0 ); - vec3 singleScatteringMetallic = vec3( 0.0 ); - vec3 multiScatteringMetallic = vec3( 0.0 ); - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); - computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); - #endif - vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); - vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); - vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; - vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - vec3 indirectSpecular = radiance * singleScattering; - indirectSpecular += multiScattering * cosineWeightedIrradiance; - vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; - #ifdef USE_SHEEN - float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; - indirectSpecular *= sheenEnergyComp; - indirectDiffuse *= sheenEnergyComp; - #endif - reflectedLight.indirectSpecular += indirectSpecular; - reflectedLight.indirectDiffuse += indirectDiffuse; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,lights_fragment_begin:` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); - material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif - #ifdef USE_LIGHT_PROBES_GRID - vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; - vec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix ); - irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal ); - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,lights_fragment_maps:`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) - #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,lights_fragment_end:`#if defined( RE_IndirectDiffuse ) - #if defined( LAMBERT ) || defined( PHONG ) - irradiance += iblIrradiance; - #endif - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,lightprobes_pars_fragment:`#ifdef USE_LIGHT_PROBES_GRID -uniform highp sampler3D probesSH; -uniform vec3 probesMin; -uniform vec3 probesMax; -uniform vec3 probesResolution; -vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { - vec3 res = probesResolution; - vec3 gridRange = probesMax - probesMin; - vec3 resMinusOne = res - 1.0; - vec3 probeSpacing = gridRange / resMinusOne; - vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; - vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 ); - uvw = uvw * resMinusOne / res + 0.5 / res; - float nz = res.z; - float paddedSlices = nz + 2.0; - float atlasDepth = 7.0 * paddedSlices; - float uvZBase = uvw.z * nz + 1.0; - vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); - vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); - vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); - vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); - vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); - vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); - vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); - vec3 c0 = s0.xyz; - vec3 c1 = vec3( s0.w, s1.xy ); - vec3 c2 = vec3( s1.zw, s2.x ); - vec3 c3 = s2.yzw; - vec3 c4 = s3.xyz; - vec3 c5 = vec3( s3.w, s4.xy ); - vec3 c6 = vec3( s4.zw, s5.x ); - vec3 c7 = s5.yzw; - vec3 c8 = s6.xyz; - float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; - vec3 result = c0 * 0.886227; - result += c1 * 2.0 * 0.511664 * y; - result += c2 * 2.0 * 0.511664 * z; - result += c3 * 2.0 * 0.511664 * x; - result += c4 * 2.0 * 0.429043 * x * y; - result += c5 * 2.0 * 0.429043 * y * z; - result += c6 * ( 0.743125 * z * z - 0.247708 ); - result += c7 * 2.0 * 0.429043 * x * z; - result += c8 * 0.429043 * ( x * x - y * y ); - return max( result, vec3( 0.0 ) ); -} -#endif`,logdepthbuf_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER - varying float vFragDepth; - varying float vIsPerspective; -#endif`,logdepthbuf_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,map_fragment:`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,map_pars_fragment:`#ifdef USE_MAP - uniform sampler2D map; -#endif`,map_particle_fragment:`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - #if defined( USE_POINTS_UV ) - vec2 uv = vUv; - #else - vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; - #endif -#endif -#ifdef USE_MAP - diffuseColor *= texture2D( map, uv ); -#endif -#ifdef USE_ALPHAMAP - diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,map_particle_pars_fragment:`#if defined( USE_POINTS_UV ) - varying vec2 vUv; -#else - #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - uniform mat3 uvTransform; - #endif -#endif -#ifdef USE_MAP - uniform sampler2D map; -#endif -#ifdef USE_ALPHAMAP - uniform sampler2D alphaMap; -#endif`,metalnessmap_fragment:`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,morphinstance_vertex:`#ifdef USE_INSTANCING_MORPH - float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; - } -#endif`,morphcolor_vertex:`#if defined( USE_MORPHCOLORS ) - vColor *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - #if defined( USE_COLOR_ALPHA ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; - #elif defined( USE_COLOR ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; - #endif - } -#endif`,morphnormal_vertex:`#ifdef USE_MORPHNORMALS - objectNormal *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,morphtarget_pars_vertex:`#ifdef USE_MORPHTARGETS - #ifndef USE_INSTANCING_MORPH - uniform float morphTargetBaseInfluence; - uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - #endif - uniform sampler2DArray morphTargetsTexture; - uniform ivec2 morphTargetsTextureSize; - vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { - int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; - int y = texelIndex / morphTargetsTextureSize.x; - int x = texelIndex - y * morphTargetsTextureSize.x; - ivec3 morphUV = ivec3( x, y, morphTargetIndex ); - return texelFetch( morphTargetsTexture, morphUV, 0 ); - } -#endif`,morphtarget_vertex:`#ifdef USE_MORPHTARGETS - transformed *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,normal_fragment_begin:`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #ifdef DOUBLE_SIDED - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #ifdef DOUBLE_SIDED - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,normal_fragment_maps:`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #if defined( USE_PACKED_NORMALMAP ) - mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); - #endif - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,normal_pars_fragment:`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,normal_pars_vertex:`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,normal_vertex:`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #ifdef FLIP_SIDED - vBitangent = - vBitangent; - #endif - #endif -#endif`,normalmap_pars_fragment:`#ifdef USE_NORMALMAP - uniform sampler2D normalMap; - uniform vec2 normalScale; -#endif -#ifdef USE_NORMALMAP_OBJECTSPACE - uniform mat3 normalMatrix; -#endif -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) - mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - vec3 N = surf_norm; - vec3 q1perp = cross( q1, N ); - vec3 q0perp = cross( N, q0 ); - vec3 T = q1perp * st0.x + q0perp * st1.x; - vec3 B = q1perp * st0.y + q0perp * st1.y; - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); - return mat3( T * scale, B * scale, N ); - } -#endif`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,clearcoat_pars_fragment:`#ifdef USE_CLEARCOATMAP - uniform sampler2D clearcoatMap; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform sampler2D clearcoatNormalMap; - uniform vec2 clearcoatNormalScale; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform sampler2D clearcoatRoughnessMap; -#endif`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,opaque_fragment:`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; -const float Inv255 = 1. / 255.; -const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); -const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); -const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); -const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); -vec4 packDepthToRGBA( const in float v ) { - if( v <= 0.0 ) - return vec4( 0., 0., 0., 0. ); - if( v >= 1.0 ) - return vec4( 1., 1., 1., 1. ); - float vuf; - float af = modf( v * PackFactors.a, vuf ); - float bf = modf( vuf * ShiftRight8, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); -} -vec3 packDepthToRGB( const in float v ) { - if( v <= 0.0 ) - return vec3( 0., 0., 0. ); - if( v >= 1.0 ) - return vec3( 1., 1., 1. ); - float vuf; - float bf = modf( v * PackFactors.b, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec3( vuf * Inv255, gf * PackUpscale, bf ); -} -vec2 packDepthToRG( const in float v ) { - if( v <= 0.0 ) - return vec2( 0., 0. ); - if( v >= 1.0 ) - return vec2( 1., 1. ); - float vuf; - float gf = modf( v * 256., vuf ); - return vec2( vuf * Inv255, gf ); -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors4 ); -} -float unpackRGBToDepth( const in vec3 v ) { - return dot( v, UnpackFactors3 ); -} -float unpackRGToDepth( const in vec2 v ) { - return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; -} -vec4 pack2HalfToRGBA( const in vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( const in vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - #ifdef USE_REVERSED_DEPTH_BUFFER - - return depth * ( far - near ) - far; - #else - return depth * ( near - far ) - near; - #endif -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - - #ifdef USE_REVERSED_DEPTH_BUFFER - return ( near * far ) / ( ( near - far ) * depth - near ); - #else - return ( near * far ) / ( ( far - near ) * depth - far ); - #endif -}`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,project_vertex:`vec4 mvPosition = vec4( transformed, 1.0 ); -#ifdef USE_BATCHING - mvPosition = batchingMatrix * mvPosition; -#endif -#ifdef USE_INSTANCING - mvPosition = instanceMatrix * mvPosition; -#endif -mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,dithering_fragment:`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,dithering_pars_fragment:`#ifdef DITHERING - vec3 dithering( vec3 color ) { - float grid_position = rand( gl_FragCoord.xy ); - vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); - dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); - return color + dither_shift_RGB; - } -#endif`,roughnessmap_fragment:`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,shadowmap_pars_fragment:`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - #if defined( SHADOWMAP_TYPE_PCF ) - uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - #else - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - #if defined( SHADOWMAP_TYPE_PCF ) - uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - #else - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #if defined( SHADOWMAP_TYPE_PCF ) - uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - #elif defined( SHADOWMAP_TYPE_BASIC ) - uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - #if defined( SHADOWMAP_TYPE_PCF ) - float interleavedGradientNoise( vec2 position ) { - return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); - } - vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { - const float goldenAngle = 2.399963229728653; - float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); - float theta = float( sampleIndex ) * goldenAngle + phi; - return vec2( cos( theta ), sin( theta ) ) * r; - } - #endif - #if defined( SHADOWMAP_TYPE_PCF ) - float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float radius = shadowRadius * texelSize.x; - float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; - shadow = ( - texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + - texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + - texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + - texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + - texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) - ) * 0.2; - } - return mix( 1.0, shadow, shadowIntensity ); - } - #elif defined( SHADOWMAP_TYPE_VSM ) - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - #ifdef USE_REVERSED_DEPTH_BUFFER - shadowCoord.z -= shadowBias; - #else - shadowCoord.z += shadowBias; - #endif - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; - float mean = distribution.x; - float variance = distribution.y * distribution.y; - #ifdef USE_REVERSED_DEPTH_BUFFER - float hard_shadow = step( mean, shadowCoord.z ); - #else - float hard_shadow = step( shadowCoord.z, mean ); - #endif - - if ( hard_shadow == 1.0 ) { - shadow = 1.0; - } else { - variance = max( variance, 0.0000001 ); - float d = shadowCoord.z - mean; - float p_max = variance / ( variance + d * d ); - p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); - shadow = max( hard_shadow, p_max ); - } - } - return mix( 1.0, shadow, shadowIntensity ); - } - #else - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - #ifdef USE_REVERSED_DEPTH_BUFFER - shadowCoord.z -= shadowBias; - #else - shadowCoord.z += shadowBias; - #endif - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - float depth = texture2D( shadowMap, shadowCoord.xy ).r; - #ifdef USE_REVERSED_DEPTH_BUFFER - shadow = step( depth, shadowCoord.z ); - #else - shadow = step( shadowCoord.z, depth ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #if defined( SHADOWMAP_TYPE_PCF ) - float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - vec3 bd3D = normalize( lightToPosition ); - vec3 absVec = abs( lightToPosition ); - float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); - if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { - #ifdef USE_REVERSED_DEPTH_BUFFER - float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); - dp -= shadowBias; - #else - float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); - dp += shadowBias; - #endif - float texelSize = shadowRadius / shadowMapSize.x; - vec3 absDir = abs( bd3D ); - vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); - tangent = normalize( cross( bd3D, tangent ) ); - vec3 bitangent = cross( bd3D, tangent ); - float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; - vec2 sample0 = vogelDiskSample( 0, 5, phi ); - vec2 sample1 = vogelDiskSample( 1, 5, phi ); - vec2 sample2 = vogelDiskSample( 2, 5, phi ); - vec2 sample3 = vogelDiskSample( 3, 5, phi ); - vec2 sample4 = vogelDiskSample( 4, 5, phi ); - shadow = ( - texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + - texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + - texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + - texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + - texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) - ) * 0.2; - } - return mix( 1.0, shadow, shadowIntensity ); - } - #elif defined( SHADOWMAP_TYPE_BASIC ) - float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - vec3 absVec = abs( lightToPosition ); - float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); - if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { - float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); - dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - float depth = textureCube( shadowMap, bd3D ).r; - #ifdef USE_REVERSED_DEPTH_BUFFER - depth = 1.0 - depth; - #endif - shadow = step( dp, depth ); - } - return mix( 1.0, shadow, shadowIntensity ); - } - #endif - #endif -#endif`,shadowmap_pars_vertex:`#if NUM_SPOT_LIGHT_COORDS > 0 - uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif -#endif`,shadowmap_vertex:`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - #ifdef HAS_NORMAL - vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); - #else - vec3 shadowWorldNormal = vec3( 0.0 ); - #endif - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,shadowmask_pars_fragment:`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,skinbase_vertex:`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,skinning_pars_vertex:`#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif`,skinning_vertex:`#ifdef USE_SKINNING - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,skinnormal_vertex:`#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - #ifdef USE_TANGENT - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - #endif -#endif`,specularmap_fragment:`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,tonemapping_fragment:`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,tonemapping_pars_fragment:`#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -uniform float toneMappingExposure; -vec3 LinearToneMapping( vec3 color ) { - return saturate( toneMappingExposure * color ); -} -vec3 ReinhardToneMapping( vec3 color ) { - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); -} -vec3 CineonToneMapping( vec3 color ) { - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); -} -vec3 RRTAndODTFit( vec3 v ) { - vec3 a = v * ( v + 0.0245786 ) - 0.000090537; - vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; - return a / b; -} -vec3 ACESFilmicToneMapping( vec3 color ) { - const mat3 ACESInputMat = mat3( - vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), - vec3( 0.04823, 0.01566, 0.83777 ) - ); - const mat3 ACESOutputMat = mat3( - vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), - vec3( -0.07367, -0.00605, 1.07602 ) - ); - color *= toneMappingExposure / 0.6; - color = ACESInputMat * color; - color = RRTAndODTFit( color ); - color = ACESOutputMat * color; - return saturate( color ); -} -const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( - vec3( 1.6605, - 0.1246, - 0.0182 ), - vec3( - 0.5876, 1.1329, - 0.1006 ), - vec3( - 0.0728, - 0.0083, 1.1187 ) -); -const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( - vec3( 0.6274, 0.0691, 0.0164 ), - vec3( 0.3293, 0.9195, 0.0880 ), - vec3( 0.0433, 0.0113, 0.8956 ) -); -vec3 agxDefaultContrastApprox( vec3 x ) { - vec3 x2 = x * x; - vec3 x4 = x2 * x2; - return + 15.5 * x4 * x2 - - 40.14 * x4 * x - + 31.96 * x4 - - 6.868 * x2 * x - + 0.4298 * x2 - + 0.1191 * x - - 0.00232; -} -vec3 AgXToneMapping( vec3 color ) { - const mat3 AgXInsetMatrix = mat3( - vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), - vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), - vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) - ); - const mat3 AgXOutsetMatrix = mat3( - vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), - vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), - vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) - ); - const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; - color *= toneMappingExposure; - color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; - color = AgXInsetMatrix * color; - color = max( color, 1e-10 ); color = log2( color ); - color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); - color = clamp( color, 0.0, 1.0 ); - color = agxDefaultContrastApprox( color ); - color = AgXOutsetMatrix * color; - color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); - color = LINEAR_REC2020_TO_LINEAR_SRGB * color; - color = clamp( color, 0.0, 1.0 ); - return color; -} -vec3 NeutralToneMapping( vec3 color ) { - const float StartCompression = 0.8 - 0.04; - const float Desaturation = 0.15; - color *= toneMappingExposure; - float x = min( color.r, min( color.g, color.b ) ); - float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; - color -= offset; - float peak = max( color.r, max( color.g, color.b ) ); - if ( peak < StartCompression ) return color; - float d = 1. - StartCompression; - float newPeak = 1. - d * d / ( peak + d - StartCompression ); - color *= newPeak / peak; - float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); - return mix( color, vec3( newPeak ), g ); -} -vec3 CustomToneMapping( vec3 color ) { return color; }`,transmission_fragment:`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = transformNormalByInverseViewMatrix( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,transmission_pars_fragment:`#ifdef USE_TRANSMISSION - uniform float transmission; - uniform float thickness; - uniform float attenuationDistance; - uniform vec3 attenuationColor; - #ifdef USE_TRANSMISSIONMAP - uniform sampler2D transmissionMap; - #endif - #ifdef USE_THICKNESSMAP - uniform sampler2D thicknessMap; - #endif - uniform vec2 transmissionSamplerSize; - uniform sampler2D transmissionSamplerMap; - uniform mat4 modelMatrix; - uniform mat4 projectionMatrix; - varying vec3 vWorldPosition; - float w0( float a ) { - return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); - } - float w1( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); - } - float w2( float a ){ - return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); - } - float w3( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * a ); - } - float g0( float a ) { - return w0( a ) + w1( a ); - } - float g1( float a ) { - return w2( a ) + w3( a ); - } - float h0( float a ) { - return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); - } - float h1( float a ) { - return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); - } - vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { - uv = uv * texelSize.zw + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - float g0x = g0( fuv.x ); - float g1x = g1( fuv.x ); - float h0x = h0( fuv.x ); - float h1x = h1( fuv.x ); - float h0y = h0( fuv.y ); - float h1y = h1( fuv.y ); - vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + - g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); - } - vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { - vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); - vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); - vec2 fLodSizeInv = 1.0 / fLodSize; - vec2 cLodSizeInv = 1.0 / cLodSize; - vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); - vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); - return mix( fSample, cSample, fract( lod ) ); - } - vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { - vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); - vec3 modelScale; - modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); - modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); - modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); - return normalize( refractionVector ) * thickness * modelScale; - } - float applyIorToRoughness( const in float roughness, const in float ior ) { - return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); - } - vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { - float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); - return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); - } - vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { - if ( isinf( attenuationDistance ) ) { - return vec3( 1.0 ); - } else { - vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; - vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; - } - } - vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, - const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, - const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, - const in vec3 attenuationColor, const in float attenuationDistance ) { - vec4 transmittedLight; - vec3 transmittance; - #ifdef USE_DISPERSION - float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; - vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); - for ( int i = 0; i < 3; i ++ ) { - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); - transmittedLight[ i ] = transmissionSample[ i ]; - transmittedLight.a += transmissionSample.a; - transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; - } - transmittedLight.a /= 3.0; - #else - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); - transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); - #endif - vec3 attenuatedColor = transmittance * transmittedLight.rgb; - vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); - float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; - return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); - } -#endif`,uv_pars_fragment:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - varying vec2 vNormalMapUv; -#endif -#ifdef USE_EMISSIVEMAP - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_SPECULARMAP - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,uv_pars_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - uniform mat3 mapTransform; - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - uniform mat3 alphaMapTransform; - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - uniform mat3 lightMapTransform; - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - uniform mat3 aoMapTransform; - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - uniform mat3 bumpMapTransform; - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - uniform mat3 normalMapTransform; - varying vec2 vNormalMapUv; -#endif -#ifdef USE_DISPLACEMENTMAP - uniform mat3 displacementMapTransform; - varying vec2 vDisplacementMapUv; -#endif -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapTransform; - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - uniform mat3 metalnessMapTransform; - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - uniform mat3 roughnessMapTransform; - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - uniform mat3 anisotropyMapTransform; - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - uniform mat3 clearcoatMapTransform; - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform mat3 clearcoatNormalMapTransform; - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform mat3 clearcoatRoughnessMapTransform; - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - uniform mat3 sheenColorMapTransform; - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - uniform mat3 sheenRoughnessMapTransform; - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - uniform mat3 iridescenceMapTransform; - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform mat3 iridescenceThicknessMapTransform; - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SPECULARMAP - uniform mat3 specularMapTransform; - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - uniform mat3 specularColorMapTransform; - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - uniform mat3 specularIntensityMapTransform; - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,uv_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - vUv = vec3( uv, 1 ).xy; -#endif -#ifdef USE_MAP - vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ALPHAMAP - vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_LIGHTMAP - vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_AOMAP - vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_BUMPMAP - vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_NORMALMAP - vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_DISPLACEMENTMAP - vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_EMISSIVEMAP - vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_METALNESSMAP - vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ROUGHNESSMAP - vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ANISOTROPYMAP - vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOATMAP - vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCEMAP - vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_COLORMAP - vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULARMAP - vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_COLORMAP - vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_TRANSMISSIONMAP - vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_THICKNESSMAP - vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,worldpos_vertex:`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 - vec4 worldPosition = vec4( transformed, 1.0 ); - #ifdef USE_BATCHING - worldPosition = batchingMatrix * worldPosition; - #endif - #ifdef USE_INSTANCING - worldPosition = instanceMatrix * worldPosition; - #endif - worldPosition = modelMatrix * worldPosition; -#endif`,background_vert:`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,background_frag:`uniform sampler2D t2D; -uniform float backgroundIntensity; -varying vec2 vUv; -void main() { - vec4 texColor = texture2D( t2D, vUv ); - #ifdef DECODE_VIDEO_TEXTURE - texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,backgroundCube_vert:`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -uniform mat3 backgroundRotation; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,cube_vert:`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,cube_frag:`uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; -varying vec3 vWorldDirection; -void main() { - vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); - gl_FragColor = texColor; - gl_FragColor.a *= opacity; - #include - #include -}`,depth_vert:`#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vHighPrecisionZW = gl_Position.zw; -}`,depth_frag:`#if DEPTH_PACKING == 3200 - uniform float opacity; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - vec4 diffuseColor = vec4( 1.0 ); - #include - #if DEPTH_PACKING == 3200 - diffuseColor.a = opacity; - #endif - #include - #include - #include - #include - #include - #ifdef USE_REVERSED_DEPTH_BUFFER - float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; - #else - float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; - #endif - #if DEPTH_PACKING == 3200 - gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); - #elif DEPTH_PACKING == 3201 - gl_FragColor = packDepthToRGBA( fragCoordZ ); - #elif DEPTH_PACKING == 3202 - gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); - #elif DEPTH_PACKING == 3203 - gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); - #endif -}`,distance_vert:`#define DISTANCE -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vWorldPosition = worldPosition.xyz; -}`,distance_frag:`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); -}`,equirect_vert:`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,equirect_frag:`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,linedashed_vert:`uniform float scale; -attribute float lineDistance; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vLineDistance = scale * lineDistance; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,linedashed_frag:`uniform vec3 diffuse; -uniform float opacity; -uniform float dashSize; -uniform float totalSize; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - if ( mod( vLineDistance, totalSize ) > dashSize ) { - discard; - } - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,meshbasic_vert:`#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) - #include - #include - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,meshbasic_frag:`uniform vec3 diffuse; -uniform float opacity; -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; - #else - reflectedLight.indirectDiffuse += vec3( 1.0 ); - #endif - #include - reflectedLight.indirectDiffuse *= diffuseColor.rgb; - vec3 outgoingLight = reflectedLight.indirectDiffuse; - #include - #include - #include - #include - #include - #include - #include -}`,meshlambert_vert:`#define LAMBERT -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,meshlambert_frag:`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,meshmatcap_vert:`#define MATCAP -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; -}`,meshmatcap_frag:`#define MATCAP -uniform vec3 diffuse; -uniform float opacity; -uniform sampler2D matcap; -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 viewDir = normalize( vViewPosition ); - vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); - vec3 y = cross( viewDir, x ); - vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; - #ifdef USE_MATCAP - vec4 matcapColor = texture2D( matcap, uv ); - #else - vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); - #endif - vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; - #include - #include - #include - #include - #include - #include -}`,meshnormal_vert:`#define NORMAL -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - vViewPosition = - mvPosition.xyz; -#endif -}`,meshnormal_frag:`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); - #include - #include - #include - #include - gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,meshphong_vert:`#define PHONG -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,meshphong_frag:`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,meshphysical_vert:`#define STANDARD -varying vec3 vViewPosition; -#ifdef USE_TRANSMISSION - varying vec3 vWorldPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -#ifdef USE_TRANSMISSION - vWorldPosition = worldPosition.xyz; -#endif -}`,meshphysical_frag:`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_DISPERSION - uniform float dispersion; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - - outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; - - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,meshtoon_vert:`#define TOON -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -}`,meshtoon_frag:`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,points_vert:`uniform float size; -uniform float scale; -#include -#include -#include -#include -#include -#include -#ifdef USE_POINTS_UV - varying vec2 vUv; - uniform mat3 uvTransform; -#endif -void main() { - #ifdef USE_POINTS_UV - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #include - #include - #include - #include - #include - #include - gl_PointSize = size; - #ifdef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); - #endif - #include - #include - #include - #include -}`,points_frag:`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,shadow_vert:`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,shadow_frag:`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include - #include -}`,sprite_vert:`uniform float rotation; -uniform vec2 center; -#include -#include -#include -#include -#include -void main() { - #include - vec4 mvPosition = modelViewMatrix[ 3 ]; - vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); - #ifndef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) scale *= - mvPosition.z; - #endif - vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; - vec2 rotatedPosition; - rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; - rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; - mvPosition.xy += rotatedPosition; - gl_Position = projectionMatrix * mvPosition; - #include - #include - #include -}`,sprite_frag:`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include -}`},le={common:{diffuse:{value:new Te(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ne},alphaMap:{value:null},alphaMapTransform:{value:new Ne},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ne}},envmap:{envMap:{value:null},envMapRotation:{value:new Ne},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ne}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ne}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ne},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ne},normalScale:{value:new $(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ne},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ne}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ne}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ne}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Te(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new A},probesMax:{value:new A},probesResolution:{value:new A}},points:{diffuse:{value:new Te(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ne},alphaTest:{value:0},uvTransform:{value:new Ne}},sprite:{diffuse:{value:new Te(16777215)},opacity:{value:1},center:{value:new $(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ne},alphaMap:{value:null},alphaMapTransform:{value:new Ne},alphaTest:{value:0}}},Dn={basic:{uniforms:Pt([le.common,le.specularmap,le.envmap,le.aomap,le.lightmap,le.fog]),vertexShader:Fe.meshbasic_vert,fragmentShader:Fe.meshbasic_frag},lambert:{uniforms:Pt([le.common,le.specularmap,le.envmap,le.aomap,le.lightmap,le.emissivemap,le.bumpmap,le.normalmap,le.displacementmap,le.fog,le.lights,{emissive:{value:new Te(0)},envMapIntensity:{value:1}}]),vertexShader:Fe.meshlambert_vert,fragmentShader:Fe.meshlambert_frag},phong:{uniforms:Pt([le.common,le.specularmap,le.envmap,le.aomap,le.lightmap,le.emissivemap,le.bumpmap,le.normalmap,le.displacementmap,le.fog,le.lights,{emissive:{value:new Te(0)},specular:{value:new Te(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Fe.meshphong_vert,fragmentShader:Fe.meshphong_frag},standard:{uniforms:Pt([le.common,le.envmap,le.aomap,le.lightmap,le.emissivemap,le.bumpmap,le.normalmap,le.displacementmap,le.roughnessmap,le.metalnessmap,le.fog,le.lights,{emissive:{value:new Te(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Fe.meshphysical_vert,fragmentShader:Fe.meshphysical_frag},toon:{uniforms:Pt([le.common,le.aomap,le.lightmap,le.emissivemap,le.bumpmap,le.normalmap,le.displacementmap,le.gradientmap,le.fog,le.lights,{emissive:{value:new Te(0)}}]),vertexShader:Fe.meshtoon_vert,fragmentShader:Fe.meshtoon_frag},matcap:{uniforms:Pt([le.common,le.bumpmap,le.normalmap,le.displacementmap,le.fog,{matcap:{value:null}}]),vertexShader:Fe.meshmatcap_vert,fragmentShader:Fe.meshmatcap_frag},points:{uniforms:Pt([le.points,le.fog]),vertexShader:Fe.points_vert,fragmentShader:Fe.points_frag},dashed:{uniforms:Pt([le.common,le.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Fe.linedashed_vert,fragmentShader:Fe.linedashed_frag},depth:{uniforms:Pt([le.common,le.displacementmap]),vertexShader:Fe.depth_vert,fragmentShader:Fe.depth_frag},normal:{uniforms:Pt([le.common,le.bumpmap,le.normalmap,le.displacementmap,{opacity:{value:1}}]),vertexShader:Fe.meshnormal_vert,fragmentShader:Fe.meshnormal_frag},sprite:{uniforms:Pt([le.sprite,le.fog]),vertexShader:Fe.sprite_vert,fragmentShader:Fe.sprite_frag},background:{uniforms:{uvTransform:{value:new Ne},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Fe.background_vert,fragmentShader:Fe.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ne}},vertexShader:Fe.backgroundCube_vert,fragmentShader:Fe.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Fe.cube_vert,fragmentShader:Fe.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Fe.equirect_vert,fragmentShader:Fe.equirect_frag},distance:{uniforms:Pt([le.common,le.displacementmap,{referencePosition:{value:new A},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Fe.distance_vert,fragmentShader:Fe.distance_frag},shadow:{uniforms:Pt([le.lights,le.fog,{color:{value:new Te(0)},opacity:{value:1}}]),vertexShader:Fe.shadow_vert,fragmentShader:Fe.shadow_frag}};Dn.physical={uniforms:Pt([Dn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ne},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ne},clearcoatNormalScale:{value:new $(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ne},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ne},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ne},sheen:{value:0},sheenColor:{value:new Te(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ne},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ne},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ne},transmissionSamplerSize:{value:new $},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ne},attenuationDistance:{value:0},attenuationColor:{value:new Te(0)},specularColor:{value:new Te(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ne},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ne},anisotropyVector:{value:new $},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ne}}]),vertexShader:Fe.meshphysical_vert,fragmentShader:Fe.meshphysical_frag};var Lo={r:0,b:0,g:0},Cm=new be,yp=new Ne;function Pm(r,e,t,n,i,s){let a=new Te(0),o,c,l=i===!0?0:1,h=null,u=0,p=null;function d(m){let v=m.isScene===!0?m.background:null;if(v&&v.isTexture){let g=m.backgroundBlurriness>0;v=e.get(v,g)}return v}function f(m,v){m.getRGB(Lo,Zc(r)),t.buffers.color.setClear(Lo.r,Lo.g,Lo.b,v,s)}return{getClearColor:function(){return a},setClearColor:function(m,v=1){a.set(m),l=v,f(a,l)},getClearAlpha:function(){return l},setClearAlpha:function(m){l=m,f(a,l)},render:function(m){let v=!1,g=d(m);g===null?f(a,l):g&&g.isColor&&(f(g,1),v=!0);let _=r.xr.getEnvironmentBlendMode();_==="additive"?t.buffers.color.setClear(0,0,0,1,s):_==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(r.autoClear||v)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil))},addToRenderList:function(m,v){let g=d(v);g&&(g.isCubeTexture||g.mapping===Ds)?(c===void 0&&(c=new ht(new En(1,1,1),new qt({name:"BackgroundCubeMaterial",uniforms:Vi(Dn.backgroundCube.uniforms),vertexShader:Dn.backgroundCube.vertexShader,fragmentShader:Dn.backgroundCube.fragmentShader,side:Gt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(_,y,S){this.matrixWorld.copyPosition(S.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=g,c.material.uniforms.backgroundBlurriness.value=v.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=v.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(Cm.makeRotationFromEuler(v.backgroundRotation)).transpose(),g.isCubeTexture&&g.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(yp),c.material.toneMapped=ze.getTransfer(g.colorSpace)!==je,h===g&&u===g.version&&p===r.toneMapping||(c.material.needsUpdate=!0,h=g,u=g.version,p=r.toneMapping),c.layers.enableAll(),m.unshift(c,c.geometry,c.material,0,0,null)):g&&g.isTexture&&(o===void 0&&(o=new ht(new Tr(2,2),new qt({name:"BackgroundMaterial",uniforms:Vi(Dn.background.uniforms),vertexShader:Dn.background.vertexShader,fragmentShader:Dn.background.fragmentShader,side:_i,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),o.geometry.deleteAttribute("normal"),Object.defineProperty(o.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(o)),o.material.uniforms.t2D.value=g,o.material.uniforms.backgroundIntensity.value=v.backgroundIntensity,o.material.toneMapped=ze.getTransfer(g.colorSpace)!==je,g.matrixAutoUpdate===!0&&g.updateMatrix(),o.material.uniforms.uvTransform.value.copy(g.matrix),h===g&&u===g.version&&p===r.toneMapping||(o.material.needsUpdate=!0,h=g,u=g.version,p=r.toneMapping),o.layers.enableAll(),m.unshift(o,o.geometry,o.material,0,0,null))},dispose:function(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),o!==void 0&&(o.geometry.dispose(),o.material.dispose(),o=void 0)}}}function Im(r,e){let t=r.getParameter(r.MAX_VERTEX_ATTRIBS),n={},i=l(null),s=i,a=!1;function o(g){return r.bindVertexArray(g)}function c(g){return r.deleteVertexArray(g)}function l(g){let _=[],y=[],S=[];for(let T=0;T=0){let W=F[Y],ne=X[Y];if(ne===void 0&&(Y==="instanceMatrix"&&O.instanceMatrix&&(ne=O.instanceMatrix),Y==="instanceColor"&&O.instanceColor&&(ne=O.instanceColor)),W===void 0||W.attribute!==ne||ne&&W.data!==ne.data)return!0;H++}return s.attributesNum!==H||s.index!==k})(g,S,y,T),M&&(function(O,I,N,k){let F={},X=I.attributes,H=0,z=N.getAttributes();for(let Y in z)if(z[Y].location>=0){let W=X[Y];W===void 0&&(Y==="instanceMatrix"&&O.instanceMatrix&&(W=O.instanceMatrix),Y==="instanceColor"&&O.instanceColor&&(W=O.instanceColor));let ne={};ne.attribute=W,W&&W.data&&(ne.data=W.data),F[Y]=ne,H++}s.attributes=F,s.attributesNum=H,s.index=k})(g,S,y,T),T!==null&&e.update(T,r.ELEMENT_ARRAY_BUFFER),(M||a)&&(a=!1,(function(O,I,N,k){h();let F=k.attributes,X=N.getAttributes(),H=I.defaultAttributeValues;for(let z in X){let Y=X[z];if(Y.location>=0){let W=F[z];if(W===void 0&&(z==="instanceMatrix"&&O.instanceMatrix&&(W=O.instanceMatrix),z==="instanceColor"&&O.instanceColor&&(W=O.instanceColor)),W!==void 0){let ne=W.normalized,de=W.itemSize,Ee=e.get(W);if(Ee===void 0)continue;let _e=Ee.buffer,ve=Ee.type,te=Ee.bytesPerElement,ce=ve===r.INT||ve===r.UNSIGNED_INT||W.gpuType===yo;if(W.isInterleavedBufferAttribute){let oe=W.data,me=oe.stride,Ue=W.offset;if(oe.isInstancedInterleavedBuffer){for(let Q=0;Q0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";h="mediump"}return h==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=t.precision!==void 0?t.precision:"highp",o=s(a);o!==a&&(ge("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);let c=t.logarithmicDepthBuffer===!0,l=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control");return t.reversedDepthBuffer===!0&&l===!1&&ge("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),{isWebGL2:!0,getMaxAnisotropy:function(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){let h=e.get("EXT_texture_filter_anisotropic");i=r.getParameter(h.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:s,textureFormatReadable:function(h){return h===nn||n.convert(h)===r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(h){let u=h===Ln&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(h!==Yt&&n.convert(h)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE)&&h!==Kt&&!u)},precision:a,logarithmicDepthBuffer:c,reversedDepthBuffer:l,maxTextures:r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),maxVertexTextures:r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:r.getParameter(r.MAX_TEXTURE_SIZE),maxCubemapSize:r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:r.getParameter(r.MAX_VERTEX_ATTRIBS),maxVertexUniforms:r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:r.getParameter(r.MAX_VARYING_VECTORS),maxFragmentUniforms:r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),maxSamples:r.getParameter(r.MAX_SAMPLES),samples:r.getParameter(r.SAMPLES)}}function Dm(r){let e=this,t=null,n=0,i=!1,s=!1,a=new Qt,o=new Ne,c={value:null,needsUpdate:!1};function l(h,u,p,d){let f=h!==null?h.length:0,m=null;if(f!==0){if(m=c.value,d!==!0||m===null){let v=p+4*f,g=u.matrixWorldInverse;o.getNormalMatrix(g),(m===null||m.length0),e.numPlanes=n,e.numIntersection=0})();else{let g=s?0:n,_=4*g,y=v.clippingState||null;c.value=y,y=l(d,u,_,p);for(let S=0;S!==_;++S)y[S]=t[S];v.clippingState=y,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=g}}}yp.set(-1,0,0,0,1,0,0,0,1);var Zd=[.125,.215,.35,.446,.526,.582],Os=20,Fs=new pi,Jd=new Te,rh=null,sh=0,ah=0,oh=!1,Um=new A,Do=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,i=100,s={}){let{size:a=256,position:o=Um}=s;rh=this._renderer.getRenderTarget(),sh=this._renderer.getActiveCubeFace(),ah=this._renderer.getActiveMipmapLevel(),oh=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,i,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=ep(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Qd(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;ea-4?f=Zd[p-a+4-1]:p===0&&(f=0),c.push(f);let m=1/(d-2),v=-m,g=1+m,_=[v,v,g,v,g,g,v,v,g,g,v,g],y=6,S=6,T=3,M=2,P=1,O=new Float32Array(T*S*y),I=new Float32Array(M*S*y),N=new Float32Array(P*S*y);for(let F=0;F2?0:-1,z=[X,H,0,X+2/3,H,0,X+2/3,H+1,0,X,H,0,X+2/3,H+1,0,X,H+1,0];O.set(z,T*S*F),I.set(_,M*S*F);let Y=[F,F,F,F,F,F];N.set(Y,P*S*F)}let k=new Ze;k.setAttribute("position",new _t(O,T)),k.setAttribute("uv",new _t(I,M)),k.setAttribute("faceIndex",new _t(N,P)),l.push(new ht(k,null)),h>4&&h--}return{lodMeshes:l,sizeLods:o,sigmas:c}})(s)),this._blurMaterial=(function(a,o,c){let l=new Float32Array(Os),h=new A(0,1,0);return new qt({name:"SphericalGaussianBlur",defines:{n:Os,CUBEUV_TEXEL_WIDTH:1/o,CUBEUV_TEXEL_HEIGHT:1/c,CUBEUV_MAX_MIP:`${a}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:l},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:h}},vertexShader:Uo(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; - - #define ENVMAP_TYPE_CUBE_UV - #include - - vec3 getSample( float theta, vec3 axis ) { - - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - - return bilinearCubeUV( envMap, sampleDirection, mipInt ); - - } - - void main() { - - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { - - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); - - } - - axis = normalize( axis ); - - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); - - for ( int i = 1; i < n; i++ ) { - - if ( i >= samples ) { - - break; - - } - - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); - - } - - } - `,blending:Pn,depthTest:!1,depthWrite:!1})})(s,e,t),this._ggxMaterial=(function(a,o,c){return new qt({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:256,CUBEUV_TEXEL_WIDTH:1/o,CUBEUV_TEXEL_HEIGHT:1/c,CUBEUV_MAX_MIP:`${a}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Uo(),fragmentShader:` - - precision highp float; - precision highp int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform float roughness; - uniform float mipInt; - - #define ENVMAP_TYPE_CUBE_UV - #include - - #define PI 3.14159265359 - - // Van der Corput radical inverse - float radicalInverse_VdC(uint bits) { - bits = (bits << 16u) | (bits >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // / 0x100000000 - } - - // Hammersley sequence - vec2 hammersley(uint i, uint N) { - return vec2(float(i) / float(N), radicalInverse_VdC(i)); - } - - // GGX VNDF importance sampling (Eric Heitz 2018) - // "Sampling the GGX Distribution of Visible Normals" - // https://jcgt.org/published/0007/04/01/ - vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { - float alpha = roughness * roughness; - - // Section 4.1: Orthonormal basis - vec3 T1 = vec3(1.0, 0.0, 0.0); - vec3 T2 = cross(V, T1); - - // Section 4.2: Parameterization of projected area - float r = sqrt(Xi.x); - float phi = 2.0 * PI * Xi.y; - float t1 = r * cos(phi); - float t2 = r * sin(phi); - float s = 0.5 * (1.0 + V.z); - t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; - - // Section 4.3: Reprojection onto hemisphere - vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; - - // Section 3.4: Transform back to ellipsoid configuration - return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); - } - - void main() { - vec3 N = normalize(vOutputDirection); - vec3 V = N; // Assume view direction equals normal for pre-filtering - - vec3 prefilteredColor = vec3(0.0); - float totalWeight = 0.0; - - // For very low roughness, just sample the environment directly - if (roughness < 0.001) { - gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); - return; - } - - // Tangent space basis for VNDF sampling - vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 tangent = normalize(cross(up, N)); - vec3 bitangent = cross(N, tangent); - - for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { - vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); - - // For PMREM, V = N, so in tangent space V is always (0, 0, 1) - vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); - - // Transform H back to world space - vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); - vec3 L = normalize(2.0 * dot(V, H) * H - V); - - float NdotL = max(dot(N, L), 0.0); - - if(NdotL > 0.0) { - // Sample environment at fixed mip level - // VNDF importance sampling handles the distribution filtering - vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); - - // Weight by NdotL for the split-sum approximation - // VNDF PDF naturally accounts for the visible microfacet distribution - prefilteredColor += sampleColor * NdotL; - totalWeight += NdotL; - } - } - - if (totalWeight > 0.0) { - prefilteredColor = prefilteredColor / totalWeight; - } - - gl_FragColor = vec4(prefilteredColor, 1.0); - } - `,blending:Pn,depthTest:!1,depthWrite:!1})})(s,e,t)}return i}_compileMaterial(e){let t=new ht(new Ze,e);this._renderer.compile(t,Fs)}_sceneToCubeUV(e,t,n,i,s){let a=new gt(90,1,t,n),o=[1,-1,1,1,1,1],c=[1,1,1,-1,-1,-1],l=this._renderer,h=l.autoClear,u=l.toneMapping;l.getClearColor(Jd),l.toneMapping=fn,l.autoClear=!1,l.state.buffers.depth.getReversed()&&(l.setRenderTarget(i),l.clearDepth(),l.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new ht(new En,new mn({name:"PMREM.Background",side:Gt,depthWrite:!1,depthTest:!1})));let p=this._backgroundBox,d=p.material,f=!1,m=e.background;m?m.isColor&&(d.color.copy(m),e.background=null,f=!0):(d.color.copy(Jd),f=!0);for(let v=0;v<6;v++){let g=v%3;g===0?(a.up.set(0,o[v],0),a.position.set(s.x,s.y,s.z),a.lookAt(s.x+c[v],s.y,s.z)):g===1?(a.up.set(0,0,o[v]),a.position.set(s.x,s.y,s.z),a.lookAt(s.x,s.y+c[v],s.z)):(a.up.set(0,o[v],0),a.position.set(s.x,s.y,s.z),a.lookAt(s.x,s.y,s.z+c[v]));let _=this._cubeSize;Or(i,g*_,v>2?_:0,_,_),l.setRenderTarget(i),f&&l.render(p,a),l.render(e,a)}l.toneMapping=u,l.autoClear=h,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===Ir||e.mapping===Fi;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=ep()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Qd());let s=i?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s,s.uniforms.envMap.value=e;let o=this._cubeSize;Or(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(a,Fs)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodMeshes.length;for(let s=1;sp-4?n-p+4:0),m=4*(this._cubeSize-d);c.envMap.value=e.texture,c.roughness.value=u,c.mipInt.value=p-t,Or(s,f,m,3*d,2*d),i.setRenderTarget(s),i.render(o,Fs),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=p-n,Or(e,f,m,3*d,2*d),i.setRenderTarget(e),i.render(o,Fs)}_blur(e,t,n,i,s){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,i,"latitudinal",s),this._halfBlur(a,e,n,n,i,"longitudinal",s)}_halfBlur(e,t,n,i,s,a,o){let c=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&we("blur direction must be either latitudinal or longitudinal!");let h=this._lodMeshes[i];h.material=l;let u=l.uniforms,p=this._sizeLods[n]-1,d=isFinite(s)?Math.PI/(2*p):2*Math.PI/39,f=s/d,m=isFinite(s)?1+Math.floor(3*f):Os;m>Os&&ge(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);let v=[],g=0;for(let S=0;S_-4?i-_+4:0),4*(this._cubeSize-y),3*y,2*y),c.setRenderTarget(t),c.render(h,Fs)}};function $d(r,e,t){let n=new Xt(r,e,t);return n.texture.mapping=Ds,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Or(r,e,t,n,i){r.viewport.set(e,t,n,i),r.scissor.set(e,t,n,i)}function Qd(){return new qt({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Uo(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - - #include - - void main() { - - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); - - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - - } - `,blending:Pn,depthTest:!1,depthWrite:!1})}function ep(){return new qt({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Uo(),fragmentShader:` - - precision mediump float; - precision mediump int; - - uniform float flipEnvMap; - - varying vec3 vOutputDirection; - - uniform samplerCube envMap; - - void main() { - - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - - } - `,blending:Pn,depthTest:!1,depthWrite:!1})}function Uo(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}var Oo=class extends Xt{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new ds(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` - - varying vec3 vWorldDirection; - - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - - } - - void main() { - - vWorldDirection = transformDirection( position, modelMatrix ); - - #include - #include - - } - `,fragmentShader:` - - uniform sampler2D tEquirect; - - varying vec3 vWorldDirection; - - #include - - void main() { - - vec3 direction = normalize( vWorldDirection ); - - vec2 sampleUV = equirectUv( direction ); - - gl_FragColor = texture2D( tEquirect, sampleUV ); - - } - `},i=new En(5,5,5),s=new qt({name:"CubemapFromEquirect",uniforms:Vi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Gt,blending:Pn});s.uniforms.tEquirect.value=t;let a=new ht(i,s),o=t.minFilter;return t.minFilter===In&&(t.minFilter=vt),new uo(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,i);e.setRenderTarget(s)}};function Om(r){let e=new WeakMap,t=new WeakMap,n=null;function i(o,c){return c===go?o.mapping=Ir:c===_o&&(o.mapping=Fi),o}function s(o){let c=o.target;c.removeEventListener("dispose",s);let l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function a(o){let c=o.target;c.removeEventListener("dispose",a);let l=t.get(c);l!==void 0&&(t.delete(c),l.dispose())}return{get:function(o,c=!1){return o==null?null:c?(function(l){if(l&&l.isTexture){let h=l.mapping,u=h===go||h===_o,p=h===Ir||h===Fi;if(u||p){let d=t.get(l),f=d!==void 0?d.texture.pmremVersion:0;if(l.isRenderTargetTexture&&l.pmremVersion!==f)return n===null&&(n=new Do(r)),d=u?n.fromEquirectangular(l,d):n.fromCubemap(l,d),d.texture.pmremVersion=l.pmremVersion,t.set(l,d),d.texture;if(d!==void 0)return d.texture;{let m=l.image;return u&&m&&m.height>0||p&&m&&(function(v){let g=0,_=6;for(let y=0;y<_;y++)v[y]!==void 0&&g++;return g===_})(m)?(n===null&&(n=new Do(r)),d=u?n.fromEquirectangular(l):n.fromCubemap(l),d.texture.pmremVersion=l.pmremVersion,t.set(l,d),l.addEventListener("dispose",a),d.texture):null}}}return l})(o):(function(l){if(l&&l.isTexture){let h=l.mapping;if(h===go||h===_o){if(e.has(l))return i(e.get(l).texture,l.mapping);{let u=l.image;if(u&&u.height>0){let p=new Oo(u.height);return p.fromEquirectangularTexture(r,l),e.set(l,p),l.addEventListener("dispose",s),i(p.texture,l.mapping)}return null}}}return l})(o)},dispose:function(){e=new WeakMap,t=new WeakMap,n!==null&&(n.dispose(),n=null)}}}function Fm(r){let e={};function t(n){if(e[n]!==void 0)return e[n];let i=r.getExtension(n);return e[n]=i,i}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){let i=t(n);return i===null&&Ri("WebGLRenderer: "+n+" extension not supported."),i}}}function Bm(r,e,t,n){let i={},s=new WeakMap;function a(c){let l=c.target;l.index!==null&&e.remove(l.index);for(let u in l.attributes)e.remove(l.attributes[u]);l.removeEventListener("dispose",a),delete i[l.id];let h=s.get(l);h&&(e.remove(h),s.delete(l)),n.releaseStatesOfGeometry(l),l.isInstancedBufferGeometry===!0&&delete l._maxInstanceCount,t.memory.geometries--}function o(c){let l=[],h=c.index,u=c.attributes.position,p=0;if(u===void 0)return;if(h!==null){let m=h.array;p=h.version;for(let v=0,g=m.length;v=65535?ss:rs)(l,1);d.version=p;let f=s.get(c);f&&e.remove(f),s.set(c,d)}return{get:function(c,l){return i[l.id]===!0||(l.addEventListener("dispose",a),i[l.id]=!0,t.memory.geometries++),l},update:function(c){let l=c.attributes;for(let h in l)e.update(l[h],r.ARRAY_BUFFER)},getWireframeAttribute:function(c){let l=s.get(c);if(l){let h=c.index;h!==null&&l.versione.maxTextureSize&&(S=Math.ceil(y/e.maxTextureSize),y=e.maxTextureSize);let T=new Float32Array(y*S*4*h),M=new ts(T,y,S,h);M.type=Kt,M.needsUpdate=!0;let P=4*_;for(let I=0;I - #include - - void main() { - gl_FragColor = texture2D( tDiffuse, vUv ); - - #ifdef LINEAR_TONE_MAPPING - gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); - #elif defined( REINHARD_TONE_MAPPING ) - gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); - #elif defined( CINEON_TONE_MAPPING ) - gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); - #elif defined( ACES_FILMIC_TONE_MAPPING ) - gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); - #elif defined( AGX_TONE_MAPPING ) - gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); - #elif defined( NEUTRAL_TONE_MAPPING ) - gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); - #elif defined( CUSTOM_TONE_MAPPING ) - gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); - #endif - - #ifdef SRGB_TRANSFER - gl_FragColor = sRGBTransferOETF( gl_FragColor ); - #endif - }`,depthTest:!1,depthWrite:!1}),h=new ht(c,l),u=new pi(-1,1,1,-1,0,1),p,d=null,f=null,m=!1,v=null,g=[],_=!1;this.setSize=function(y,S){a.setSize(y,S),o.setSize(y,S);for(let T=0;T0&&g[0].isRenderPass===!0;let S=a.width,T=a.height;for(let M=0;M0)return r;let i=e*t,s=tp[i];if(s===void 0&&(s=new Float32Array(i),tp[i]=s),e!==0){n.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,r[a].toArray(s,o)}return s}function Mt(r,e){if(r.length!==e.length)return!1;for(let t=0,n=r.length;t0&&(this.seq=i.concat(s))}setValue(e,t,n,i){let s=this.map[t];s!==void 0&&s.setValue(e,n,i)}setOptional(e,t,n){let i=t[n];i!==void 0&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let s=0,a=t.length;s!==a;++s){let o=t[s],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,i)}}static seqWithValue(e,t){let n=[];for(let i=0,s=e.length;i!==s;++i){let a=e[i];a.id in t&&n.push(a)}return n}};function op(r,e,t){let n=r.createShader(e);return r.shaderSource(n,t),r.compileShader(n),n}var If=0,lp=new Ne;function cp(r,e,t){let n=r.getShaderParameter(e,r.COMPILE_STATUS),i=(r.getShaderInfoLog(e)||"").trim();if(n&&i==="")return"";let s=/ERROR: 0:(\d+)/.exec(i);if(s){let a=parseInt(s[1]);return t.toUpperCase()+` - -`+i+` - -`+(function(o,c){let l=o.split(` -`),h=[],u=Math.max(c-6,0),p=Math.min(c+6,l.length);for(let d=u;d":" "} ${f}: ${l[d]}`)}return h.join(` -`)})(r.getShaderSource(e),a)}return i}function Lf(r,e){let t=(function(n){ze._getMatrix(lp,ze.workingColorSpace,n);let i=`mat3( ${lp.elements.map(s=>s.toFixed(4))} )`;switch(ze.getTransfer(n)){case Qr:return[i,"LinearTransferOETF"];case je:return[i,"sRGBTransferOETF"];default:return ge("WebGLProgram: Unsupported color space: ",n),[i,"LinearTransferOETF"]}})(e);return[`vec4 ${r}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}var Nf={[ic]:"Linear",[rc]:"Reinhard",[sc]:"Cineon",[Ns]:"ACESFilmic",[oc]:"AgX",[lc]:"Neutral",[ac]:"Custom"};function Df(r,e){let t=Nf[e];return t===void 0?(ge("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+r+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+r+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}var No=new A;function Uf(){return ze.getLuminanceCoefficients(No),["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${No.x.toFixed(4)}, ${No.y.toFixed(4)}, ${No.z.toFixed(4)} );`," return dot( weights, rgb );","}"].join(` -`)}function Bs(r){return r!==""}function hp(r,e){let t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return r.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function up(r,e){return r.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}var Of=/^[ \t]*#include +<([\w\d./]+)>/gm;function mh(r){return r.replace(Of,Bf)}var Ff=new Map;function Bf(r,e){let t=Fe[e];if(t===void 0){let n=Ff.get(e);if(n===void 0)throw new Error("THREE.WebGLProgram: Can not resolve #include <"+e+">");t=Fe[n],ge('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n)}return mh(t)}var zf=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function dp(r){return r.replace(zf,Gf)}function Gf(r,e,t,n){let i="";for(let s=parseInt(e);s0&&(v+=` -`),g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,f].filter(Bs).join(` -`),g.length>0&&(g+=` -`)):(v=[pp(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,f,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(Bs).join(` -`),g=[pp(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,f,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==fn?"#define TONE_MAPPING":"",t.toneMapping!==fn?Fe.tonemapping_pars_fragment:"",t.toneMapping!==fn?Df("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Fe.colorspace_pars_fragment,Lf("linearToOutputTexel",t.outputColorSpace),Uf(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` -`].filter(Bs).join(` -`)),a=mh(a),a=hp(a,t),a=up(a,t),o=mh(o),o=hp(o,t),o=up(o,t),a=dp(a),o=dp(o),t.isRawShaderMaterial!==!0&&(_=`#version 300 es -`,v=[d,"#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+v,g=["#define varying in",t.glslVersion===Yc?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Yc?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` -`)+` -`+g);let y=_+v+a,S=_+g+o,T=op(i,i.VERTEX_SHADER,y),M=op(i,i.FRAGMENT_SHADER,S);function P(k){if(r.debug.checkShaderErrors){let F=i.getProgramInfoLog(m)||"",X=i.getShaderInfoLog(T)||"",H=i.getShaderInfoLog(M)||"",z=F.trim(),Y=X.trim(),W=H.trim(),ne=!0,de=!0;if(i.getProgramParameter(m,i.LINK_STATUS)===!1)if(ne=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(i,m,T,M);else{let Ee=cp(i,T,"vertex"),_e=cp(i,M,"fragment");we("WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(m,i.VALIDATE_STATUS)+` - -Material Name: `+k.name+` -Material Type: `+k.type+` - -Program Info Log: `+z+` -`+Ee+` -`+_e)}else z!==""?ge("WebGLProgram: Program Info Log:",z):Y!==""&&W!==""||(de=!1);de&&(k.diagnostics={runnable:ne,programLog:z,vertexShader:{log:Y,prefix:v},fragmentShader:{log:W,prefix:g}})}i.deleteShader(T),i.deleteShader(M),O=new Fr(i,m),I=(function(F,X){let H={},z=F.getProgramParameter(X,F.ACTIVE_ATTRIBUTES);for(let Y=0;Y0,L=m.clearcoat>0,w=m.dispersion>0,V=m.iridescence>0,j=m.sheen>0,K=m.transmission>0,re=D&&!!m.anisotropyMap,ye=L&&!!m.clearcoatMap,xe=L&&!!m.clearcoatNormalMap,he=L&&!!m.clearcoatRoughnessMap,Ce=V&&!!m.iridescenceMap,ee=V&&!!m.iridescenceThicknessMap,se=j&&!!m.sheenColorMap,ie=j&&!!m.sheenRoughnessMap,pe=!!m.specularMap,Qe=!!m.specularColorMap,Xe=!!m.specularIntensityMap,ot=K&&!!m.transmissionMap,It=K&&!!m.thicknessMap,Se=!!m.gradientMap,qe=!!m.alphaMap,Be=m.alphaTest>0,At=!!m.alphaHash,et=!!m.extensions,yt=fn;m.toneMapped&&(de!==null&&de.isXRRenderTarget!==!0||(yt=r.toneMapping));let at={shaderID:k,shaderType:m.type,shaderName:m.name,vertexShader:H,fragmentShader:z,defines:m.defines,customVertexShaderID:Y,customFragmentShaderID:W,isRawShaderMaterial:m.isRawShaderMaterial===!0,glslVersion:m.glslVersion,precision:p,batching:ve,batchingColor:ve&&y._colorsTexture!==null,instancing:_e,instancingColor:_e&&y.instanceColor!==null,instancingMorph:_e&&y.morphTexture!==null,outputColorSpace:de===null?r.outputColorSpace:de.isXRRenderTarget===!0?de.texture.colorSpace:ze.workingColorSpace,alphaToCoverage:!!m.alphaToCoverage,map:te,matcap:ce,envMap:oe,envMapMode:oe&&I.mapping,envMapCubeUVHeight:N,aoMap:me,lightMap:Ue,bumpMap:Q,normalMap:C,displacementMap:b,emissiveMap:R,normalMapObjectSpace:C&&m.normalMapType===Nd,normalMapTangentSpace:C&&m.normalMapType===qc,packedNormalMap:C&&m.normalMapType===qc&&(Zt=m.normalMap.format,Zt===Gi||Zt===Ro||Zt===Co),metalnessMap:U,roughnessMap:x,anisotropy:D,anisotropyMap:re,clearcoat:L,clearcoatMap:ye,clearcoatNormalMap:xe,clearcoatRoughnessMap:he,dispersion:w,iridescence:V,iridescenceMap:Ce,iridescenceThicknessMap:ee,sheen:j,sheenColorMap:se,sheenRoughnessMap:ie,specularMap:pe,specularColorMap:Qe,specularIntensityMap:Xe,transmission:K,transmissionMap:ot,thicknessMap:It,gradientMap:Se,opaque:m.transparent===!1&&m.blending===Ls&&m.alphaToCoverage===!1,alphaMap:qe,alphaTest:Be,alphaHash:At,combine:m.combine,mapUv:te&&f(m.map.channel),aoMapUv:me&&f(m.aoMap.channel),lightMapUv:Ue&&f(m.lightMap.channel),bumpMapUv:Q&&f(m.bumpMap.channel),normalMapUv:C&&f(m.normalMap.channel),displacementMapUv:b&&f(m.displacementMap.channel),emissiveMapUv:R&&f(m.emissiveMap.channel),metalnessMapUv:U&&f(m.metalnessMap.channel),roughnessMapUv:x&&f(m.roughnessMap.channel),anisotropyMapUv:re&&f(m.anisotropyMap.channel),clearcoatMapUv:ye&&f(m.clearcoatMap.channel),clearcoatNormalMapUv:xe&&f(m.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:he&&f(m.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&f(m.iridescenceMap.channel),iridescenceThicknessMapUv:ee&&f(m.iridescenceThicknessMap.channel),sheenColorMapUv:se&&f(m.sheenColorMap.channel),sheenRoughnessMapUv:ie&&f(m.sheenRoughnessMap.channel),specularMapUv:pe&&f(m.specularMap.channel),specularColorMapUv:Qe&&f(m.specularColorMap.channel),specularIntensityMapUv:Xe&&f(m.specularIntensityMap.channel),transmissionMapUv:ot&&f(m.transmissionMap.channel),thicknessMapUv:It&&f(m.thicknessMap.channel),alphaMapUv:qe&&f(m.alphaMap.channel),vertexTangents:!!M.attributes.tangent&&(C||D),vertexNormals:!!M.attributes.normal,vertexColors:m.vertexColors,vertexAlphas:m.vertexColors===!0&&!!M.attributes.color&&M.attributes.color.itemSize===4,pointsUvs:y.isPoints===!0&&!!M.attributes.uv&&(te||qe),fog:!!T,useFog:m.fog===!0,fogExp2:!!T&&T.isFogExp2,flatShading:m.wireframe===!1&&(m.flatShading===!0||M.attributes.normal===void 0&&C===!1&&(m.isMeshLambertMaterial||m.isMeshPhongMaterial||m.isMeshStandardMaterial||m.isMeshPhysicalMaterial)),sizeAttenuation:m.sizeAttenuation===!0,logarithmicDepthBuffer:u,reversedDepthBuffer:Ee,skinning:y.isSkinnedMesh===!0,hasPositionAttribute:M.attributes.position!==void 0,morphTargets:M.morphAttributes.position!==void 0,morphNormals:M.morphAttributes.normal!==void 0,morphColors:M.morphAttributes.color!==void 0,morphTargetsCount:X,morphTextureStride:ne,numDirLights:v.directional.length,numPointLights:v.point.length,numSpotLights:v.spot.length,numSpotLightMaps:v.spotLightMap.length,numRectAreaLights:v.rectArea.length,numHemiLights:v.hemi.length,numDirLightShadows:v.directionalShadowMap.length,numPointLightShadows:v.pointShadowMap.length,numSpotLightShadows:v.spotShadowMap.length,numSpotLightShadowsWithMaps:v.numSpotLightShadowsWithMaps,numLightProbes:v.numLightProbes,numLightProbeGrids:S.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:m.dithering,shadowMapEnabled:r.shadowMap.enabled&&g.length>0,shadowMapType:r.shadowMap.type,toneMapping:yt,decodeVideoTexture:te&&m.map.isVideoTexture===!0&&ze.getTransfer(m.map.colorSpace)===je,decodeVideoTextureEmissive:R&&m.emissiveMap.isVideoTexture===!0&&ze.getTransfer(m.emissiveMap.colorSpace)===je,premultipliedAlpha:m.premultipliedAlpha,doubleSided:m.side===tn,flipSided:m.side===Gt,useDepthPacking:m.depthPacking>=0,depthPacking:m.depthPacking||0,index0AttributeName:m.index0AttributeName,extensionClipCullDistance:et&&m.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(et&&m.extensions.multiDraw===!0||ve)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:m.customProgramCacheKey()};var Zt;return at.vertexUv1s=c.has(1),at.vertexUv2s=c.has(2),at.vertexUv3s=c.has(3),c.clear(),at},getProgramCacheKey:function(m){let v=[];if(m.shaderID?v.push(m.shaderID):(v.push(m.customVertexShaderID),v.push(m.customFragmentShaderID)),m.defines!==void 0)for(let g in m.defines)v.push(g),v.push(m.defines[g]);return m.isRawShaderMaterial===!1&&((function(g,_){g.push(_.precision),g.push(_.outputColorSpace),g.push(_.envMapMode),g.push(_.envMapCubeUVHeight),g.push(_.mapUv),g.push(_.alphaMapUv),g.push(_.lightMapUv),g.push(_.aoMapUv),g.push(_.bumpMapUv),g.push(_.normalMapUv),g.push(_.displacementMapUv),g.push(_.emissiveMapUv),g.push(_.metalnessMapUv),g.push(_.roughnessMapUv),g.push(_.anisotropyMapUv),g.push(_.clearcoatMapUv),g.push(_.clearcoatNormalMapUv),g.push(_.clearcoatRoughnessMapUv),g.push(_.iridescenceMapUv),g.push(_.iridescenceThicknessMapUv),g.push(_.sheenColorMapUv),g.push(_.sheenRoughnessMapUv),g.push(_.specularMapUv),g.push(_.specularColorMapUv),g.push(_.specularIntensityMapUv),g.push(_.transmissionMapUv),g.push(_.thicknessMapUv),g.push(_.combine),g.push(_.fogExp2),g.push(_.sizeAttenuation),g.push(_.morphTargetsCount),g.push(_.morphAttributeCount),g.push(_.numDirLights),g.push(_.numPointLights),g.push(_.numSpotLights),g.push(_.numSpotLightMaps),g.push(_.numHemiLights),g.push(_.numRectAreaLights),g.push(_.numDirLightShadows),g.push(_.numPointLightShadows),g.push(_.numSpotLightShadows),g.push(_.numSpotLightShadowsWithMaps),g.push(_.numLightProbes),g.push(_.shadowMapType),g.push(_.toneMapping),g.push(_.numClippingPlanes),g.push(_.numClipIntersection),g.push(_.depthPacking)})(v,m),(function(g,_){a.disableAll(),_.instancing&&a.enable(0),_.instancingColor&&a.enable(1),_.instancingMorph&&a.enable(2),_.matcap&&a.enable(3),_.envMap&&a.enable(4),_.normalMapObjectSpace&&a.enable(5),_.normalMapTangentSpace&&a.enable(6),_.clearcoat&&a.enable(7),_.iridescence&&a.enable(8),_.alphaTest&&a.enable(9),_.vertexColors&&a.enable(10),_.vertexAlphas&&a.enable(11),_.vertexUv1s&&a.enable(12),_.vertexUv2s&&a.enable(13),_.vertexUv3s&&a.enable(14),_.vertexTangents&&a.enable(15),_.anisotropy&&a.enable(16),_.alphaHash&&a.enable(17),_.batching&&a.enable(18),_.dispersion&&a.enable(19),_.batchingColor&&a.enable(20),_.gradientMap&&a.enable(21),_.packedNormalMap&&a.enable(22),_.vertexNormals&&a.enable(23),g.push(a.mask),a.disableAll(),_.fog&&a.enable(0),_.useFog&&a.enable(1),_.flatShading&&a.enable(2),_.logarithmicDepthBuffer&&a.enable(3),_.reversedDepthBuffer&&a.enable(4),_.skinning&&a.enable(5),_.morphTargets&&a.enable(6),_.morphNormals&&a.enable(7),_.morphColors&&a.enable(8),_.premultipliedAlpha&&a.enable(9),_.shadowMapEnabled&&a.enable(10),_.doubleSided&&a.enable(11),_.flipSided&&a.enable(12),_.useDepthPacking&&a.enable(13),_.dithering&&a.enable(14),_.transmission&&a.enable(15),_.sheen&&a.enable(16),_.opaque&&a.enable(17),_.pointsUvs&&a.enable(18),_.decodeVideoTexture&&a.enable(19),_.decodeVideoTextureEmissive&&a.enable(20),_.alphaToCoverage&&a.enable(21),_.numLightProbeGrids>0&&a.enable(22),_.hasPositionAttribute&&a.enable(23),g.push(a.mask)})(v,m),v.push(r.outputColorSpace)),v.push(m.customProgramCacheKey),v.join()},getUniforms:function(m){let v=d[m.type],g;if(v){let _=Dn[v];g=Yd.clone(_.uniforms)}else g=m.uniforms;return g},acquireProgram:function(m,v){let g=h.get(v);return g!==void 0?++g.usedTimes:(g=new Xf(r,v,m,i),l.push(g),h.set(v,g)),g},releaseProgram:function(m){if(--m.usedTimes===0){let v=l.indexOf(m);l[v]=l[l.length-1],l.pop(),h.delete(m.cacheKey),m.destroy()}},releaseShaderCache:function(m){o.remove(m)},programs:l,dispose:function(){o.dispose()}}}function Yf(){let r=new WeakMap;return{has:function(e){return r.has(e)},get:function(e){let t=r.get(e);return t===void 0&&(t={},r.set(e,t)),t},remove:function(e){r.delete(e)},update:function(e,t,n){r.get(e)[t]=n},dispose:function(){r=new WeakMap}}}function Kf(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.material.id!==e.material.id?r.material.id-e.material.id:r.materialVariant!==e.materialVariant?r.materialVariant-e.materialVariant:r.z!==e.z?r.z-e.z:r.id-e.id}function mp(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function fp(){let r=[],e=0,t=[],n=[],i=[];function s(o){let c=0;return o.isInstancedMesh&&(c+=2),o.isSkinnedMesh&&(c+=1),c}function a(o,c,l,h,u,p){let d=r[e];return d===void 0?(d={id:o.id,object:o,geometry:c,material:l,materialVariant:s(o),groupOrder:h,renderOrder:o.renderOrder,z:u,group:p},r[e]=d):(d.id=o.id,d.object=o,d.geometry=c,d.material=l,d.materialVariant=s(o),d.groupOrder=h,d.renderOrder=o.renderOrder,d.z=u,d.group=p),e++,d}return{opaque:t,transmissive:n,transparent:i,init:function(){e=0,t.length=0,n.length=0,i.length=0},push:function(o,c,l,h,u,p){let d=a(o,c,l,h,u,p);l.transmission>0?n.push(d):l.transparent===!0?i.push(d):t.push(d)},unshift:function(o,c,l,h,u,p){let d=a(o,c,l,h,u,p);l.transmission>0?n.unshift(d):l.transparent===!0?i.unshift(d):t.unshift(d)},finish:function(){for(let o=e,c=r.length;o1&&t.sort(o||Kf),n.length>1&&n.sort(c||mp),i.length>1&&i.sort(c||mp),l&&(t.reverse(),n.reverse(),i.reverse())}}}function Zf(){let r=new WeakMap;return{get:function(e,t){let n=r.get(e),i;return n===void 0?(i=new fp,r.set(e,[i])):t>=n.length?(i=new fp,n.push(i)):i=n[t],i},dispose:function(){r=new WeakMap}}}function Jf(){let r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new A,color:new Te};break;case"SpotLight":t={position:new A,direction:new A,color:new Te,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new A,color:new Te,distance:0,decay:0};break;case"HemisphereLight":t={direction:new A,skyColor:new Te,groundColor:new Te};break;case"RectAreaLight":t={color:new Te,position:new A,halfWidth:new A,halfHeight:new A}}return r[e.id]=t,t}}}var $f=0;function Qf(r,e){return(e.castShadow?2:0)-(r.castShadow?2:0)+(e.map?1:0)-(r.map?1:0)}function eg(r){let e=new Jf,t=(function(){let o={};return{get:function(c){if(o[c.id]!==void 0)return o[c.id];let l;switch(c.type){case"DirectionalLight":case"SpotLight":l={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new $};break;case"PointLight":l={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new $,shadowCameraNear:1,shadowCameraFar:1e3}}return o[c.id]=l,l}}})(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let o=0;o<9;o++)n.probe.push(new A);let i=new A,s=new be,a=new be;return{setup:function(o){let c=0,l=0,h=0;for(let P=0;P<9;P++)n.probe[P].set(0,0,0);let u=0,p=0,d=0,f=0,m=0,v=0,g=0,_=0,y=0,S=0,T=0;o.sort(Qf);for(let P=0,O=o.length;P0&&(r.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=le.LTC_FLOAT_1,n.rectAreaLTC2=le.LTC_FLOAT_2):(n.rectAreaLTC1=le.LTC_HALF_1,n.rectAreaLTC2=le.LTC_HALF_2)),n.ambient[0]=c,n.ambient[1]=l,n.ambient[2]=h;let M=n.hash;M.directionalLength===u&&M.pointLength===p&&M.spotLength===d&&M.rectAreaLength===f&&M.hemiLength===m&&M.numDirectionalShadows===v&&M.numPointShadows===g&&M.numSpotShadows===_&&M.numSpotMaps===y&&M.numLightProbes===T||(n.directional.length=u,n.spot.length=d,n.rectArea.length=f,n.point.length=p,n.hemi.length=m,n.directionalShadow.length=v,n.directionalShadowMap.length=v,n.pointShadow.length=g,n.pointShadowMap.length=g,n.spotShadow.length=_,n.spotShadowMap.length=_,n.directionalShadowMatrix.length=v,n.pointShadowMatrix.length=g,n.spotLightMatrix.length=_+y-S,n.spotLightMap.length=y,n.numSpotLightShadowsWithMaps=S,n.numLightProbes=T,M.directionalLength=u,M.pointLength=p,M.spotLength=d,M.rectAreaLength=f,M.hemiLength=m,M.numDirectionalShadows=v,M.numPointShadows=g,M.numSpotShadows=_,M.numSpotMaps=y,M.numLightProbes=T,n.version=$f++)},setupView:function(o,c){let l=0,h=0,u=0,p=0,d=0,f=c.matrixWorldInverse;for(let m=0,v=o.length;m=i.length?(s=new gp(r),i.push(s)):s=i[n],s},dispose:function(){e=new WeakMap}}}var ng=[new A(1,0,0),new A(-1,0,0),new A(0,1,0),new A(0,-1,0),new A(0,0,1),new A(0,0,-1)],ig=[new A(0,-1,0),new A(0,-1,0),new A(0,0,1),new A(0,0,-1),new A(0,-1,0),new A(0,-1,0)],_p=new be,zs=new A,ch=new A;function rg(r,e,t){let n=new Zn,i=new $,s=new $,a=new Ke,o=new no,c=new io,l={},h=t.maxTextureSize,u={[_i]:Gt,[Gt]:_i,[tn]:tn},p=new qt({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new $},radius:{value:4}},vertexShader:`void main() { - gl_Position = vec4( position, 1.0 ); -}`,fragmentShader:`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); - gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); -}`}),d=p.clone();d.defines.HORIZONTAL_PASS=1;let f=new Ze;f.setAttribute("position",new _t(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let m=new ht(f,p),v=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Oi;let g=this.type;function _(M,P){let O=e.update(m);p.defines.VSM_SAMPLES!==M.blurSamples&&(p.defines.VSM_SAMPLES=M.blurSamples,d.defines.VSM_SAMPLES=M.blurSamples,p.needsUpdate=!0,d.needsUpdate=!0),M.mapPass===null&&(M.mapPass=new Xt(i.x,i.y,{format:Gi,type:Ln})),p.uniforms.shadow_pass.value=M.map.depthTexture,p.uniforms.resolution.value=M.mapSize,p.uniforms.radius.value=M.radius,r.setRenderTarget(M.mapPass),r.clear(),r.renderBufferDirect(P,null,O,p,m,null),d.uniforms.shadow_pass.value=M.mapPass.texture,d.uniforms.resolution.value=M.mapSize,d.uniforms.radius.value=M.radius,r.setRenderTarget(M.map),r.clear(),r.renderBufferDirect(P,null,O,d,m,null)}function y(M,P,O,I){let N=null,k=O.isPointLight===!0?M.customDistanceMaterial:M.customDepthMaterial;if(k!==void 0)N=k;else if(N=O.isPointLight===!0?c:o,r.localClippingEnabled&&P.clipShadows===!0&&Array.isArray(P.clippingPlanes)&&P.clippingPlanes.length!==0||P.displacementMap&&P.displacementScale!==0||P.alphaMap&&P.alphaTest>0||P.map&&P.alphaTest>0||P.alphaToCoverage===!0){let F=N.uuid,X=P.uuid,H=l[F];H===void 0&&(H={},l[F]=H);let z=H[X];z===void 0&&(z=N.clone(),H[X]=z,P.addEventListener("dispose",T)),N=z}return N.visible=P.visible,N.wireframe=P.wireframe,N.side=I===Cr?P.shadowSide!==null?P.shadowSide:P.side:P.shadowSide!==null?P.shadowSide:u[P.side],N.alphaMap=P.alphaMap,N.alphaTest=P.alphaToCoverage===!0?.5:P.alphaTest,N.map=P.map,N.clipShadows=P.clipShadows,N.clippingPlanes=P.clippingPlanes,N.clipIntersection=P.clipIntersection,N.displacementMap=P.displacementMap,N.displacementScale=P.displacementScale,N.displacementBias=P.displacementBias,N.wireframeLinewidth=P.wireframeLinewidth,N.linewidth=P.linewidth,O.isPointLight===!0&&N.isMeshDistanceMaterial===!0&&(r.properties.get(N).light=O),N}function S(M,P,O,I,N){if(M.visible===!1)return;if(M.layers.test(P.layers)&&(M.isMesh||M.isLine||M.isPoints)&&(M.castShadow||M.receiveShadow&&N===Cr)&&(!M.frustumCulled||n.intersectsObject(M))){M.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse,M.matrixWorld);let F=e.update(M),X=M.material;if(Array.isArray(X)){let H=F.groups;for(let z=0,Y=H.length;zz.needsUpdate=!0):H.material.needsUpdate=!0)});for(let H=0,z=M.length;Hh||i.y>h)&&(i.x>h&&(s.x=Math.floor(h/ne.x),i.x=s.x*ne.x,W.mapSize.x=s.x),i.y>h&&(s.y=Math.floor(h/ne.y),i.y=s.y*ne.y,W.mapSize.y=s.y));let de=r.state.buffers.depth.getReversed();if(W.camera._reversedDepth=de,W.map===null||X===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Cr){if(Y.isPointLight){ge("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new Xt(i.x,i.y,{format:Gi,type:Ln,minFilter:vt,magFilter:vt,generateMipmaps:!1}),W.map.texture.name=Y.name+".shadowMap",W.map.depthTexture=new Jn(i.x,i.y,Kt),W.map.depthTexture.name=Y.name+".shadowMapDepth",W.map.depthTexture.format=vi,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Nt,W.map.depthTexture.magFilter=Nt}else Y.isPointLight?(W.map=new Oo(i.x),W.map.depthTexture=new Ia(i.x,ti)):(W.map=new Xt(i.x,i.y),W.map.depthTexture=new Jn(i.x,i.y,ti)),W.map.depthTexture.name=Y.name+".shadowMap",W.map.depthTexture.format=vi,this.type===Oi?(W.map.depthTexture.compareFunction=de?Io:Po,W.map.depthTexture.minFilter=vt,W.map.depthTexture.magFilter=vt):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Nt,W.map.depthTexture.magFilter=Nt);W.camera.updateProjectionMatrix()}let Ee=W.map.isWebGLCubeRenderTarget?6:1;for(let _e=0;_e=1):Y.indexOf("OpenGL ES")!==-1&&(z=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),H=z>=2);let W=null,ne={},de=r.getParameter(r.SCISSOR_BOX),Ee=r.getParameter(r.VIEWPORT),_e=new Ke().fromArray(de),ve=new Ke().fromArray(Ee);function te(x,D,L,w){let V=new Uint8Array(4),j=r.createTexture();r.bindTexture(x,j),r.texParameteri(x,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(x,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let K=0;KR||x.height>R)&&(U=R/Math.max(x.width,x.height)),U<1){if(typeof HTMLImageElement<"u"&&C instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&C instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&C instanceof ImageBitmap||typeof VideoFrame<"u"&&C instanceof VideoFrame){let D=Math.floor(U*x.width),L=Math.floor(U*x.height);p===void 0&&(p=m(D,L));let w=b?m(D,L):p;return w.width=D,w.height=L,w.getContext("2d").drawImage(C,0,0,D,L),ge("WebGLRenderer: Texture has been resized from ("+x.width+"x"+x.height+") to ("+D+"x"+L+")."),w}return"data"in C&&ge("WebGLRenderer: Image in DataTexture is too big ("+x.width+"x"+x.height+")."),C}return C}function g(C){return C.generateMipmaps}function _(C){r.generateMipmap(C)}function y(C){return C.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:C.isWebGL3DRenderTarget?r.TEXTURE_3D:C.isWebGLArrayRenderTarget||C.isCompressedArrayTexture?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D}function S(C,b,R,U,x,D=!1){if(C!==null){if(r[C]!==void 0)return r[C];ge("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+C+"'")}let L;U&&(L=e.get("EXT_texture_norm16"),L||ge("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let w=b;if(b===r.RED&&(R===r.FLOAT&&(w=r.R32F),R===r.HALF_FLOAT&&(w=r.R16F),R===r.UNSIGNED_BYTE&&(w=r.R8),R===r.UNSIGNED_SHORT&&L&&(w=L.R16_EXT),R===r.SHORT&&L&&(w=L.R16_SNORM_EXT)),b===r.RED_INTEGER&&(R===r.UNSIGNED_BYTE&&(w=r.R8UI),R===r.UNSIGNED_SHORT&&(w=r.R16UI),R===r.UNSIGNED_INT&&(w=r.R32UI),R===r.BYTE&&(w=r.R8I),R===r.SHORT&&(w=r.R16I),R===r.INT&&(w=r.R32I)),b===r.RG&&(R===r.FLOAT&&(w=r.RG32F),R===r.HALF_FLOAT&&(w=r.RG16F),R===r.UNSIGNED_BYTE&&(w=r.RG8),R===r.UNSIGNED_SHORT&&L&&(w=L.RG16_EXT),R===r.SHORT&&L&&(w=L.RG16_SNORM_EXT)),b===r.RG_INTEGER&&(R===r.UNSIGNED_BYTE&&(w=r.RG8UI),R===r.UNSIGNED_SHORT&&(w=r.RG16UI),R===r.UNSIGNED_INT&&(w=r.RG32UI),R===r.BYTE&&(w=r.RG8I),R===r.SHORT&&(w=r.RG16I),R===r.INT&&(w=r.RG32I)),b===r.RGB_INTEGER&&(R===r.UNSIGNED_BYTE&&(w=r.RGB8UI),R===r.UNSIGNED_SHORT&&(w=r.RGB16UI),R===r.UNSIGNED_INT&&(w=r.RGB32UI),R===r.BYTE&&(w=r.RGB8I),R===r.SHORT&&(w=r.RGB16I),R===r.INT&&(w=r.RGB32I)),b===r.RGBA_INTEGER&&(R===r.UNSIGNED_BYTE&&(w=r.RGBA8UI),R===r.UNSIGNED_SHORT&&(w=r.RGBA16UI),R===r.UNSIGNED_INT&&(w=r.RGBA32UI),R===r.BYTE&&(w=r.RGBA8I),R===r.SHORT&&(w=r.RGBA16I),R===r.INT&&(w=r.RGBA32I)),b===r.RGB&&(R===r.UNSIGNED_SHORT&&L&&(w=L.RGB16_EXT),R===r.SHORT&&L&&(w=L.RGB16_SNORM_EXT),R===r.UNSIGNED_INT_5_9_9_9_REV&&(w=r.RGB9_E5),R===r.UNSIGNED_INT_10F_11F_11F_REV&&(w=r.R11F_G11F_B10F)),b===r.RGBA){let V=D?Qr:ze.getTransfer(x);R===r.FLOAT&&(w=r.RGBA32F),R===r.HALF_FLOAT&&(w=r.RGBA16F),R===r.UNSIGNED_BYTE&&(w=V===je?r.SRGB8_ALPHA8:r.RGBA8),R===r.UNSIGNED_SHORT&&L&&(w=L.RGBA16_EXT),R===r.SHORT&&L&&(w=L.RGBA16_SNORM_EXT),R===r.UNSIGNED_SHORT_4_4_4_4&&(w=r.RGBA4),R===r.UNSIGNED_SHORT_5_5_5_1&&(w=r.RGB5_A1)}return w!==r.R16F&&w!==r.R32F&&w!==r.RG16F&&w!==r.RG32F&&w!==r.RGBA16F&&w!==r.RGBA32F||e.get("EXT_color_buffer_float"),w}function T(C,b){let R;return C?b===null||b===ti||b===Dr?R=r.DEPTH24_STENCIL8:b===Kt?R=r.DEPTH32F_STENCIL8:b===Nr&&(R=r.DEPTH24_STENCIL8,ge("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):b===null||b===ti||b===Dr?R=r.DEPTH_COMPONENT24:b===Kt?R=r.DEPTH_COMPONENT32F:b===Nr&&(R=r.DEPTH_COMPONENT16),R}function M(C,b){return g(C)===!0||C.isFramebufferTexture&&C.minFilter!==Nt&&C.minFilter!==vt?Math.log2(Math.max(b.width,b.height))+1:C.mipmaps!==void 0&&C.mipmaps.length>0?C.mipmaps.length:C.isCompressedTexture&&Array.isArray(C.image)?b.mipmaps.length:1}function P(C){let b=C.target;b.removeEventListener("dispose",P),(function(R){let U=n.get(R);if(U.__webglInit===void 0)return;let x=R.source,D=d.get(x);if(D){let L=D[U.__cacheKey];L.usedTimes--,L.usedTimes===0&&I(R),Object.keys(D).length===0&&d.delete(x)}n.remove(R)})(b),b.isVideoTexture&&h.delete(b),b.isHTMLTexture&&u.delete(b)}function O(C){let b=C.target;b.removeEventListener("dispose",O),(function(R){let U=n.get(R);if(R.depthTexture&&(R.depthTexture.dispose(),n.remove(R.depthTexture)),R.isWebGLCubeRenderTarget)for(let D=0;D<6;D++){if(Array.isArray(U.__webglFramebuffer[D]))for(let L=0;L0&&R.__version!==C.version){let U=C.image;if(U===null)ge("WebGLRenderer: Texture marked for update but no image data found.");else{if(U.complete!==!1)return void ne(R,C,b);ge("WebGLRenderer: Texture marked for update but image is incomplete")}}else C.isExternalTexture&&(R.__webglTexture=C.sourceTexture?C.sourceTexture:null);t.bindTexture(r.TEXTURE_2D,R.__webglTexture,r.TEXTURE0+b)}let F={[hi]:r.REPEAT,[Tn]:r.CLAMP_TO_EDGE,[hr]:r.MIRRORED_REPEAT},X={[Nt]:r.NEAREST,[vo]:r.NEAREST_MIPMAP_NEAREST,[Bi]:r.NEAREST_MIPMAP_LINEAR,[vt]:r.LINEAR,[Lr]:r.LINEAR_MIPMAP_NEAREST,[In]:r.LINEAR_MIPMAP_LINEAR},H={[Dd]:r.NEVER,[zd]:r.ALWAYS,[Ud]:r.LESS,[Po]:r.LEQUAL,[Od]:r.EQUAL,[Io]:r.GEQUAL,[Fd]:r.GREATER,[Bd]:r.NOTEQUAL};function z(C,b){if(b.type!==Kt||e.has("OES_texture_float_linear")!==!1||b.magFilter!==vt&&b.magFilter!==Lr&&b.magFilter!==Bi&&b.magFilter!==In&&b.minFilter!==vt&&b.minFilter!==Lr&&b.minFilter!==Bi&&b.minFilter!==In||ge("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(C,r.TEXTURE_WRAP_S,F[b.wrapS]),r.texParameteri(C,r.TEXTURE_WRAP_T,F[b.wrapT]),C!==r.TEXTURE_3D&&C!==r.TEXTURE_2D_ARRAY||r.texParameteri(C,r.TEXTURE_WRAP_R,F[b.wrapR]),r.texParameteri(C,r.TEXTURE_MAG_FILTER,X[b.magFilter]),r.texParameteri(C,r.TEXTURE_MIN_FILTER,X[b.minFilter]),b.compareFunction&&(r.texParameteri(C,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(C,r.TEXTURE_COMPARE_FUNC,H[b.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(b.magFilter===Nt||b.minFilter!==Bi&&b.minFilter!==In||b.type===Kt&&e.has("OES_texture_float_linear")===!1)return;if(b.anisotropy>1||n.get(b).__currentAnisotropy){let R=e.get("EXT_texture_filter_anisotropic");r.texParameterf(C,R.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,i.getMaxAnisotropy())),n.get(b).__currentAnisotropy=b.anisotropy}}}function Y(C,b){let R=!1;C.__webglInit===void 0&&(C.__webglInit=!0,b.addEventListener("dispose",P));let U=b.source,x=d.get(U);x===void 0&&(x={},d.set(U,x));let D=(function(L){let w=[];return w.push(L.wrapS),w.push(L.wrapT),w.push(L.wrapR||0),w.push(L.magFilter),w.push(L.minFilter),w.push(L.anisotropy),w.push(L.internalFormat),w.push(L.format),w.push(L.type),w.push(L.generateMipmaps),w.push(L.premultiplyAlpha),w.push(L.flipY),w.push(L.unpackAlignment),w.push(L.colorSpace),w.join()})(b);if(D!==C.__cacheKey){x[D]===void 0&&(x[D]={texture:r.createTexture(),usedTimes:0},a.memory.textures++,R=!0),x[D].usedTimes++;let L=x[C.__cacheKey];L!==void 0&&(x[C.__cacheKey].usedTimes--,L.usedTimes===0&&I(b)),C.__cacheKey=D,C.__webglTexture=x[D].texture}return R}function W(C,b,R){return Math.floor(Math.floor(C/R)/b)}function ne(C,b,R){let U=r.TEXTURE_2D;(b.isDataArrayTexture||b.isCompressedArrayTexture)&&(U=r.TEXTURE_2D_ARRAY),b.isData3DTexture&&(U=r.TEXTURE_3D);let x=Y(C,b),D=b.source;t.bindTexture(U,C.__webglTexture,r.TEXTURE0+R);let L=n.get(D);if(D.version!==L.__version||x===!0){if(t.activeTexture(r.TEXTURE0+R),!(typeof ImageBitmap<"u"&&b.image instanceof ImageBitmap)){let se=ze.getPrimaries(ze.workingColorSpace),ie=b.colorSpace===ki?null:ze.getPrimaries(b.colorSpace),pe=b.colorSpace===ki||se===ie?r.NONE:r.BROWSER_DEFAULT_WEBGL;t.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,b.flipY),t.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),t.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,pe)}t.pixelStorei(r.UNPACK_ALIGNMENT,b.unpackAlignment);let w=v(b.image,!1,i.maxTextureSize);w=Ue(b,w);let V=s.convert(b.format,b.colorSpace),j=s.convert(b.type),K,re=S(b.internalFormat,V,j,b.normalized,b.colorSpace,b.isVideoTexture);z(U,b);let ye=b.mipmaps,xe=b.isVideoTexture!==!0,he=L.__version===void 0||x===!0,Ce=D.dataReady,ee=M(b,w);if(b.isDepthTexture)re=T(b.format===zi,b.type),he&&(xe?t.texStorage2D(r.TEXTURE_2D,1,re,w.width,w.height):t.texImage2D(r.TEXTURE_2D,0,re,w.width,w.height,0,V,j,null));else if(b.isDataTexture)if(ye.length>0){xe&&he&&t.texStorage2D(r.TEXTURE_2D,ee,re,ye[0].width,ye[0].height);for(let se=0,ie=ye.length;seBe.start-At.start);let ot=0;for(let Be=1;Be0){let pe=$c(K.width,K.height,b.format,b.type);for(let Qe of b.layerUpdates){let Xe=K.data.subarray(Qe*pe/K.data.BYTES_PER_ELEMENT,(Qe+1)*pe/K.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,se,0,0,Qe,K.width,K.height,1,V,Xe)}b.clearLayerUpdates()}else t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,se,0,0,0,K.width,K.height,w.depth,V,K.data)}else t.compressedTexImage3D(r.TEXTURE_2D_ARRAY,se,re,K.width,K.height,w.depth,0,K.data,0,0);else ge("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else xe?Ce&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,se,0,0,0,K.width,K.height,w.depth,V,j,K.data):t.texImage3D(r.TEXTURE_2D_ARRAY,se,re,K.width,K.height,w.depth,0,V,j,K.data)}else{xe&&he&&t.texStorage2D(r.TEXTURE_2D,ee,re,ye[0].width,ye[0].height);for(let se=0,ie=ye.length;se0){let se=$c(w.width,w.height,b.format,b.type);for(let ie of b.layerUpdates){let pe=w.data.subarray(ie*se/w.data.BYTES_PER_ELEMENT,(ie+1)*se/w.data.BYTES_PER_ELEMENT);t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,ie,w.width,w.height,1,V,j,pe)}b.clearLayerUpdates()}else t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,w.width,w.height,w.depth,V,j,w.data)}else t.texImage3D(r.TEXTURE_2D_ARRAY,0,re,w.width,w.height,w.depth,0,V,j,w.data);else if(b.isData3DTexture)xe?(he&&t.texStorage3D(r.TEXTURE_3D,ee,re,w.width,w.height,w.depth),Ce&&t.texSubImage3D(r.TEXTURE_3D,0,0,0,0,w.width,w.height,w.depth,V,j,w.data)):t.texImage3D(r.TEXTURE_3D,0,re,w.width,w.height,w.depth,0,V,j,w.data);else if(b.isFramebufferTexture){if(he)if(xe)t.texStorage2D(r.TEXTURE_2D,ee,re,w.width,w.height);else{let se=w.width,ie=w.height;for(let pe=0;pe>=1,ie>>=1}}else if(b.isHTMLTexture){if("texElementImage2D"in r){let se=r.canvas;if(se.hasAttribute("layoutsubtree")||se.setAttribute("layoutsubtree","true"),w.parentNode!==se)return se.appendChild(w),u.add(b),se.onpaint=ie=>{let pe=ie.changedElements;for(let Qe of u)pe.includes(Qe.image)&&(Qe.needsUpdate=!0)},void se.requestPaint();if(r.texElementImage2D.length===3)r.texElementImage2D(r.TEXTURE_2D,r.RGBA8,w);else{let pe=r.RGBA,Qe=r.RGBA,Xe=r.UNSIGNED_BYTE;r.texElementImage2D(r.TEXTURE_2D,0,pe,Qe,Xe,w)}r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)}}else if(ye.length>0){if(xe&&he){let se=Q(ye[0]);t.texStorage2D(r.TEXTURE_2D,ee,re,se.width,se.height)}for(let se=0,ie=ye.length;se>D),ye=Math.max(1,b.height>>D);x===r.TEXTURE_3D||x===r.TEXTURE_2D_ARRAY?t.texImage3D(x,D,V,re,ye,b.depth,0,L,w,null):t.texImage2D(x,D,V,re,ye,0,L,w,null)}t.bindFramebuffer(r.FRAMEBUFFER,C),me(b)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,U,x,K.__webglTexture,0,oe(b)):(x===r.TEXTURE_2D||x>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&x<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,U,x,K.__webglTexture,D),t.bindFramebuffer(r.FRAMEBUFFER,null)}function Ee(C,b,R){if(r.bindRenderbuffer(r.RENDERBUFFER,C),b.depthBuffer){let U=b.depthTexture,x=U&&U.isDepthTexture?U.type:null,D=T(b.stencilBuffer,x),L=b.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;me(b)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,oe(b),D,b.width,b.height):R?r.renderbufferStorageMultisample(r.RENDERBUFFER,oe(b),D,b.width,b.height):r.renderbufferStorage(r.RENDERBUFFER,D,b.width,b.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,L,r.RENDERBUFFER,C)}else{let U=b.textures;for(let x=0;x{delete b.__boundDepthTexture,delete b.__depthDisposeCallback,U.removeEventListener("dispose",x)};U.addEventListener("dispose",x),b.__depthDisposeCallback=x}b.__boundDepthTexture=U}if(C.depthTexture&&!b.__autoAllocateDepthBuffer)if(R)for(let U=0;U<6;U++)_e(b.__webglFramebuffer[U],C,U);else{let U=C.texture.mipmaps;U&&U.length>0?_e(b.__webglFramebuffer[0],C,0):_e(b.__webglFramebuffer,C,0)}else if(R){b.__webglDepthbuffer=[];for(let U=0;U<6;U++)if(t.bindFramebuffer(r.FRAMEBUFFER,b.__webglFramebuffer[U]),b.__webglDepthbuffer[U]===void 0)b.__webglDepthbuffer[U]=r.createRenderbuffer(),Ee(b.__webglDepthbuffer[U],C,!1);else{let x=C.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,D=b.__webglDepthbuffer[U];r.bindRenderbuffer(r.RENDERBUFFER,D),r.framebufferRenderbuffer(r.FRAMEBUFFER,x,r.RENDERBUFFER,D)}}else{let U=C.texture.mipmaps;if(U&&U.length>0?t.bindFramebuffer(r.FRAMEBUFFER,b.__webglFramebuffer[0]):t.bindFramebuffer(r.FRAMEBUFFER,b.__webglFramebuffer),b.__webglDepthbuffer===void 0)b.__webglDepthbuffer=r.createRenderbuffer(),Ee(b.__webglDepthbuffer,C,!1);else{let x=C.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,D=b.__webglDepthbuffer;r.bindRenderbuffer(r.RENDERBUFFER,D),r.framebufferRenderbuffer(r.FRAMEBUFFER,x,r.RENDERBUFFER,D)}}t.bindFramebuffer(r.FRAMEBUFFER,null)}let te=[],ce=[];function oe(C){return Math.min(i.maxSamples,C.samples)}function me(C){let b=n.get(C);return C.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&b.__useRenderToTexture!==!1}function Ue(C,b){let R=C.colorSpace,U=C.format,x=C.type;return C.isCompressedTexture===!0||C.isVideoTexture===!0||R!==Dt&&R!==ki&&(ze.getTransfer(R)===je?U===nn&&x===Yt||ge("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):we("WebGLTextures: Unsupported texture color space:",R)),b}function Q(C){return typeof HTMLImageElement<"u"&&C instanceof HTMLImageElement?(l.width=C.naturalWidth||C.width,l.height=C.naturalHeight||C.height):typeof VideoFrame<"u"&&C instanceof VideoFrame?(l.width=C.displayWidth,l.height=C.displayHeight):(l.width=C.width,l.height=C.height),l}this.allocateTextureUnit=function(){let C=N;return C>=i.maxTextures&&ge("WebGLTextures: Trying to use "+C+" texture units while this GPU supports only "+i.maxTextures),N+=1,C},this.resetTextureUnits=function(){N=0},this.getTextureUnits=function(){return N},this.setTextureUnits=function(C){N=C},this.setTexture2D=k,this.setTexture2DArray=function(C,b){let R=n.get(C);C.isRenderTargetTexture===!1&&C.version>0&&R.__version!==C.version?ne(R,C,b):(C.isExternalTexture&&(R.__webglTexture=C.sourceTexture?C.sourceTexture:null),t.bindTexture(r.TEXTURE_2D_ARRAY,R.__webglTexture,r.TEXTURE0+b))},this.setTexture3D=function(C,b){let R=n.get(C);C.isRenderTargetTexture===!1&&C.version>0&&R.__version!==C.version?ne(R,C,b):t.bindTexture(r.TEXTURE_3D,R.__webglTexture,r.TEXTURE0+b)},this.setTextureCube=function(C,b){let R=n.get(C);C.isCubeDepthTexture!==!0&&C.version>0&&R.__version!==C.version?(function(U,x,D){if(x.image.length!==6)return;let L=Y(U,x),w=x.source;t.bindTexture(r.TEXTURE_CUBE_MAP,U.__webglTexture,r.TEXTURE0+D);let V=n.get(w);if(w.version!==V.__version||L===!0){t.activeTexture(r.TEXTURE0+D);let j=ze.getPrimaries(ze.workingColorSpace),K=x.colorSpace===ki?null:ze.getPrimaries(x.colorSpace),re=x.colorSpace===ki||j===K?r.NONE:r.BROWSER_DEFAULT_WEBGL;t.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,x.flipY),t.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),t.pixelStorei(r.UNPACK_ALIGNMENT,x.unpackAlignment),t.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,re);let ye=x.isCompressedTexture||x.image[0].isCompressedTexture,xe=x.image[0]&&x.image[0].isDataTexture,he=[];for(let Se=0;Se<6;Se++)he[Se]=ye||xe?xe?x.image[Se].image:x.image[Se]:v(x.image[Se],!0,i.maxCubemapSize),he[Se]=Ue(x,he[Se]);let Ce=he[0],ee=s.convert(x.format,x.colorSpace),se=s.convert(x.type),ie=S(x.internalFormat,ee,se,x.normalized,x.colorSpace),pe=x.isVideoTexture!==!0,Qe=V.__version===void 0||L===!0,Xe=w.dataReady,ot,It=M(x,Ce);if(z(r.TEXTURE_CUBE_MAP,x),ye){pe&&Qe&&t.texStorage2D(r.TEXTURE_CUBE_MAP,It,ie,Ce.width,Ce.height);for(let Se=0;Se<6;Se++){ot=he[Se].mipmaps;for(let qe=0;qe0&&It++;let Se=Q(he[0]);t.texStorage2D(r.TEXTURE_CUBE_MAP,It,ie,Se.width,Se.height)}for(let Se=0;Se<6;Se++)if(xe){pe?Xe&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Se,0,0,0,he[Se].width,he[Se].height,ee,se,he[Se].data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Se,0,ie,he[Se].width,he[Se].height,0,ee,se,he[Se].data);for(let qe=0;qe1;if(L||(U.__webglTexture===void 0&&(U.__webglTexture=r.createTexture()),U.__version=b.version,a.memory.textures++),D){R.__webglFramebuffer=[];for(let w=0;w<6;w++)if(b.mipmaps&&b.mipmaps.length>0){R.__webglFramebuffer[w]=[];for(let V=0;V0){R.__webglFramebuffer=[];for(let w=0;w0&&me(C)===!1){R.__webglMultisampledFramebuffer=r.createFramebuffer(),R.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,R.__webglMultisampledFramebuffer);for(let w=0;w0)for(let V=0;V0)for(let V=0;V0){if(me(C)===!1){let b=C.textures,R=C.width,U=C.height,x=r.COLOR_BUFFER_BIT,D=C.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,L=n.get(C),w=b.length>1;if(w)for(let j=0;j0?t.bindFramebuffer(r.DRAW_FRAMEBUFFER,L.__webglFramebuffer[0]):t.bindFramebuffer(r.DRAW_FRAMEBUFFER,L.__webglFramebuffer);for(let j=0;j= 1.0 ) { - - gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; - - } else { - - gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; - - } - -}`,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ht(new Tr(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},vh=class extends pn{constructor(e,t){super();let n=this,i=null,s=1,a=null,o="local-floor",c=1,l=null,h=null,u=null,p=null,d=null,f=null,m=typeof XRWebGLBinding<"u",v=new _h,g={},_=t.getContextAttributes(),y=null,S=null,T=[],M=[],P=new $,O=null,I=new gt;I.viewport=new Ke;let N=new gt;N.viewport=new Ke;let k=[I,N],F=new po,X=null,H=null;function z(te){let ce=M.indexOf(te.inputSource);if(ce===-1)return;let oe=T[ce];oe!==void 0&&(oe.update(te.inputSource,te.frame,l||a),oe.dispatchEvent({type:te.type,data:te.inputSource}))}function Y(){i.removeEventListener("select",z),i.removeEventListener("selectstart",z),i.removeEventListener("selectend",z),i.removeEventListener("squeeze",z),i.removeEventListener("squeezestart",z),i.removeEventListener("squeezeend",z),i.removeEventListener("end",Y),i.removeEventListener("inputsourceschange",W);for(let te=0;te=0&&(M[me]=null,T[me].disconnect(oe))}for(let ce=0;ce=M.length){M.push(oe),me=Q;break}if(M[Q]===null){M[Q]=oe,me=Q;break}}if(me===-1)break}let Ue=T[me];Ue&&Ue.connect(oe)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(te){let ce=T[te];return ce===void 0&&(ce=new fr,T[te]=ce),ce.getTargetRaySpace()},this.getControllerGrip=function(te){let ce=T[te];return ce===void 0&&(ce=new fr,T[te]=ce),ce.getGripSpace()},this.getHand=function(te){let ce=T[te];return ce===void 0&&(ce=new fr,T[te]=ce),ce.getHandSpace()},this.setFramebufferScaleFactor=function(te){s=te,n.isPresenting===!0&&ge("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(te){o=te,n.isPresenting===!0&&ge("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(te){l=te},this.getBaseLayer=function(){return p!==null?p:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(i,t)),u},this.getFrame=function(){return f},this.getSession=function(){return i},this.setSession=async function(te){if(i=te,i!==null){if(y=e.getRenderTarget(),i.addEventListener("select",z),i.addEventListener("selectstart",z),i.addEventListener("selectend",z),i.addEventListener("squeeze",z),i.addEventListener("squeezestart",z),i.addEventListener("squeezeend",z),i.addEventListener("end",Y),i.addEventListener("inputsourceschange",W),_.xrCompatible!==!0&&await t.makeXRCompatible(),O=e.getPixelRatio(),e.getSize(P),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let ce=null,oe=null,me=null;_.depth&&(me=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ce=_.stencil?zi:vi,oe=_.stencil?Dr:ti);let Ue={colorFormat:t.RGBA8,depthFormat:me,scaleFactor:s};u=this.getBinding(),p=u.createProjectionLayer(Ue),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),S=new Xt(p.textureWidth,p.textureHeight,{format:nn,type:Yt,depthTexture:new Jn(p.textureWidth,p.textureHeight,oe,void 0,void 0,void 0,void 0,void 0,void 0,ce),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}else{let ce={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:s};d=new XRWebGLLayer(i,t,ce),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),S=new Xt(d.framebufferWidth,d.framebufferHeight,{format:nn,type:Yt,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(c),l=null,a=await i.requestReferenceSpace(o),ve.setContext(i),ve.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return v.getDepthTexture()};let ne=new A,de=new A;function Ee(te,ce){ce===null?te.matrixWorld.copy(te.matrix):te.matrixWorld.multiplyMatrices(ce.matrixWorld,te.matrix),te.matrixWorldInverse.copy(te.matrixWorld).invert()}this.updateCamera=function(te){if(i===null)return;let ce=te.near,oe=te.far;v.texture!==null&&(v.depthNear>0&&(ce=v.depthNear),v.depthFar>0&&(oe=v.depthFar)),F.near=N.near=I.near=ce,F.far=N.far=I.far=oe,X===F.near&&H===F.far||(i.updateRenderState({depthNear:F.near,depthFar:F.far}),X=F.near,H=F.far),F.layers.mask=6|te.layers.mask,I.layers.mask=-5&F.layers.mask,N.layers.mask=-3&F.layers.mask;let me=te.parent,Ue=F.cameras;Ee(F,me);for(let Q=0;Q0&&(i.alphaTest.value=s.alphaTest);let a=e.get(s),o=a.envMap,c=a.envMapRotation;o&&(i.envMap.value=o,i.envMapRotation.value.setFromMatrix4(lg.makeRotationFromEuler(c)).transpose(),o.isCubeTexture&&o.isRenderTargetTexture===!1&&i.envMapRotation.value.premultiply(Tp),i.reflectivity.value=s.reflectivity,i.ior.value=s.ior,i.refractionRatio.value=s.refractionRatio),s.lightMap&&(i.lightMap.value=s.lightMap,i.lightMapIntensity.value=s.lightMapIntensity,t(s.lightMap,i.lightMapTransform)),s.aoMap&&(i.aoMap.value=s.aoMap,i.aoMapIntensity.value=s.aoMapIntensity,t(s.aoMap,i.aoMapTransform))}return{refreshFogUniforms:function(i,s){s.color.getRGB(i.fogColor.value,Zc(r)),s.isFog?(i.fogNear.value=s.near,i.fogFar.value=s.far):s.isFogExp2&&(i.fogDensity.value=s.density)},refreshMaterialUniforms:function(i,s,a,o,c){s.isNodeMaterial?s.uniformsNeedUpdate=!1:s.isMeshBasicMaterial?n(i,s):s.isMeshLambertMaterial?(n(i,s),s.envMap&&(i.envMapIntensity.value=s.envMapIntensity)):s.isMeshToonMaterial?(n(i,s),(function(l,h){h.gradientMap&&(l.gradientMap.value=h.gradientMap)})(i,s)):s.isMeshPhongMaterial?(n(i,s),(function(l,h){l.specular.value.copy(h.specular),l.shininess.value=Math.max(h.shininess,1e-4)})(i,s),s.envMap&&(i.envMapIntensity.value=s.envMapIntensity)):s.isMeshStandardMaterial?(n(i,s),(function(l,h){l.metalness.value=h.metalness,h.metalnessMap&&(l.metalnessMap.value=h.metalnessMap,t(h.metalnessMap,l.metalnessMapTransform)),l.roughness.value=h.roughness,h.roughnessMap&&(l.roughnessMap.value=h.roughnessMap,t(h.roughnessMap,l.roughnessMapTransform)),h.envMap&&(l.envMapIntensity.value=h.envMapIntensity)})(i,s),s.isMeshPhysicalMaterial&&(function(l,h,u){l.ior.value=h.ior,h.sheen>0&&(l.sheenColor.value.copy(h.sheenColor).multiplyScalar(h.sheen),l.sheenRoughness.value=h.sheenRoughness,h.sheenColorMap&&(l.sheenColorMap.value=h.sheenColorMap,t(h.sheenColorMap,l.sheenColorMapTransform)),h.sheenRoughnessMap&&(l.sheenRoughnessMap.value=h.sheenRoughnessMap,t(h.sheenRoughnessMap,l.sheenRoughnessMapTransform))),h.clearcoat>0&&(l.clearcoat.value=h.clearcoat,l.clearcoatRoughness.value=h.clearcoatRoughness,h.clearcoatMap&&(l.clearcoatMap.value=h.clearcoatMap,t(h.clearcoatMap,l.clearcoatMapTransform)),h.clearcoatRoughnessMap&&(l.clearcoatRoughnessMap.value=h.clearcoatRoughnessMap,t(h.clearcoatRoughnessMap,l.clearcoatRoughnessMapTransform)),h.clearcoatNormalMap&&(l.clearcoatNormalMap.value=h.clearcoatNormalMap,t(h.clearcoatNormalMap,l.clearcoatNormalMapTransform),l.clearcoatNormalScale.value.copy(h.clearcoatNormalScale),h.side===Gt&&l.clearcoatNormalScale.value.negate())),h.dispersion>0&&(l.dispersion.value=h.dispersion),h.iridescence>0&&(l.iridescence.value=h.iridescence,l.iridescenceIOR.value=h.iridescenceIOR,l.iridescenceThicknessMinimum.value=h.iridescenceThicknessRange[0],l.iridescenceThicknessMaximum.value=h.iridescenceThicknessRange[1],h.iridescenceMap&&(l.iridescenceMap.value=h.iridescenceMap,t(h.iridescenceMap,l.iridescenceMapTransform)),h.iridescenceThicknessMap&&(l.iridescenceThicknessMap.value=h.iridescenceThicknessMap,t(h.iridescenceThicknessMap,l.iridescenceThicknessMapTransform))),h.transmission>0&&(l.transmission.value=h.transmission,l.transmissionSamplerMap.value=u.texture,l.transmissionSamplerSize.value.set(u.width,u.height),h.transmissionMap&&(l.transmissionMap.value=h.transmissionMap,t(h.transmissionMap,l.transmissionMapTransform)),l.thickness.value=h.thickness,h.thicknessMap&&(l.thicknessMap.value=h.thicknessMap,t(h.thicknessMap,l.thicknessMapTransform)),l.attenuationDistance.value=h.attenuationDistance,l.attenuationColor.value.copy(h.attenuationColor)),h.anisotropy>0&&(l.anisotropyVector.value.set(h.anisotropy*Math.cos(h.anisotropyRotation),h.anisotropy*Math.sin(h.anisotropyRotation)),h.anisotropyMap&&(l.anisotropyMap.value=h.anisotropyMap,t(h.anisotropyMap,l.anisotropyMapTransform))),l.specularIntensity.value=h.specularIntensity,l.specularColor.value.copy(h.specularColor),h.specularColorMap&&(l.specularColorMap.value=h.specularColorMap,t(h.specularColorMap,l.specularColorMapTransform)),h.specularIntensityMap&&(l.specularIntensityMap.value=h.specularIntensityMap,t(h.specularIntensityMap,l.specularIntensityMapTransform))})(i,s,c)):s.isMeshMatcapMaterial?(n(i,s),(function(l,h){h.matcap&&(l.matcap.value=h.matcap)})(i,s)):s.isMeshDepthMaterial?n(i,s):s.isMeshDistanceMaterial?(n(i,s),(function(l,h){let u=e.get(h).light;l.referencePosition.value.setFromMatrixPosition(u.matrixWorld),l.nearDistance.value=u.shadow.camera.near,l.farDistance.value=u.shadow.camera.far})(i,s)):s.isMeshNormalMaterial?n(i,s):s.isLineBasicMaterial?((function(l,h){l.diffuse.value.copy(h.color),l.opacity.value=h.opacity,h.map&&(l.map.value=h.map,t(h.map,l.mapTransform))})(i,s),s.isLineDashedMaterial&&(function(l,h){l.dashSize.value=h.dashSize,l.totalSize.value=h.dashSize+h.gapSize,l.scale.value=h.scale})(i,s)):s.isPointsMaterial?(function(l,h,u,p){l.diffuse.value.copy(h.color),l.opacity.value=h.opacity,l.size.value=h.size*u,l.scale.value=.5*p,h.map&&(l.map.value=h.map,t(h.map,l.uvTransform)),h.alphaMap&&(l.alphaMap.value=h.alphaMap,t(h.alphaMap,l.alphaMapTransform)),h.alphaTest>0&&(l.alphaTest.value=h.alphaTest)})(i,s,a,o):s.isSpriteMaterial?(function(l,h){l.diffuse.value.copy(h.color),l.opacity.value=h.opacity,l.rotation.value=h.rotation,h.map&&(l.map.value=h.map,t(h.map,l.mapTransform)),h.alphaMap&&(l.alphaMap.value=h.alphaMap,t(h.alphaMap,l.alphaMapTransform)),h.alphaTest>0&&(l.alphaTest.value=h.alphaTest)})(i,s):s.isShadowMaterial?(i.color.value.copy(s.color),i.opacity.value=s.opacity):s.isShaderMaterial&&(s.uniformsNeedUpdate=!1)}}}function hg(r,e,t,n){let i={},s={},a=[],o=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function c(p,d,f,m){if((function(v,g,_,y){let S=v.value,T=g+"_"+_;if(y[T]===void 0)return typeof S=="number"||typeof S=="boolean"?y[T]=S:ArrayBuffer.isView(S)?y[T]=S.slice():y[T]=S.clone(),!0;{let M=y[T];if(typeof S=="number"||typeof S=="boolean"){if(M!==S)return y[T]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(M.equals(S)===!1)return M.copy(S),!0}}return!1})(p,d,f,m)===!0){let v=p.__offset,g=p.value;if(Array.isArray(g)){let _=0;for(let y=0;y0&&(y+=S-T),g.__size=y,g.__cache={}})(p),f=(function(g){let _=(function(){for(let M=0;M0),Yo=!!wt.morphAttributes.position,ji=!!wt.morphAttributes.normal,Op=!!wt.morphAttributes.color,hu=fn;Ie.toneMapped&&(ne!==null&&ne.isXRRenderTarget!==!0||(hu=N.toneMapping));let uu=wt.morphAttributes.position||wt.morphAttributes.normal||wt.morphAttributes.color,Fp=uu!==void 0?uu.length:0,Le=ie.get(Ie),Si=M.state.lights;if(L===!0&&(w===!0||ke!==Ee)){let mt=ke===Ee&&Ie.id===de;et.setState(Ie,ke,mt)}let on=!1;Ie.version===Le.__version?Le.needsLights&&Le.lightsStateVersion!==Si.state.version||Le.outputColorSpace!==Xs||De.isBatchedMesh&&Le.batching===!1?on=!0:De.isBatchedMesh||Le.batching!==!0?De.isBatchedMesh&&Le.batchingColor===!0&&De.colorTexture===null||De.isBatchedMesh&&Le.batchingColor===!1&&De.colorTexture!==null||De.isInstancedMesh&&Le.instancing===!1?on=!0:De.isInstancedMesh||Le.instancing!==!0?De.isSkinnedMesh&&Le.skinning===!1?on=!0:De.isSkinnedMesh||Le.skinning!==!0?De.isInstancedMesh&&Le.instancingColor===!0&&De.instanceColor===null||De.isInstancedMesh&&Le.instancingColor===!1&&De.instanceColor!==null||De.isInstancedMesh&&Le.instancingMorph===!0&&De.morphTexture===null||De.isInstancedMesh&&Le.instancingMorph===!1&&De.morphTexture!==null||Le.envMap!==vn||Ie.fog===!0&&Le.fog!==an?on=!0:Le.numClippingPlanes===void 0||Le.numClippingPlanes===et.numPlanes&&Le.numIntersection===et.numIntersection?(Le.vertexAlphas!==Xi||Le.vertexTangents!==On||Le.morphTargets!==Yo||Le.morphNormals!==ji||Le.morphColors!==Op||Le.toneMapping!==hu||Le.morphTargetsCount!==Fp||!!Le.lightProbeGrid!=M.state.lightProbeGridArray.length>0)&&(on=!0):on=!0:on=!0:on=!0:on=!0:(on=!0,Le.__version=Ie.version);let ii=Le.currentProgram;on===!0&&(ii=Ws(Ie,it,De),F&&Ie.isNodeMaterial&&F.onUpdateProgram(Ie,ii,Le));let du=!1,qi=!1,Ko=!1,rt=ii.getUniforms(),Jt=Le.uniforms;if(ee.useProgram(ii.program)&&(du=!0,qi=!0,Ko=!0),Ie.id!==de&&(de=Ie.id,qi=!0),Le.needsLights){let mt=(function(xn,Jo){if(xn.length===0)return null;if(xn.length===1)return xn[0].texture!==null?xn[0]:null;S.setFromMatrixPosition(Jo.matrixWorld);for(let Yi=0,Bp=xn.length;Yi0&&rt.setValue(B,"directionalShadowMap",Si.state.directionalShadowMap,pe),Si.state.spotShadowMap.length>0&&rt.setValue(B,"spotShadowMap",Si.state.spotShadowMap,pe),Si.state.pointShadowMap.length>0&&rt.setValue(B,"pointShadowMap",Si.state.pointShadowMap,pe)),De.isSkinnedMesh){rt.setOptional(B,De,"bindMatrix"),rt.setOptional(B,De,"bindMatrixInverse");let mt=De.skeleton;mt&&(mt.boneTexture===null&&mt.computeBoneTexture(),rt.setValue(B,"boneTexture",mt.boneTexture,pe))}De.isBatchedMesh&&(rt.setOptional(B,De,"batchingTexture"),rt.setValue(B,"batchingTexture",De._matricesTexture,pe),rt.setOptional(B,De,"batchingIdTexture"),rt.setValue(B,"batchingIdTexture",De._indirectTexture,pe),rt.setOptional(B,De,"batchingColorTexture"),De._colorsTexture!==null&&rt.setValue(B,"batchingColorTexture",De._colorsTexture,pe));let Zo=wt.morphAttributes;if(Zo.position===void 0&&Zo.normal===void 0&&Zo.color===void 0||Zt.update(De,wt,ii),(qi||Le.receiveShadow!==De.receiveShadow)&&(Le.receiveShadow=De.receiveShadow,rt.setValue(B,"receiveShadow",De.receiveShadow)),(Ie.isMeshStandardMaterial||Ie.isMeshLambertMaterial||Ie.isMeshPhongMaterial)&&Ie.envMap===null&&it.environment!==null&&(Jt.envMapIntensity.value=it.environmentIntensity),Jt.dfgLUT!==void 0&&(Jt.dfgLUT.value=(Nn===null&&(Nn=new yr(ug,16,16,Gi,Ln),Nn.name="DFG_LUT",Nn.minFilter=vt,Nn.magFilter=vt,Nn.wrapS=Tn,Nn.wrapT=Tn,Nn.generateMipmaps=!1,Nn.needsUpdate=!0),Nn)),qi){if(rt.setValue(B,"toneMappingExposure",N.toneMappingExposure),Le.needsLights&&(ln=Ko,(yn=Jt).ambientLightColor.needsUpdate=ln,yn.lightProbe.needsUpdate=ln,yn.directionalLights.needsUpdate=ln,yn.directionalLightShadows.needsUpdate=ln,yn.pointLights.needsUpdate=ln,yn.pointLightShadows.needsUpdate=ln,yn.spotLights.needsUpdate=ln,yn.spotLightShadows.needsUpdate=ln,yn.rectAreaLights.needsUpdate=ln,yn.hemisphereLights.needsUpdate=ln),an&&Ie.fog===!0&&qe.refreshFogUniforms(Jt,an),qe.refreshMaterialUniforms(Jt,Ie,Q,Ue,M.state.transmissionRenderTarget[ke.id]),Le.needsLights&&Le.lightProbeGrid){let mt=Le.lightProbeGrid;Jt.probesSH.value=mt.texture,Jt.probesMin.value.copy(mt.boundingBox.min),Jt.probesMax.value.copy(mt.boundingBox.max),Jt.probesResolution.value.copy(mt.resolution)}Fr.upload(B,lu(Le),Jt,pe)}var yn,ln;if(Ie.isShaderMaterial&&Ie.uniformsNeedUpdate===!0&&(Fr.upload(B,lu(Le),Jt,pe),Ie.uniformsNeedUpdate=!1),Ie.isSpriteMaterial&&rt.setValue(B,"center",De.center),rt.setValue(B,"modelViewMatrix",De.modelViewMatrix),rt.setValue(B,"normalMatrix",De.normalMatrix),rt.setValue(B,"modelMatrix",De.matrixWorld),Ie.uniformsGroups!==void 0){let mt=Ie.uniformsGroups;for(let xn=0,Jo=mt.length;xn{function ae(){J.forEach(function(ue){ie.get(ue).currentProgram.isReady()&&J.delete(ue)}),J.size!==0?setTimeout(ae,10):Z(E)}he.get("KHR_parallel_shader_compile")!==null?ae():setTimeout(ae,10)})};let Xo=null;function iu(){Mi.stop()}function ru(){Mi.start()}let Mi=new vp;function jo(E,G,q,J){if(E.visible===!1)return;if(E.layers.test(G.layers)){if(E.isGroup)q=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(G);else if(E.isLightProbeGrid)M.pushLightProbeGrid(E);else if(E.isLight)M.pushLight(E),E.castShadow&&M.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||D.intersectsSprite(E)){J&&K.setFromMatrixPosition(E.matrixWorld).applyMatrix4(V);let ae=It.update(E),ue=E.material;ue.visible&&T.push(E,ae,ue,q,K.z,null)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||D.intersectsObject(E))){let ae=It.update(E),ue=E.material;if(J&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),K.copy(E.boundingSphere.center)):(ae.boundingSphere===null&&ae.computeBoundingSphere(),K.copy(ae.boundingSphere.center)),K.applyMatrix4(E.matrixWorld).applyMatrix4(V)),Array.isArray(ue)){let fe=ae.groups;for(let Me=0,Pe=fe.length;Me0&&Hs(Z,G,q),ae.length>0&&Hs(ae,G,q),ue.length>0&&Hs(ue,G,q),ee.buffers.depth.setTest(!0),ee.buffers.depth.setMask(!0),ee.buffers.color.setMask(!0),ee.setPolygonOffset(!1)}function au(E,G,q,J){if((q.isScene===!0?q.overrideMaterial:null)!==null)return;if(M.state.transmissionRenderTarget[J.id]===void 0){let He=he.has("EXT_color_buffer_half_float")||he.has("EXT_color_buffer_float");M.state.transmissionRenderTarget[J.id]=new Xt(1,1,{generateMipmaps:!0,type:He?Ln:Yt,minFilter:In,samples:Math.max(4,Ce.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ze.workingColorSpace})}let Z=M.state.transmissionRenderTarget[J.id],ae=J.viewport||_e;Z.setSize(ae.z*N.transmissionResolutionScale,ae.w*N.transmissionResolutionScale);let ue=N.getRenderTarget(),fe=N.getActiveCubeFace(),Me=N.getActiveMipmapLevel();N.setRenderTarget(Z),N.getClearColor(ce),oe=N.getClearAlpha(),oe<1&&N.setClearColor(16777215,.5),N.clear(),ye&&at.render(q);let Pe=N.toneMapping;N.toneMapping=fn;let Ve=J.viewport;if(J.viewport!==void 0&&(J.viewport=void 0),M.setupLightsView(J),L===!0&&et.setGlobalState(N.clippingPlanes,J),Hs(E,q,J),pe.updateMultisampleRenderTarget(Z),pe.updateRenderTargetMipmap(Z),he.has("WEBGL_multisampled_render_to_texture")===!1){let He=!1;for(let Re=0,We=G.length;Re0,J.currentProgram=He,J.uniformsList=null,He}function lu(E){if(E.uniformsList===null){let G=E.currentProgram.getUniforms();E.uniformsList=Fr.seqWithValue(G.seq,E.uniforms)}return E.uniformsList}function cu(E,G){let q=ie.get(E);q.outputColorSpace=G.outputColorSpace,q.batching=G.batching,q.batchingColor=G.batchingColor,q.instancing=G.instancing,q.instancingColor=G.instancingColor,q.instancingMorph=G.instancingMorph,q.skinning=G.skinning,q.morphTargets=G.morphTargets,q.morphNormals=G.morphNormals,q.morphColors=G.morphColors,q.morphTargetsCount=G.morphTargetsCount,q.numClippingPlanes=G.numClippingPlanes,q.numIntersection=G.numClipIntersection,q.vertexAlphas=G.vertexAlphas,q.vertexTangents=G.vertexTangents,q.toneMapping=G.toneMapping}Mi.setAnimationLoop(function(E){Xo&&Xo(E)}),typeof self<"u"&&Mi.setContext(self),this.setAnimationLoop=function(E){Xo=E,dt.setAnimationLoop(E),E===null?Mi.stop():Mi.start()},dt.addEventListener("sessionstart",iu),dt.addEventListener("sessionend",ru),this.render=function(E,G){if(G!==void 0&&G.isCamera!==!0)return void we("WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(k===!0)return;F!==null&&F.renderStart(E,G);let q=dt.enabled===!0&&dt.isPresenting===!0,J=I!==null&&(ne===null||q)&&I.begin(N,ne);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),G.parent===null&&G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),dt.enabled!==!0||dt.isPresenting!==!0||I!==null&&I.isCompositing()!==!1||(dt.cameraAutoUpdate===!0&&dt.updateCamera(G),G=dt.getCamera()),E.isScene===!0&&E.onBeforeRender(N,E,G,ne),M=At.get(E,O.length),M.init(G),M.state.textureUnits=pe.getTextureUnits(),O.push(M),V.multiplyMatrices(G.projectionMatrix,G.matrixWorldInverse),D.setFromProjectionMatrix(V,qn,G.reversedDepth),w=this.localClippingEnabled,L=et.init(this.clippingPlanes,w),T=Be.get(E,P.length),T.init(),P.push(T),dt.enabled===!0&&dt.isPresenting===!0){let ae=N.xr.getDepthSensingMesh();ae!==null&&jo(ae,G,-1/0,N.sortObjects)}jo(E,G,0,N.sortObjects),T.finish(),N.sortObjects===!0&&T.sort(C,b,G.reversedDepth),ye=dt.enabled===!1||dt.isPresenting===!1||dt.hasDepthSensing()===!1,ye&&at.addToRenderList(T,E),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),L===!0&&et.beginShadows();let Z=M.state.shadowsArray;if(yt.render(Z,E,G),L===!0&&et.endShadows(),(J&&I.hasRenderPass())===!1){let ae=T.opaque,ue=T.transmissive;if(M.setupLights(),G.isArrayCamera){let fe=G.cameras;if(ue.length>0)for(let Me=0,Pe=fe.length;Me0&&au(ae,ue,E,G),ye&&at.render(E),su(T,E,G)}ne!==null&&W===0&&(pe.updateMultisampleRenderTarget(ne),pe.updateRenderTargetMipmap(ne)),J&&I.end(N),E.isScene===!0&&E.onAfterRender(N,E,G),ni.resetDefaultState(),de=-1,Ee=null,O.pop(),O.length>0?(M=O[O.length-1],pe.setTextureUnits(M.state.textureUnits),L===!0&&et.setGlobalState(N.clippingPlanes,M.state.camera)):M=null,P.pop(),T=P.length>0?P[P.length-1]:null,F!==null&&F.renderEnd()},this.getActiveCubeFace=function(){return Y},this.getActiveMipmapLevel=function(){return W},this.getRenderTarget=function(){return ne},this.setRenderTargetTextures=function(E,G,q){let J=ie.get(E);J.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,J.__autoAllocateDepthBuffer===!1&&(J.__useRenderToTexture=!1),ie.get(E.texture).__webglTexture=G,ie.get(E.depthTexture).__webglTexture=J.__autoAllocateDepthBuffer?void 0:q,J.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,G){let q=ie.get(E);q.__webglFramebuffer=G,q.__useDefaultFramebuffer=G===void 0},this.setRenderTarget=function(E,G=0,q=0){ne=E,Y=G,W=q;let J=null,Z=!1,ae=!1;if(E){let ue=ie.get(E);if(ue.__useDefaultFramebuffer!==void 0)return ee.bindFramebuffer(B.FRAMEBUFFER,ue.__webglFramebuffer),_e.copy(E.viewport),ve.copy(E.scissor),te=E.scissorTest,ee.viewport(_e),ee.scissor(ve),ee.setScissorTest(te),void(de=-1);if(ue.__webglFramebuffer===void 0)pe.setupRenderTarget(E);else if(ue.__hasExternalTextures)pe.rebindTextures(E,ie.get(E.texture).__webglTexture,ie.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){let Pe=E.depthTexture;if(ue.__boundDepthTexture!==Pe){if(Pe!==null&&ie.has(Pe)&&(E.width!==Pe.image.width||E.height!==Pe.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");pe.setupDepthRenderbuffer(E)}}let fe=E.texture;(fe.isData3DTexture||fe.isDataArrayTexture||fe.isCompressedArrayTexture)&&(ae=!0);let Me=ie.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(J=Array.isArray(Me[G])?Me[G][q]:Me[G],Z=!0):J=E.samples>0&&pe.useMultisampledRTT(E)===!1?ie.get(E).__webglMultisampledFramebuffer:Array.isArray(Me)?Me[q]:Me,_e.copy(E.viewport),ve.copy(E.scissor),te=E.scissorTest}else _e.copy(R).multiplyScalar(Q).floor(),ve.copy(U).multiplyScalar(Q).floor(),te=x;if(q!==0&&(J=X),ee.bindFramebuffer(B.FRAMEBUFFER,J)&&ee.drawBuffers(E,J),ee.viewport(_e),ee.scissor(ve),ee.setScissorTest(te),Z){let ue=ie.get(E.texture);B.framebufferTexture2D(B.FRAMEBUFFER,B.COLOR_ATTACHMENT0,B.TEXTURE_CUBE_MAP_POSITIVE_X+G,ue.__webglTexture,q)}else if(ae){let ue=G;for(let fe=0;fe1&&B.readBuffer(B.COLOR_ATTACHMENT0+fe),!Ce.textureFormatReadable(Ve))return void we("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Ce.textureTypeReadable(He))return void we("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");G>=0&&G<=E.width-J&&q>=0&&q<=E.height-Z&&B.readPixels(G,q,J,Z,_n.convert(Ve),_n.convert(He),ae)}finally{let Pe=ne!==null?ie.get(ne).__webglFramebuffer:null;ee.bindFramebuffer(B.FRAMEBUFFER,Pe)}}},this.readRenderTargetPixelsAsync=async function(E,G,q,J,Z,ae,ue,fe=0){if(!E||!E.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Me=ie.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&ue!==void 0&&(Me=Me[ue]),Me){if(G>=0&&G<=E.width-J&&q>=0&&q<=E.height-Z){ee.bindFramebuffer(B.FRAMEBUFFER,Me);let Pe=E.textures[fe],Ve=Pe.format,He=Pe.type;if(E.textures.length>1&&B.readBuffer(B.COLOR_ATTACHMENT0+fe),!Ce.textureFormatReadable(Ve))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Ce.textureTypeReadable(He))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Re=B.createBuffer();B.bindBuffer(B.PIXEL_PACK_BUFFER,Re),B.bufferData(B.PIXEL_PACK_BUFFER,ae.byteLength,B.STREAM_READ),B.readPixels(G,q,J,Z,_n.convert(Ve),_n.convert(He),0);let We=ne!==null?ie.get(ne).__webglFramebuffer:null;ee.bindFramebuffer(B.FRAMEBUFFER,We);let xt=B.fenceSync(B.SYNC_GPU_COMMANDS_COMPLETE,0);return B.flush(),await Vd(B,xt,4),B.bindBuffer(B.PIXEL_PACK_BUFFER,Re),B.getBufferSubData(B.PIXEL_PACK_BUFFER,0,ae),B.deleteBuffer(Re),B.deleteSync(xt),ae}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(E,G=null,q=0){let J=Math.pow(2,-q),Z=Math.floor(E.image.width*J),ae=Math.floor(E.image.height*J),ue=G!==null?G.x:0,fe=G!==null?G.y:0;pe.setTexture2D(E,0),B.copyTexSubImage2D(B.TEXTURE_2D,q,0,0,ue,fe,Z,ae),ee.unbindTexture()},this.copyTextureToTexture=function(E,G,q=null,J=null,Z=0,ae=0){let ue,fe,Me,Pe,Ve,He,Re,We,xt,pt=E.isCompressedTexture?E.mipmaps[ae]:E.image;if(q!==null)ue=q.max.x-q.min.x,fe=q.max.y-q.min.y,Me=q.isBox3?q.max.z-q.min.z:1,Pe=q.min.x,Ve=q.min.y,He=q.isBox3?q.min.z:0;else{let vn=Math.pow(2,-Z);ue=Math.floor(pt.width*vn),fe=Math.floor(pt.height*vn),Me=E.isDataArrayTexture?pt.depth:E.isData3DTexture?Math.floor(pt.depth*vn):1,Pe=0,Ve=0,He=0}J!==null?(Re=J.x,We=J.y,xt=J.z):(Re=0,We=0,xt=0);let nt=_n.convert(G.format),ke=_n.convert(G.type),it;G.isData3DTexture?(pe.setTexture3D(G,0),it=B.TEXTURE_3D):G.isDataArrayTexture||G.isCompressedArrayTexture?(pe.setTexture2DArray(G,0),it=B.TEXTURE_2D_ARRAY):(pe.setTexture2D(G,0),it=B.TEXTURE_2D),ee.activeTexture(B.TEXTURE0),ee.pixelStorei(B.UNPACK_FLIP_Y_WEBGL,G.flipY),ee.pixelStorei(B.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),ee.pixelStorei(B.UNPACK_ALIGNMENT,G.unpackAlignment);let wt=ee.getParameter(B.UNPACK_ROW_LENGTH),Ie=ee.getParameter(B.UNPACK_IMAGE_HEIGHT),De=ee.getParameter(B.UNPACK_SKIP_PIXELS),an=ee.getParameter(B.UNPACK_SKIP_ROWS),qo=ee.getParameter(B.UNPACK_SKIP_IMAGES);ee.pixelStorei(B.UNPACK_ROW_LENGTH,pt.width),ee.pixelStorei(B.UNPACK_IMAGE_HEIGHT,pt.height),ee.pixelStorei(B.UNPACK_SKIP_PIXELS,Pe),ee.pixelStorei(B.UNPACK_SKIP_ROWS,Ve),ee.pixelStorei(B.UNPACK_SKIP_IMAGES,He);let Xs=E.isDataArrayTexture||E.isData3DTexture,Gr=G.isDataArrayTexture||G.isData3DTexture;if(E.isDepthTexture){let vn=ie.get(E),Xi=ie.get(G),On=ie.get(vn.__renderTarget),Yo=ie.get(Xi.__renderTarget);ee.bindFramebuffer(B.READ_FRAMEBUFFER,On.__webglFramebuffer),ee.bindFramebuffer(B.DRAW_FRAMEBUFFER,Yo.__webglFramebuffer);for(let ji=0;ji=2.0 are supported."));return}let l=new qh(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h=0&&o[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(a),l.setPlugins(o),l.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,s){n.parse(e,t,i,s)})}};function pg(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}function ut(r,e,t){let n=r.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}var Ge={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},bh=class{constructor(e){this.parser=e,this.name=Ge.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}},Fh=class{constructor(e){this.parser=e,this.name=Ge.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=i.images[a.source],c=n.textureLoader;if(o.uri){let l=n.options.manager.getHandler(o.uri);l!==null&&(c=l)}return n.loadTextureImage(e,a.source,c)}},Bh=class{constructor(e){this.parser=e,this.name=Ge.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=i.images[a.source],c=n.textureLoader;if(o.uri){let l=n.options.manager.getHandler(o.uri);l!==null&&(c=l)}return n.loadTextureImage(e,a.source,c)}},Go=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let i=n.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){let c=i.byteOffset||0,l=i.byteLength||0,h=i.count,u=i.byteStride,p=new Uint8Array(o,c,l);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,p,i.mode,i.filter).then(function(d){return d.buffer}):a.ready.then(function(){let d=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(d),h,u,p,i.mode,i.filter),d})})}else return null}},zh=class{constructor(e){this.name=Ge.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let i=t.meshes[n.mesh];for(let l of i.primitives)if(l.mode!==rn.TRIANGLES&&l.mode!==rn.TRIANGLE_STRIP&&l.mode!==rn.TRIANGLE_FAN&&l.mode!==void 0)return null;let a=n.extensions[this.name].attributes,o=[],c={};for(let l in a)o.push(this.parser.getDependency("accessor",a[l]).then(h=>(c[l]=h,c[l])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(l=>{let h=l.pop(),u=h.isGroup?h.children:[h],p=l[0].count,d=[];for(let f of u){let m=new be,v=new A,g=new ct,_=new A(1,1,1),y=new ls(f.geometry,f.material,p);for(let S=0;S0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":r.search(/\.ktx2($|\?)/i)>0||r.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var Mg=new be,qh=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new pg,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,a=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;let c=o.match(/Version\/(\d+)/);i=n&&c?parseInt(c[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||s&&a<98?this.textureLoader=new As(this.options.manager):this.textureLoader=new Ps(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Ar(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(a){let o={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:n,userData:{}};return Hi(s,o,i),Un(o,i),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(o)})).then(function(){for(let c of o.scenes)c.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,s=t.length;i{let c=this.associations.get(a);c!=null&&this.associations.set(o,c);for(let[l,h]of a.children.entries())s(h,o.children[l])};return s(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&v.setY(I,M[P*c+1]),c>=3&&v.setZ(I,M[P*c+2]),c>=4&&v.setW(I,M[P*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}v.normalized=f}return v})}loadTexture(e){let t=this.json,n=this.options,s=t.textures[e].source,a=t.images[s],o=this.textureLoader;if(a.uri){let c=n.manager.getHandler(a.uri);c!==null&&(o=c)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,n){let i=this,s=this.json,a=s.textures[e],o=s.images[t],c=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[c])return this.textureCache[c];let l=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);let p=(s.samplers||{})[a.sampler]||{};return h.magFilter=Rp[p.magFilter]||vt,h.minFilter=Rp[p.minFilter]||In,h.wrapS=Cp[p.wrapS]||hi,h.wrapT=Cp[p.wrapT]||hi,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==Nt&&h.minFilter!==vt,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){let n=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());let a=i.images[e],o=self.URL||self.webkitURL,c=a.uri||"",l=!1;if(a.bufferView!==void 0)c=n.getDependency("bufferView",a.bufferView).then(function(u){l=!0;let p=new Blob([u],{type:a.mimeType});return c=o.createObjectURL(p),c});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let h=Promise.resolve(c).then(function(u){return new Promise(function(p,d){let f=p;t.isImageBitmapLoader===!0&&(f=function(m){let v=new Et(m);v.needsUpdate=!0,p(v)}),t.load(ei.resolveURL(u,s.path),f,void 0,d)})}).then(function(u){return l===!0&&o.revokeObjectURL(c),Un(u,a),u.userData.mimeType=a.mimeType||xg(a.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,i){let s=this;return this.getDependency("texture",n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),s.extensions[Ge.KHR_TEXTURE_TRANSFORM]){let o=n.extensions!==void 0?n.extensions[Ge.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let c=s.associations.get(a);a=s.extensions[Ge.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,c)}}return i!==void 0&&(a.colorSpace=i),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+n.uuid,c=this.cache.get(o);c||(c=new Mr,Bt.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(o,c)),n=c}else if(e.isLine){let o="LineBasicMaterial:"+n.uuid,c=this.cache.get(o);c||(c=new xr,Bt.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(o,c)),n=c}if(i||s||a){let o="ClonedMaterial:"+n.uuid+":";i&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let c=this.cache.get(o);c||(c=n.clone(),s&&(c.vertexColors=!0),a&&(c.flatShading=!0),i&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(o,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return An}loadMaterial(e){let t=this,n=this.json,i=this.extensions,s=n.materials[e],a,o={},c=s.extensions||{},l=[];if(c[Ge.KHR_MATERIALS_UNLIT]){let u=i[Ge.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),l.push(u.extendParams(o,s,t))}else{let u=s.pbrMetallicRoughness||{};if(o.color=new Te(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){let p=u.baseColorFactor;o.color.setRGB(p[0],p[1],p[2],Dt),o.opacity=p[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(o,"map",u.baseColorTexture,lt)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=tn);let h=s.alphaMode||Mh.OPAQUE;if(h===Mh.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===Mh.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==mn&&(l.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new $(1,1),s.normalTexture.scale!==void 0)){let u=s.normalTexture.scale;o.normalScale.set(u,u)}if(s.occlusionTexture!==void 0&&a!==mn&&(l.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==mn){let u=s.emissiveFactor;o.emissive=new Te().setRGB(u[0],u[1],u[2],Dt)}return s.emissiveTexture!==void 0&&a!==mn&&l.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,lt)),Promise.all(l).then(function(){let u=new a(o);return s.name&&(u.name=s.name),Un(u,s),t.associations.set(u,{materials:e}),s.extensions&&Hi(i,u,s),u})}createUniqueName(e){let t=$e.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function s(o){return n[Ge.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(c){return Pp(c,o,t)})}let a=[];for(let o=0,c=e.length;o0&&vg(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),Un(g,s),v.extensions&&Hi(i,g,v),t.assignFinalMaterial(g),u.push(g)}for(let d=0,f=u.length;d0){let d=h.userData.pivot,f=u[0];h.pivot=new A().fromArray(d),h.position.x-=d[0],h.position.y-=d[1],h.position.z-=d[2],f.position.set(0,0,0),delete h.userData.pivot}return h})}_loadNodeShallow(e){let t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],a=s.name?i.createUniqueName(s.name):"",o=[],c=i._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return c&&o.push(c),s.camera!==void 0&&o.push(i.getDependency("camera",s.camera).then(function(l){return i._getNodeRef(i.cameraCache,s.camera,l)})),i._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){o.push(l)}),this.nodeCache[e]=Promise.all(o).then(function(l){let h;if(s.isBone===!0?h=new vr:l.length>1?h=new Wt:l.length===1?h=l[0]:h=new tt,h!==l[0])for(let u=0,p=l.length;u1){let u=i.associations.get(h);i.associations.set(h,{...u})}return i.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],i=this,s=new Wt;n.name&&(s.name=i.createUniqueName(n.name)),Un(s,n),n.extensions&&Hi(t,s,n);let a=n.nodes||[],o=[];for(let c=0,l=a.length;c{let u=new Map;for(let[p,d]of i.associations)(p instanceof Bt||p instanceof Et)&&u.set(p,d);return h.traverse(p=>{let d=i.associations.get(p);d!=null&&u.set(p,d)}),u};return i.associations=l(s),s})}_createAnimationTracks(e,t,n,i,s){let a=[],o=e.name?e.name:e.uuid,c=[];function l(d){d.morphTargetInfluences&&c.push(d.name?d.name:d.uuid)}yi[s.path]===yi.weights?(l(e),e.isGroup&&e.children.forEach(l)):c.push(o);let h;switch(yi[s.path]){case yi.weights:h=$n;break;case yi.rotation:h=Rn;break;case yi.translation:case yi.scale:h=Qn;break;default:n.itemSize===1?h=$n:h=Qn;break}let u=i.interpolation!==void 0?fg[i.interpolation]:Pi,p=this._getArrayFromAccessor(n);for(let d=0,f=c.length;dMath.PI&&(n-=kt),i<-Math.PI?i+=kt:i>Math.PI&&(i-=kt),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=a!=this._spherical.radius}if(bt.setFromSpherical(this._spherical),bt.applyQuaternion(this._quatInverse),t.copy(this.target).add(bt),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){let o=bt.length();a=this._clampDistance(o*this._scale);let c=o-a;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),s=!!c}else if(this.object.isOrthographicCamera){let o=new A(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=c!==this.object.zoom;let l=new A(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(o),this.object.updateMatrixWorld(),a=bt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(Vo.origin.copy(this.object.position),Vo.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Vo.direction))Yh||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Yh||this._lastTargetPosition.distanceToSquared(this.target)>Yh?(this.dispatchEvent(Lp),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?kt/60*this.autoRotateSpeed*e:kt/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){bt.setFromMatrixColumn(t,0),bt.multiplyScalar(-e),this._panOffset.add(bt)}_panUp(e,t){this.screenSpacePanning===!0?bt.setFromMatrixColumn(t,1):(bt.setFromMatrixColumn(t,0),bt.crossVectors(this.object.up,bt)),bt.multiplyScalar(e),this._panOffset.add(bt)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;bt.copy(i).sub(this.target);let s=bt.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),i=e-n.left,s=t-n.top,a=n.width,o=n.height;this._mouse.x=i/a*2-1,this._mouse.y=-(s/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(kt*this._rotateDelta.x/t.clientHeight),this._rotateUp(kt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(kt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-kt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(kt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-kt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(kt*this._rotateDelta.x/t.clientHeight),this._rotateUp(kt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t{let H=X.scene;if(H.position.set(.1,-.96,.37),l.add(H),_=H.getObjectByName("Seat_FR"),y=H.getObjectByName("Seat_FR_Backrest"),S=H.getObjectByName("Seat_FR_Legrest"),!_||!y||!S)throw new Error("GLB \u4E2D\u7F3A\u5C11 Seat_FR\u3001Seat_FR_Backrest \u6216 Seat_FR_Legrest \u8282\u70B9");T=_.position.clone(),M=y.quaternion.clone(),P=S.quaternion.clone(),H.traverse(z=>{if(!z.isMesh)return;z.castShadow=!0,z.receiveShadow=!0,(Array.isArray(z.material)?z.material:[z.material]).filter(Boolean).forEach(W=>{"envMapIntensity"in W&&(W.envMapIntensity=1.25),W.needsUpdate=!0})}),ks.classList.add("is-ready"),Wi.setAttribute("aria-hidden","true"),window.dispatchEvent(new CustomEvent("n7-seat-model-ready"))},X=>{if(!X.total)return;let H=Math.min(100,Math.round(X.loaded/X.total*100));Wi.querySelector("small").textContent=`ANDROID GLB \xB7 ${H}%`},Up);function N(){let X=Math.max(1,ks.clientWidth),H=Math.max(1,ks.clientHeight),z=X/H<1.1;t.fov=z?42:34,t.aspect=X/H,t.updateProjectionMatrix(),r.setSize(X,H,!1)}new ResizeObserver(N).observe(ks),N();let k=performance.now();function F(X){requestAnimationFrame(F);let H=Math.min(.05,Math.max(0,(X-k)/1e3));k=X;let z=Math.min(1,H*10.5);Object.keys(m).forEach(Y=>{m[Y]+=(f[Y]-m[Y])*z}),_&&(_.position.copy(T),_.position.x+=m.longitudinalM,_.position.y+=m.verticalM,g.setFromAxisAngle(v,gn.degToRad(-m.backrestDeg)),y.quaternion.copy(M).multiply(g),g.setFromAxisAngle(v,gn.degToRad(-m.legrestDeg)),S.quaternion.copy(P).multiply(g)),s.update(),r.render(e,t)}requestAnimationFrame(F),window.n7SeatModel={scene:e,camera:t,controls:s,renderer:r,targetPose:f,resetView:I}}try{Og()}catch(r){Up(r)}})(); -/** - * @license - * Copyright 2010-2026 Three.js Authors - * SPDX-License-Identifier: MIT - */ diff --git a/apps/web-console/console-v2.css b/apps/web-console/console-v2.css index 7457844..f419a0c 100644 --- a/apps/web-console/console-v2.css +++ b/apps/web-console/console-v2.css @@ -28,15 +28,6 @@ font-family: Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; } -.console-v2[data-demo-role="admin"] { - --v2-accent: #315eaa; - --v2-accent-strong: #234785; - --v2-accent-soft: #e1e9fa; - --v2-sidebar: #e0e8f7; - --v2-sidebar-deep: #cedbf2; - --v2-line: rgba(49, 94, 170, 0.16); -} - .console-v2 * { scrollbar-color: var(--v2-accent) rgba(133, 151, 151, 0.14); scrollbar-width: thin; @@ -105,12 +96,6 @@ border-right: 1px solid var(--v2-line); } -.console-v2[data-demo-role="admin"] .v2-sidebar { - background: - radial-gradient(circle at 14% 3%, rgba(255, 255, 255, 0.8), transparent 24%), - linear-gradient(158deg, var(--v2-sidebar) 0%, #edf2fb 60%, var(--v2-sidebar-deep) 130%); -} - .v2-profile { display: grid; grid-template-columns: 56px minmax(0, 1fr) 30px; @@ -144,12 +129,6 @@ filter: blur(4px); } -[data-demo-role="admin"] .v2-avatar { - background: - radial-gradient(circle at 28% 25%, rgba(255, 255, 255, 0.95), transparent 18%), - linear-gradient(135deg, #183c7a 3%, #6688d4 48%, #e5b0c8 55%, #315eaa 100%); -} - .v2-profile-copy { min-width: 0; } @@ -172,6 +151,7 @@ } .v2-role-select > span, +.v2-role-select > strong, .v2-role-select select, .v2-role-select .v2-dropdown-trigger { color: #091c1e; @@ -613,7 +593,7 @@ background: #fff0e9; } -.console-v2[data-demo-role="user"] .v2-execution-field { +.console-v2 .v2-execution-field { display: none; } @@ -632,7 +612,7 @@ font-weight: 800; } -.console-v2[data-demo-role="user"] .v2-user-target-status { +.console-v2 .v2-user-target-status { display: grid; } @@ -859,18 +839,6 @@ line-height: 1.5; } -/* Calibration and repair use their module root as the workspace card. This - matches orchestration, extension and evolution without adding a wrapper or - consuming any additional layout space. */ -.console-v2[data-module="self-calibration"] .v2-self-calibration, -.console-v2[data-module="self-repair"] .v2-self-repair { - box-sizing: border-box; - background: rgba(255, 255, 255, 0.9); - border: 1px solid rgba(117, 145, 145, 0.14); - border-radius: clamp(17px, 1.4vw, 24px); - box-shadow: var(--v2-shadow); -} - .v2-natural-grid { min-width: 0; min-height: 0; @@ -1304,7 +1272,7 @@ min-width: 0; min-height: 36px; display: grid; - grid-template-columns: repeat(5, minmax(0, 1fr)); + grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: stretch; margin-inline: calc(0px - var(--v2-main-pad)); padding: 3px var(--v2-main-pad) 0; @@ -1446,121 +1414,6 @@ display: none; } -.console-v2 .v2-inline-gesture #gestureArmButton { - width: 42px; - height: 42px; - min-height: 42px; - grid-row: 1; - display: inline-grid; - place-items: center; - padding: 0; - overflow: hidden; - color: white; - border: 0; - border-radius: 50%; - background: var(--v2-accent); - box-shadow: 0 8px 20px color-mix(in srgb, var(--v2-accent) 24%, transparent); - font-size: 0; - line-height: 0; -} - -.console-v2 .v2-inline-gesture #gestureArmButton svg { - width: 17px; - height: 17px; - display: block; - margin: 0; -} - -.console-v2 .v2-inline-gesture #gestureArmButton span { - display: none; -} - -.console-v2[data-demo-role="user"] .v2-inline-gesture #gestureArmButton { - cursor: default; - opacity: 1; -} - -.console-v2[data-demo-role="user"] .v2-inline-gesture #gestureArmButton svg { - display: none; -} - -.console-v2 .v2-inline-gesture .gesture-debug-panel { - width: clamp(300px, 28vw, 360px); - max-width: none; - position: absolute; - top: auto; - left: calc(100% + 8px); - right: auto; - bottom: 52px; - display: grid; - gap: 7px; - padding: 9px; - color: var(--v2-ink); - border: 1px solid var(--v2-line); - border-radius: 11px; - background: rgba(255, 255, 255, 0.98); - box-shadow: 0 14px 32px rgba(25, 48, 50, 0.2); -} - -.console-v2 .v2-inline-gesture .gesture-debug-panel[hidden] { - display: none; -} - -.console-v2 .v2-inline-gesture .gesture-debug-heading { - display: flex; - align-items: center; - justify-content: space-between; - gap: 10px; -} - -.console-v2 .v2-inline-gesture .gesture-debug-heading span { - color: var(--v2-accent-strong); - font-size: 11px; - font-weight: 900; -} - -.console-v2 .v2-inline-gesture .gesture-debug-heading small { - color: var(--v2-muted); - font-size: 8px; -} - -.console-v2 .v2-inline-gesture .gesture-debug-controls { - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - gap: 7px; -} - -.console-v2 .v2-inline-gesture .gesture-debug-controls select, -.console-v2 .v2-inline-gesture .gesture-debug-controls button { - min-height: 32px; - border: 1px solid var(--v2-line); - border-radius: 8px; - font-size: 9px; -} - -.console-v2 .v2-inline-gesture .gesture-debug-controls select { - min-width: 0; - padding: 0 8px; - color: var(--v2-ink); - background: #f7f9f9; -} - -.console-v2 .v2-inline-gesture .gesture-debug-controls button { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 5px; - padding: 5px 9px; - color: white; - background: var(--v2-accent); - white-space: nowrap; -} - -.console-v2 .v2-inline-gesture .gesture-debug-controls button svg { - width: 12px; - height: 12px; -} - .console-v2 .v2-inline-gesture .gesture-footnote, .console-v2 .v2-inline-gesture .gesture-progress { display: none; @@ -1758,7 +1611,7 @@ padding: 0; } -.console-v2[data-demo-role="user"] .v2-output-shell { +.console-v2 .v2-output-shell { grid-template-columns: minmax(0, 1fr); } @@ -1807,7 +1660,7 @@ letter-spacing: -0.08em; } -.console-v2[data-demo-role="user"] .v2-page-index { +.console-v2 .v2-page-index { display: none; } @@ -1910,7 +1763,7 @@ display: grid !important; } -.console-v2[data-demo-role="user"] .v2-output-shell.v2-twin-active { +.console-v2 .v2-output-shell.v2-twin-active { overflow: visible; background: transparent; border: 0; @@ -1918,14 +1771,14 @@ box-shadow: none; } -.console-v2[data-demo-role="user"] .v2-output-shell.v2-twin-active .v2-output-content { +.console-v2 .v2-output-shell.v2-twin-active .v2-output-content { margin: 0; background: transparent; border: 0; border-radius: 0; } -.console-v2[data-demo-role="user"] .joint-twin-shell.v2-output-page { +.console-v2 .joint-twin-shell.v2-output-page { gap: 12px; padding: 0; background: transparent; @@ -2557,6 +2410,7 @@ } .v2-role-select > span, + .v2-role-select > strong, .v2-role-select select, .v2-role-select .v2-dropdown-trigger { font-size: 20px; @@ -2576,9 +2430,7 @@ margin-top: 14px; } - .console-v2[data-module="self-calibration"] .v2-calibration-sidebar, - .console-v2[data-module="self-extension"] .v2-extension-sidebar, - .console-v2[data-module="self-repair"] .v2-repair-sidebar { + .console-v2[data-module="self-extension"] .v2-extension-sidebar { margin-top: 14px; } @@ -2764,6 +2616,1405 @@ } } +/* Interactive vehicle sync control layout -------------------------------- */ + +.console-v2.v2-interactive-sync .workspace { + grid-template-columns: clamp(250px, 19vw, 292px) minmax(0, 1fr); +} + +.console-v2.v2-interactive-sync .main-panel { + grid-template-rows: 56px clamp(224px, 29dvh, 254px) minmax(0, 1fr); + gap: 10px; + padding-bottom: 10px; +} + +.console-v2.v2-interactive-sync .v2-module-switcher { + min-height: 56px; + grid-template-columns: minmax(0, 1fr) auto auto; + gap: 18px; +} + +.console-v2.v2-interactive-sync .v2-unified-brand-mark { + width: 34px; + height: 34px; + border-radius: 11px; +} + +.console-v2.v2-interactive-sync .v2-unified-brand h1 { + margin-top: 2px; + font-size: clamp(15px, 1.3vw, 20px); +} + +.console-v2 .v2-remote-control-state { + display: flex; + align-items: center; + gap: 7px; + padding: 7px 10px; + color: #52716f; + background: rgba(255, 255, 255, 0.72); + border: 1px solid rgba(15, 121, 115, 0.1); + border-radius: 999px; + font-size: 9px; +} + +.console-v2 .v2-remote-control-state svg { + width: 13px; + color: var(--v2-accent); +} + +.console-v2 .v2-remote-control-state strong { + color: #12806f; +} + +.console-v2.v2-interactive-sync .v2-natural-panel { + grid-template-columns: minmax(390px, 0.95fr) minmax(390px, 1.05fr); + grid-template-rows: auto minmax(76px, 1fr) auto; + column-gap: 14px; + row-gap: 7px; + padding: 13px 16px; +} + +.console-v2.v2-interactive-sync .v2-operation-heading h2 { + font-size: clamp(19px, 1.6vw, 25px); +} + +.console-v2.v2-interactive-sync .v2-operation-heading .panel-intro { + max-width: 540px; + font-size: 9px; +} + +.console-v2.v2-interactive-sync .v2-natural-grid { + display: grid; + grid-column: 1; + grid-row: 2; + grid-template-columns: minmax(0, 1fr); +} + +.console-v2.v2-interactive-sync .v2-request-form { + display: grid; +} + +.console-v2.v2-interactive-sync .v2-request-status { + display: none; +} + +.console-v2.v2-interactive-sync .v2-request-form .command-composer, +.console-v2.v2-interactive-sync .v2-request-form #utterance { + height: 76px; + min-height: 76px; +} + +.console-v2.v2-interactive-sync .v2-request-form #utterance { + padding: 11px 60px 34px 14px; + font-size: 12px; +} + +.console-v2.v2-interactive-sync .v2-request-form .primary-action { + width: 32px; + height: 32px; + min-height: 32px; + right: 8px; + bottom: 8px; +} + +.console-v2.v2-interactive-sync .v2-request-form .context-reset { + top: 5px; + right: 7px; +} + +.console-v2.v2-interactive-sync .v2-request-form .composer-hint { + right: 49px; + bottom: 8px; +} + +.console-v2.v2-interactive-sync .v2-reasoning-trigger { + left: 10px; + bottom: 7px; +} + +.console-v2.v2-interactive-sync .v2-mode-rail { + grid-column: 1; + grid-row: 3; + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: 10px; + padding: 0; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-rail-heading { + display: flex !important; + align-items: center; + margin: 0; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-rail-heading > div { + display: grid; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-rail-heading span { + color: #466664; + font-size: 10px; + font-weight: 850; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-rail-heading small, +.console-v2.v2-interactive-sync .v2-mode-rail #saveModeToggle, +.console-v2.v2-interactive-sync .v2-mode-rail .mode-rail-controls { + display: none !important; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-chips { + gap: 6px; + padding: 0; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-chips button { + min-height: 29px; + padding: 4px 10px; + cursor: pointer; + pointer-events: auto; + opacity: 1; +} + +.console-v2.v2-interactive-sync .v2-mode-rail .mode-chips button:hover { + color: #fff; + background: linear-gradient(135deg, #0a6d68, #15988f); + border-color: transparent; +} + +.console-v2.v2-interactive-sync .v2-task-overview { + grid-column: 2; + grid-row: 1 / 4; + gap: 9px; + padding: 13px 14px; +} + +.console-v2.v2-interactive-sync .v2-task-copy strong { + font-size: clamp(12px, 1vw, 15px); +} + +.console-v2.v2-interactive-sync .v2-task-timeline { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 5px; +} + +.console-v2.v2-interactive-sync .v2-task-timeline span { + min-height: 35px; + padding: 5px 6px; +} + +.console-v2.v2-interactive-sync .v2-sidebar { + padding: 18px 14px 12px; +} + +.console-v2.v2-interactive-sync .v2-sync-sidebar { + gap: 10px; +} + +.console-v2.v2-interactive-sync .v2-sync-sidebar-heading h2 { + margin: 4px 0 4px; + font-size: 21px; +} + +.console-v2.v2-interactive-sync .v2-sync-sidebar-heading p { + font-size: 9px; + line-height: 1.55; +} + +.console-v2.v2-interactive-sync .v2-sync-link-stack { + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 5px; +} + +.console-v2.v2-interactive-sync .v2-sync-link { + min-height: 47px; + display: grid; + grid-template-columns: 1fr 7px; + gap: 4px; + padding: 7px; + border-radius: 11px; +} + +.console-v2.v2-interactive-sync .v2-sync-link > svg { + display: none; +} + +.console-v2.v2-interactive-sync .v2-sync-link strong { + font-size: 9px; +} + +.console-v2.v2-interactive-sync .v2-sync-link span { + font-size: 7px; +} + +.console-v2 .v2-sync-log { + min-height: 0; + display: grid; + flex: 1; + grid-template-rows: auto minmax(0, 1fr); + overflow: hidden; + background: rgba(255, 255, 255, 0.78); + border: 1px solid rgba(15, 112, 106, 0.11); + border-radius: 15px; + box-shadow: 0 10px 26px rgba(31, 87, 84, 0.06); +} + +.console-v2 .v2-sync-log > header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 10px 10px 8px; + border-bottom: 1px solid rgba(30, 104, 100, 0.08); +} + +.console-v2 .v2-sync-log header small { + color: #27827d; + font: 800 7px/1.2 "SFMono-Regular", Consolas, monospace; + letter-spacing: 0.1em; +} + +.console-v2 .v2-sync-log h3 { + margin: 3px 0 0; + color: #173637; + font-size: 12px; +} + +.console-v2 .v2-sync-log select { + height: 26px; + padding: 0 6px; + color: #55706f; + background: #f3f7f6; + border: 1px solid rgba(58, 107, 104, 0.1); + border-radius: 8px; + font-size: 8px; +} + +.console-v2 .v2-sync-log ol { + min-height: 0; + margin: 0; + padding: 8px 9px 12px; + overflow: auto; + list-style: none; + scrollbar-width: thin; +} + +.console-v2 .v2-sync-log li { + position: relative; + display: grid; + grid-template-columns: 38px 20px minmax(0, 1fr); + gap: 5px; + padding: 7px 0; +} + +.console-v2 .v2-sync-log li:not(:last-child)::after { + width: 1px; + position: absolute; + top: 30px; + bottom: -6px; + left: 48px; + content: ""; + background: rgba(55, 124, 119, 0.13); +} + +.console-v2 .v2-sync-log time { + padding-top: 4px; + color: #8a9b9a; + font: 700 7px/1 "SFMono-Regular", Consolas, monospace; +} + +.console-v2 .v2-sync-log li > span { + width: 19px; + height: 19px; + display: grid; + z-index: 1; + place-items: center; + color: #fff; + background: #4b91d9; + border-radius: 50%; +} + +.console-v2 .v2-sync-log li[data-log-status="success"] > span { + background: #19a66f; +} + +.console-v2 .v2-sync-log li[data-log-status="error"] > span { + background: #dc6f65; +} + +.console-v2 .v2-sync-log li > span svg { + width: 10px; +} + +.console-v2 .v2-sync-log li > div { + min-width: 0; + display: grid; + gap: 3px; +} + +.console-v2 .v2-sync-log li strong { + overflow: hidden; + color: #263f40; + font-size: 9px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-sync-log li small { + display: -webkit-box; + overflow: hidden; + color: #738887; + font-size: 8px; + line-height: 1.45; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; +} + +.console-v2 .v2-sync-log-empty { + grid-template-columns: 1fr !important; + text-align: center; +} + +.console-v2.v2-interactive-sync .v2-sync-protocol { + flex: 0 0 auto; + margin-top: 0; + padding: 8px 10px; +} + +.console-v2.v2-interactive-sync .v2-sidebar-footer { + min-height: 34px; + margin-top: 7px; + padding-top: 7px; +} + +.console-v2.v2-interactive-sync .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(0, 1.25fr) minmax(320px, 0.75fr); + grid-template-rows: minmax(0, 1fr); + gap: 10px; +} + +.console-v2.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] { + grid-template-columns: minmax(0, 1fr); +} + +.console-v2.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] .v2-unified-right-rail { + display: none; +} + +.console-v2.v2-interactive-sync .joint-twin-shell > .twin-band { + width: 100%; + max-width: 980px; + justify-self: center; +} + +.console-v2.v2-interactive-sync .v2-unified-right-rail { + display: flex; + flex-direction: column; + gap: 8px; + overflow: hidden; +} + +.console-v2 .v2-side-status-panel { + min-height: 0; + flex: 1 1 0; +} + +.console-v2 .v2-side-status-panel[hidden] { + display: none !important; +} + +.console-v2 .v2-device-sync-board { + grid-template-rows: auto minmax(0, 1fr); + padding: 9px; +} + +.console-v2 .v2-device-sync-board > header { + display: grid; + grid-template-columns: minmax(0, 1fr) auto 27px; + gap: 7px; +} + +.console-v2 .v2-device-sync-board > header > button, +.console-v2 .v2-extension-sync-heading > button { + width: 26px; + height: 26px; + display: grid; + place-items: center; + color: #66817f; + background: #f1f6f5; + border: 0; + border-radius: 8px; + cursor: pointer; +} + +.console-v2 .v2-device-sync-board > header > button svg, +.console-v2 .v2-extension-sync-heading > button svg { + width: 13px; +} + +.console-v2 .v2-device-sync-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-rows: none; + grid-auto-rows: minmax(76px, auto); + gap: 6px; + padding-right: 2px; + overflow: auto; + scrollbar-width: thin; +} + +.console-v2 .v2-synced-device { + min-height: 76px; + display: grid; + grid-template-columns: 27px minmax(0, 1fr) 6px; + grid-template-rows: auto auto; + align-content: start; + text-align: left; + cursor: pointer; +} + +.console-v2 .v2-synced-device:hover, +.console-v2 .v2-synced-device.active { + background: linear-gradient(145deg, #e9f7f4, #f5fbfa); + border-color: rgba(13, 126, 117, 0.22); + box-shadow: 0 8px 18px rgba(26, 99, 94, 0.09); +} + +.console-v2 .v2-synced-device dl { + min-width: 0; + display: grid; + grid-column: 1 / -1; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 3px 6px; + margin: 5px 0 0; + padding-top: 5px; + border-top: 1px solid rgba(60, 113, 109, 0.08); +} + +.console-v2 .v2-synced-device dl div { + min-width: 0; + display: flex; + justify-content: space-between; + gap: 4px; +} + +.console-v2 .v2-synced-device dt, +.console-v2 .v2-synced-device dd { + overflow: hidden; + margin: 0; + font-size: 7px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-synced-device dt { + color: #8a9a99; +} + +.console-v2 .v2-synced-device dd { + color: #385a58; + font-weight: 800; +} + +.console-v2 .v2-extension-panel, +.console-v2 .v2-extension-sync-mount { + min-height: 0; +} + +.console-v2 .v2-extension-panel { + overflow: hidden; +} + +.console-v2 .v2-extension-sync-mount { + height: 100%; + overflow: auto; + scrollbar-width: thin; +} + +.console-v2 .v2-extension-sync-heading { + display: grid; + grid-template-columns: minmax(0, 1fr) auto 27px; + align-items: center; + gap: 7px; +} + +.console-v2 .v2-panel-visibility-controls { + display: flex; + align-items: center; + gap: 5px; +} + +.console-v2 .v2-panel-visibility-controls button { + min-height: 27px; + display: inline-flex; + align-items: center; + gap: 5px; + padding: 0 8px; + color: #6c7f7e; + background: #f0f4f3; + border: 1px solid rgba(79, 110, 108, 0.09); + border-radius: 9px; + font-size: 8px; + font-weight: 800; + cursor: pointer; +} + +.console-v2 .v2-panel-visibility-controls button.active { + color: #0a736d; + background: #def3ef; + border-color: rgba(15, 123, 115, 0.17); +} + +.console-v2 .v2-panel-visibility-controls svg { + width: 12px; +} + +.console-v2 .v2-twin-hotspots { + position: absolute; + inset: 0; + z-index: 14; + pointer-events: none; +} + +.console-v2 .v2-twin-hotspots button { + position: absolute; + display: flex; + align-items: center; + gap: 4px; + padding: 5px 7px; + color: #164846; + background: rgba(242, 252, 250, 0.92); + border: 1px solid rgba(12, 119, 111, 0.2); + border-radius: 999px; + box-shadow: 0 7px 18px rgba(22, 82, 78, 0.13); + font-size: 8px; + font-weight: 850; + cursor: pointer; + pointer-events: auto; + transform: translate(-50%, -50%); + transition: transform 150ms ease, background 150ms ease, color 150ms ease; +} + +.console-v2 .v2-twin-hotspots button:hover, +.console-v2 .v2-twin-hotspots button:focus-visible, +.console-v2 .v2-twin-hotspots button.active { + z-index: 2; + color: #fff; + background: #0b7f78; + outline: none; + transform: translate(-50%, -50%) scale(1.08); +} + +.console-v2 .v2-twin-hotspots button svg { + width: 11px; +} + +.console-v2 .v2-twin-hotspots [data-twin-device="windows"] { top: 48%; left: 8%; } +.console-v2 .v2-twin-hotspots [data-twin-device="shade"] { top: 16%; left: 45%; } +.console-v2 .v2-twin-hotspots [data-twin-device="driver"] { top: 46%; left: 63%; } +.console-v2 .v2-twin-hotspots [data-twin-device="passenger"] { top: 58%; left: 44%; } +.console-v2 .v2-twin-hotspots [data-twin-device="reading"] { top: 30%; left: 34%; } +.console-v2 .v2-twin-hotspots [data-twin-device="ambient"] { top: 78%; left: 47%; } +.console-v2 .v2-twin-hotspots [data-twin-device="headlight"] { top: 62%; left: 88%; } +.console-v2 .v2-twin-hotspots [data-twin-device="climate"] { top: 80%; left: 12%; } + +.console-v2 .v2-twin-device-popover { + width: min(360px, calc(100% - 34px)); + max-height: min(190px, calc(100% - 78px)); + position: absolute; + top: 52px; + left: 50%; + z-index: 25; + padding: 10px; + overflow: auto; + color: #243f40; + background: rgba(255, 255, 255, 0.97); + border: 1px solid rgba(10, 115, 108, 0.18); + border-radius: 14px; + box-shadow: 0 18px 42px rgba(27, 74, 72, 0.2); + transform: translateX(-50%); + backdrop-filter: blur(14px); +} + +.console-v2 .v2-twin-device-popover[hidden] { + display: none; +} + +.console-v2 .v2-twin-device-popover header { + display: grid; + grid-template-columns: 30px minmax(0, 1fr) auto; + align-items: center; + gap: 8px; +} + +.console-v2 .v2-twin-device-popover header > span { + width: 30px; + height: 30px; + display: grid; + place-items: center; + color: #fff; + background: #0b807a; + border-radius: 10px; +} + +.console-v2 .v2-twin-device-popover header svg { + width: 15px; +} + +.console-v2 .v2-twin-device-popover header div { + display: grid; + gap: 2px; +} + +.console-v2 .v2-twin-device-popover header small { + color: #4c8c88; + font: 800 7px/1 "SFMono-Regular", Consolas, monospace; + letter-spacing: 0.08em; +} + +.console-v2 .v2-twin-device-popover header strong { + font-size: 13px; +} + +.console-v2 .v2-twin-device-popover header > b { + color: #718583; + font-size: 8px; +} + +.console-v2 .v2-twin-device-popover dl { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 5px; + margin: 9px 0 0; +} + +.console-v2 .v2-twin-device-popover dl div { + min-width: 0; + display: grid; + gap: 2px; + padding: 6px; + background: #f2f7f6; + border-radius: 8px; +} + +.console-v2 .v2-twin-device-popover dt, +.console-v2 .v2-twin-device-popover dd { + overflow: hidden; + margin: 0; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-twin-device-popover dt { + color: #819290; + font-size: 7px; +} + +.console-v2 .v2-twin-device-popover dd { + color: #2c5351; + font-size: 9px; + font-weight: 850; +} + +@media (max-width: 1366px) { + .console-v2.v2-interactive-sync .workspace { + grid-template-columns: 250px minmax(0, 1fr); + } + + .console-v2.v2-interactive-sync .v2-natural-panel { + grid-template-columns: minmax(360px, 0.9fr) minmax(370px, 1.1fr); + } + + .console-v2.v2-interactive-sync .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(0, 1fr) minmax(310px, 0.72fr); + } + + .console-v2 .v2-synced-device dl { + grid-template-columns: minmax(0, 1fr); + } +} + +@media (max-height: 760px) { + .console-v2.v2-interactive-sync .main-panel { + grid-template-rows: 52px 216px minmax(0, 1fr); + } + + .console-v2.v2-interactive-sync .v2-module-switcher { + min-height: 52px; + } + + .console-v2.v2-interactive-sync .v2-natural-panel { + padding-block: 10px; + } + + .console-v2.v2-interactive-sync .v2-task-timeline span { + min-height: 31px; + } +} + +/* Unified cockpit sync foundation ---------------------------------------- */ + +.console-v2.v2-passive-display { + --v2-accent: #0b807a; + --v2-accent-strong: #075d5a; + --v2-accent-soft: #d9f5f1; + --v2-sidebar: #e6f6f3; + --v2-sidebar-deep: #ccebe7; + background: #eef3f2; +} + +.console-v2.v2-passive-display .workspace { + grid-template-columns: clamp(236px, 17vw, 278px) minmax(0, 1fr); +} + +.console-v2.v2-passive-display .main-panel { + grid-template-rows: 68px clamp(210px, 25dvh, 252px) minmax(0, 1fr); + gap: 12px; + padding-bottom: 12px; +} + +.console-v2.v2-passive-display .v2-sidebar { + padding: 26px 20px 18px; + background: + radial-gradient(circle at 20% 2%, rgba(255, 255, 255, 0.96), transparent 25%), + linear-gradient(160deg, #e6f7f4 0%, #d5efec 64%, #bfe4df 145%); +} + +.console-v2.v2-passive-display .v2-profile, +.console-v2.v2-passive-display .v2-control-section, +.console-v2.v2-passive-display .v2-config-section, +.console-v2.v2-passive-display .v2-sidebar-toggle, +.console-v2.v2-passive-display .v2-sidebar-footer button { + display: none !important; +} + +.console-v2 .v2-sync-sidebar { + min-height: 0; + display: flex; + flex: 1; + flex-direction: column; + gap: 18px; +} + +.console-v2 .v2-sync-sidebar-heading small, +.console-v2 .v2-unified-brand small, +.console-v2 .v2-device-sync-board header small, +.console-v2 .v2-sync-scope small { + color: #24847f; + font: 850 9px/1.2 "SFMono-Regular", Consolas, monospace; + letter-spacing: 0.14em; +} + +.console-v2 .v2-sync-sidebar-heading h2 { + margin: 7px 0 8px; + color: #0b292a; + font-size: clamp(22px, 1.8vw, 28px); + font-weight: 950; + letter-spacing: -0.045em; +} + +.console-v2 .v2-sync-sidebar-heading p { + margin: 0; + color: #688080; + font-size: 11px; + line-height: 1.75; +} + +.console-v2 .v2-sync-link-stack { + display: grid; + gap: 9px; +} + +.console-v2 .v2-sync-link { + min-height: 58px; + display: grid; + grid-template-columns: 34px minmax(0, 1fr) 8px; + align-items: center; + gap: 10px; + padding: 10px 11px; + background: rgba(255, 255, 255, 0.72); + border: 1px solid rgba(13, 108, 104, 0.1); + border-radius: 14px; + box-shadow: 0 9px 24px rgba(32, 94, 91, 0.06); +} + +.console-v2 .v2-sync-link > svg { + width: 18px; + color: #397a77; +} + +.console-v2 .v2-sync-link div { + min-width: 0; + display: grid; + gap: 2px; +} + +.console-v2 .v2-sync-link strong { + color: #173839; + font-size: 12px; +} + +.console-v2 .v2-sync-link span { + overflow: hidden; + color: #819190; + font-size: 9px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-sync-link > b { + width: 7px; + height: 7px; + background: #b8c5c4; + border-radius: 50%; +} + +.console-v2 .v2-sync-link[data-state="online"] > b { + background: #18a783; + box-shadow: 0 0 0 5px rgba(24, 167, 131, 0.1); +} + +.console-v2 .v2-sync-link[data-state="offline"] > b { + background: #e1786f; +} + +.console-v2 .v2-sync-scope { + padding: 15px; + background: linear-gradient(135deg, rgba(4, 89, 87, 0.92), rgba(17, 125, 117, 0.9)); + border-radius: 16px; + box-shadow: 0 15px 32px rgba(10, 91, 88, 0.14); +} + +.console-v2 .v2-sync-scope small { + color: #a9e9e1; +} + +.console-v2 .v2-sync-scope p { + margin: 8px 0 0; + color: #f2fffd; + font-size: 11px; + font-weight: 650; + line-height: 1.8; +} + +.console-v2 .v2-sync-protocol { + display: flex; + align-items: center; + gap: 10px; + margin-top: auto; + padding: 13px; + background: rgba(255, 255, 255, 0.48); + border: 1px solid rgba(25, 111, 107, 0.1); + border-radius: 14px; +} + +.console-v2 .v2-sync-protocol > svg { + width: 18px; + color: var(--v2-accent); +} + +.console-v2 .v2-sync-protocol div { + min-width: 0; + display: grid; + gap: 3px; +} + +.console-v2 .v2-sync-protocol small { + color: #7d918f; + font-size: 9px; +} + +.console-v2 .v2-sync-protocol strong { + overflow: hidden; + color: #214342; + font-size: 10px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2.v2-passive-display .v2-sidebar-footer { + min-height: 45px; + margin-top: 16px; + padding: 10px 11px 0; + border-top: 1px solid rgba(27, 105, 101, 0.12); +} + +.console-v2.v2-passive-display .v2-module-switcher { + min-height: 68px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto auto; + align-items: center; + gap: 24px; + margin-inline: calc(0px - var(--v2-main-pad)); + padding: 0 var(--v2-main-pad); + overflow: visible; + background: linear-gradient(90deg, #f9fbfa, #edf7f5 70%, #def1ed); + border-bottom: 1px solid rgba(14, 112, 107, 0.12); + box-shadow: 0 8px 22px rgba(33, 83, 81, 0.05); +} + +.console-v2 .v2-unified-brand { + min-width: 0; + display: flex; + align-items: center; + gap: 12px; +} + +.console-v2 .v2-unified-brand-mark { + width: 40px; + height: 40px; + display: grid; + flex: 0 0 auto; + place-items: center; + color: white; + background: linear-gradient(135deg, #064b4b, #13978e); + border-radius: 13px; + box-shadow: 0 10px 22px rgba(10, 100, 96, 0.18); +} + +.console-v2 .v2-unified-brand-mark svg { + width: 21px; +} + +.console-v2 .v2-unified-brand h1 { + overflow: hidden; + margin: 4px 0 0; + color: #102d2e; + font-size: clamp(17px, 1.5vw, 23px); + font-weight: 950; + letter-spacing: -0.04em; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-unified-capabilities { + display: flex; + align-items: center; + gap: 6px; +} + +.console-v2 .v2-unified-capabilities span { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 10px; + color: #2f6562; + background: rgba(255, 255, 255, 0.72); + border: 1px solid rgba(15, 121, 115, 0.1); + border-radius: 999px; + font-size: 10px; + font-weight: 800; +} + +.console-v2 .v2-unified-capabilities i, +.console-v2 .v2-unified-live > i { + width: 6px; + height: 6px; + background: #19a886; + border-radius: 50%; +} + +.console-v2 .v2-unified-live { + display: flex; + align-items: center; + gap: 7px; + color: #4b6e6c; + font: 800 9px/1 "SFMono-Regular", Consolas, monospace; +} + +.console-v2 .v2-unified-live b { + min-width: 65px; + color: #173f3e; + font-size: 11px; +} + +.console-v2.v2-passive-display .v2-natural-panel { + grid-template-columns: minmax(310px, 0.78fr) minmax(430px, 1.22fr); + grid-template-rows: auto 1fr auto; + column-gap: 18px; + padding: 18px 22px; +} + +.console-v2.v2-passive-display .v2-operation-heading { + grid-column: 1; + grid-row: 1; +} + +.console-v2.v2-passive-display .v2-operation-heading h2 { + font-size: clamp(21px, 1.8vw, 29px); +} + +.console-v2.v2-passive-display .v2-natural-grid { + grid-column: 1; + grid-row: 2; + grid-template-columns: minmax(0, 1fr); + align-items: stretch; +} + +.console-v2.v2-passive-display .v2-request-form { + display: none; +} + +.console-v2.v2-passive-display .v2-request-status { + min-height: 0; + padding: 10px 0 0; + background: transparent; + border: 0; + box-shadow: none; +} + +.console-v2.v2-passive-display .v2-request-status .matrix-stat { + display: none; +} + +.console-v2.v2-passive-display .v2-request-status h2 { + font-size: 15px; +} + +.console-v2.v2-passive-display .v2-mode-rail { + min-width: 0; + grid-column: 1; + grid-row: 3; + align-self: end; + padding: 8px 0 0; + background: transparent; + border: 0; +} + +.console-v2.v2-passive-display .v2-mode-rail .mode-rail-heading, +.console-v2.v2-passive-display .v2-mode-rail .mode-rail-controls, +.console-v2.v2-passive-display .v2-mode-rail .save-mode-composer { + display: none !important; +} + +.console-v2.v2-passive-display .v2-mode-rail .mode-chips { + gap: 6px; + padding: 0; +} + +.console-v2.v2-passive-display .v2-mode-rail .mode-chips button { + min-height: 31px; + padding: 5px 10px; + cursor: default; + pointer-events: none; + opacity: 0.68; +} + +.console-v2.v2-passive-display .v2-mode-rail .mode-chips button.v2-sync-active { + color: #fff; + background: linear-gradient(135deg, #0a6d68, #15988f); + border-color: transparent; + box-shadow: 0 8px 18px rgba(11, 119, 113, 0.2); + opacity: 1; +} + +.console-v2 .v2-task-overview { + min-width: 0; + min-height: 0; + display: grid; + grid-column: 2; + grid-row: 1 / 4; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-rows: auto minmax(0, 1fr); + gap: 13px; + padding: 16px 17px; + overflow: hidden; + background: + radial-gradient(circle at 88% 10%, rgba(57, 187, 169, 0.15), transparent 32%), + linear-gradient(145deg, #f5fbfa, #e9f5f2); + border: 1px solid rgba(15, 122, 115, 0.12); + border-radius: 17px; +} + +.console-v2 .v2-task-copy { + min-width: 0; + display: grid; + gap: 5px; +} + +.console-v2 .v2-task-copy span { + color: #31817c; + font-size: 9px; + font-weight: 900; + letter-spacing: 0.08em; +} + +.console-v2 .v2-task-copy strong { + overflow: hidden; + color: #153435; + font-size: clamp(13px, 1.15vw, 17px); + line-height: 1.45; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-task-state { + align-self: start; + padding: 6px 9px; + color: #6d8280; + background: white; + border: 1px solid rgba(72, 116, 113, 0.13); + border-radius: 999px; + font-size: 9px; + font-weight: 850; + white-space: nowrap; +} + +.console-v2 .v2-task-state[data-state="running"] { + color: #076f69; + background: #dff6f2; +} + +.console-v2 .v2-task-state[data-state="succeeded"] { + color: #1d7b5f; + background: #e1f7ec; +} + +.console-v2 .v2-task-state[data-state="partial"] { + color: #9b6b18; + background: #fff5dd; +} + +.console-v2 .v2-task-state[data-state="failed"] { + color: #af504a; + background: #fff0ee; +} + +.console-v2 .v2-task-timeline { + min-width: 0; + display: grid; + grid-column: 1 / -1; + grid-template-columns: repeat(4, minmax(0, 1fr)); + align-self: end; + gap: 7px; +} + +.console-v2 .v2-task-timeline span { + min-width: 0; + display: grid; + grid-template-columns: 25px minmax(0, 1fr); + align-items: center; + gap: 7px; + padding: 8px; + color: #557271; + background: rgba(255, 255, 255, 0.78); + border: 1px solid rgba(15, 115, 109, 0.09); + border-radius: 11px; +} + +.console-v2 .v2-task-timeline i { + width: 25px; + height: 25px; + display: grid; + place-items: center; + color: #fff; + background: #80a9a5; + border-radius: 8px; + font: 800 8px "SFMono-Regular", Consolas, monospace; +} + +.console-v2 .v2-task-timeline .done i, +.console-v2 .v2-task-timeline .active i { + background: var(--v2-accent); +} + +.console-v2 .v2-task-timeline .active i { + box-shadow: 0 0 0 5px rgba(14, 128, 122, 0.1); +} + +.console-v2 .v2-task-timeline b { + overflow: hidden; + font-size: 9px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2.v2-passive-display .v2-output-shell, +.console-v2.v2-passive-display .v2-output-content { + min-height: 0; +} + +.console-v2.v2-passive-display .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(480px, 1.16fr) minmax(360px, 0.84fr); + grid-template-rows: minmax(0, 1fr); + gap: 12px; +} + +.console-v2.v2-passive-display .joint-twin-shell > .twin-band { + min-width: 0; + min-height: 0; + grid-column: 1; + grid-row: 1; +} + +.console-v2 .v2-unified-right-rail { + min-width: 0; + min-height: 0; + display: grid; + grid-column: 2; + grid-row: 1; + grid-template-rows: minmax(240px, 1.25fr) minmax(160px, 0.75fr); + gap: 10px; + overflow: hidden; +} + +.console-v2 .v2-source-state-only, +.console-v2.v2-passive-display .state-band { + display: none !important; +} + +.console-v2 .v2-device-sync-board { + min-width: 0; + min-height: 0; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + padding: 10px; + overflow: hidden; + background: #fff; + border: 1px solid rgba(71, 112, 110, 0.12); + border-radius: 18px; + box-shadow: 0 13px 34px rgba(41, 74, 75, 0.07); +} + +.console-v2 .v2-device-sync-board > header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 1px 2px 7px; +} + +.console-v2 .v2-device-sync-board h3 { + margin: 3px 0 0; + color: #183435; + font-size: 15px; +} + +.console-v2 .v2-device-sync-board > header > span { + display: inline-flex; + align-items: center; + gap: 6px; + color: #5a7a78; + font-size: 8px; + font-weight: 800; +} + +.console-v2 .v2-device-sync-board > header > span i { + width: 6px; + height: 6px; + background: #18a783; + border-radius: 50%; +} + +.console-v2 .v2-device-sync-grid { + min-height: 0; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-rows: repeat(4, minmax(38px, 1fr)); + gap: 5px 7px; +} + +.console-v2 .v2-synced-device { + min-width: 0; + display: grid; + grid-template-columns: 27px minmax(0, 1fr) 6px; + align-items: center; + gap: 8px; + padding: 4px 7px; + background: linear-gradient(145deg, #f7faf9, #eff5f4); + border: 1px solid rgba(75, 119, 116, 0.08); + border-radius: 12px; +} + +.console-v2 .v2-synced-device > span { + width: 27px; + height: 27px; + display: grid; + place-items: center; + color: #236f6b; + background: #dff2ef; + border-radius: 10px; +} + +.console-v2 .v2-synced-device > span svg { + width: 13px; +} + +.console-v2 .v2-synced-device > div { + min-width: 0; + display: grid; + gap: 3px; +} + +.console-v2 .v2-synced-device strong { + color: #1d3a3b; + font-size: 10px; +} + +.console-v2 .v2-synced-device small { + overflow: hidden; + color: #7e908f; + font-size: 8px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.console-v2 .v2-device-signal { + width: 6px; + height: 6px; + background: #becac9; + border-radius: 50%; +} + +.console-v2 .v2-synced-device[data-ready="true"] .v2-device-signal { + background: #18a783; +} + +.console-v2 .v2-extension-sync-mount { + min-width: 0; +} + +@media (max-height: 760px) { + .console-v2.v2-passive-display .main-panel { + grid-template-rows: 60px 198px minmax(0, 1fr); + } + + .console-v2.v2-passive-display .v2-module-switcher { + min-height: 60px; + } + + .console-v2.v2-passive-display .v2-natural-panel { + padding-block: 13px; + } + + .console-v2 .v2-task-timeline span { + padding: 6px; + } +} + +@media (max-width: 1280px) { + .console-v2.v2-passive-display .workspace { + grid-template-columns: 220px minmax(0, 1fr); + } + + .console-v2.v2-passive-display .v2-sidebar { + padding-inline: 15px; + } + + .console-v2 .v2-unified-capabilities { + display: none; + } + + .console-v2.v2-passive-display .v2-natural-panel { + grid-template-columns: minmax(280px, 0.7fr) minmax(390px, 1.3fr); + } + + .console-v2.v2-passive-display .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(440px, 1.1fr) minmax(330px, 0.9fr); + } +} + @media (max-width: 1366px) { .console-v2 { min-width: 1120px; @@ -4736,3 +5987,649 @@ body.device-power-drawer-open { font-size: 11px; } } + +/* Final cascade for the interactive sync workspace. */ +.console-v2.v2-passive-display.v2-interactive-sync .workspace { + grid-template-columns: clamp(250px, 19vw, 292px) minmax(0, 1fr); +} + +.console-v2.v2-passive-display.v2-interactive-sync .main-panel { + grid-template-rows: 56px clamp(224px, 29dvh, 254px) minmax(0, 1fr); + gap: 10px; + padding-bottom: 10px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-module-switcher { + min-height: 56px; + grid-template-columns: minmax(0, 1fr) auto auto; + gap: 18px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-natural-panel { + grid-template-columns: minmax(390px, 0.95fr) minmax(390px, 1.05fr); + grid-template-rows: auto minmax(76px, 1fr) auto; + column-gap: 14px; + row-gap: 7px; + padding: 13px 16px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-natural-grid { + display: grid; + grid-column: 1; + grid-row: 2; + grid-template-columns: minmax(0, 1fr); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-request-form { + display: grid; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-request-status { + display: none; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail { + grid-column: 1; + grid-row: 3; + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: 10px; + padding: 0; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-rail-heading { + display: flex !important; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button { + min-height: 29px; + padding: 4px 10px; + cursor: pointer; + pointer-events: auto; + opacity: 1; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-task-overview { + grid-column: 2; + grid-row: 1 / 4; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(0, 1.25fr) minmax(320px, 0.75fr); + grid-template-rows: minmax(0, 1fr); + gap: 10px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] { + grid-template-columns: minmax(0, 1fr); +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell > .twin-band { + width: 100%; + max-width: 980px; + grid-column: 1; + grid-row: 1; + justify-self: center; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-rows: none; + grid-auto-rows: minmax(76px, auto); + overflow: auto; +} + +@media (max-width: 1366px) { + .console-v2.v2-passive-display.v2-interactive-sync .workspace { + grid-template-columns: 250px minmax(0, 1fr); + } + + .console-v2.v2-passive-display.v2-interactive-sync .v2-natural-panel { + grid-template-columns: minmax(360px, 0.9fr) minmax(370px, 1.1fr); + } + + .console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(0, 1fr) minmax(310px, 0.72fr); + } +} + +@media (max-height: 760px) { + .console-v2.v2-passive-display.v2-interactive-sync .main-panel { + grid-template-rows: 52px 216px minmax(0, 1fr); + } + + .console-v2.v2-passive-display.v2-interactive-sync .v2-module-switcher { + min-height: 52px; + } + + .console-v2.v2-passive-display.v2-interactive-sync .v2-natural-panel { + padding-block: 10px; + } +} + +/* Symmetric three-column twin workspace --------------------------------- */ +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail { + grid-template-columns: auto minmax(0, 1fr) auto; + gap: 8px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips { + min-width: 0; + grid-column: 2; + display: flex; + padding: 1px; + overflow-x: auto; + scroll-behavior: smooth; + overscroll-behavior-x: contain; + touch-action: pan-x; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button { + min-width: 94px; + flex: 0 0 auto; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-rail-controls { + display: flex !important; + grid-column: 3; + grid-row: 1; + align-items: center; + gap: 5px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-rail-pager { + display: grid; + grid-template-columns: repeat(2, 26px); + padding: 2px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-rail-page { + width: 26px; + height: 26px; + display: grid; + place-items: center; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-gallery-toggle { + min-height: 30px; + display: inline-flex; + align-items: center; + gap: 5px; + padding: 4px 8px; + white-space: nowrap; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell.v2-output-page, +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] { + grid-template-columns: minmax(198px, 0.52fr) minmax(420px, 1.25fr) minmax(198px, 0.52fr); + grid-template-rows: minmax(0, 1fr); + gap: 8px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="devices"] { + grid-template-columns: minmax(210px, 0.58fr) minmax(460px, 1.42fr) 42px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="extensions"] { + grid-template-columns: 42px minmax(460px, 1.42fr) minmax(210px, 0.58fr); +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] { + grid-template-columns: 42px minmax(520px, 1fr) 42px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-unified-right-rail, +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] .v2-unified-right-rail { + display: contents !important; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell > .twin-band { + width: 100%; + max-width: none; + grid-column: 2; + grid-row: 1; + justify-self: stretch; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel { + grid-column: 1; + grid-row: 1; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel { + grid-column: 3; + grid-row: 1; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-side-status-panel { + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-board > header { + grid-template-columns: minmax(0, 1fr) auto; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-board > header > span { + display: none; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-board > header > button, +.console-v2.v2-passive-display.v2-interactive-sync .v2-extension-sync-heading > button { + width: auto; + min-width: 52px; + height: 28px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + padding: 0 7px; + font-size: 8px; + font-weight: 800; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-grid { + grid-template-columns: minmax(0, 1fr); + grid-template-rows: none; + grid-auto-rows: minmax(82px, auto); + gap: 6px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-synced-device dl { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-extension-sync-heading { + grid-template-columns: minmax(0, 1fr) auto; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-extension-sync-heading > span { + display: none; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-side-status-panel.is-collapsed { + display: grid !important; + grid-template-rows: minmax(0, 1fr) !important; + place-items: stretch; + padding: 0; + overflow: hidden; + background: linear-gradient(180deg, rgba(229, 245, 242, 0.96), rgba(203, 233, 228, 0.96)); + border: 1px solid rgba(15, 116, 109, 0.15); + border-radius: 14px; + box-shadow: none; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > header { + width: 100%; + height: 100%; + display: grid; + padding: 0; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > header > div, +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > header > span, +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > .v2-device-sync-grid { + display: none; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > header > button, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-heading > button { + width: 100%; + min-width: 0; + height: 100%; + min-height: 120px; + flex-direction: column; + gap: 8px; + padding: 10px 0; + color: #0b756f; + background: transparent; + border-radius: 13px; + writing-mode: vertical-rl; + cursor: pointer; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > header > button:hover, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-heading > button:hover { + color: #fff; + background: #0b807a; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel.is-collapsed > header > button svg, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-heading > button svg { + width: 16px; + height: 16px; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-mount { + height: 100%; + display: grid; + grid-template-rows: minmax(0, 1fr); + padding: 0; + overflow: hidden; + background: linear-gradient(180deg, #143b3c, #0e2d2f); + border: 0; + border-radius: 13px; + box-shadow: none; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-heading { + height: 100%; + display: grid; + grid-template-columns: minmax(0, 1fr); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-heading > div, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-heading > span, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-gateway, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-device-list, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-linkage { + display: none; +} + +.console-v2 .v2-panel-visibility-controls button { + min-height: 30px; +} + +.console-v2 .v2-panel-visibility-controls button b { + padding-left: 5px; + color: #74918e; + border-left: 1px solid rgba(46, 105, 101, 0.12); + font-size: 7px; +} + +.console-v2 .v2-panel-visibility-controls button:not(.active) b { + color: #a07942; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-panel-visibility-controls { + display: none !important; +} + +/* Hotspots follow the actual rendered vehicle: rear at left, front at right. */ +.console-v2 .v2-twin-hotspots [data-twin-device="windows"] { top: 50%; left: 42%; } +.console-v2 .v2-twin-hotspots [data-twin-device="shade"] { top: 25%; left: 53%; } +.console-v2 .v2-twin-hotspots [data-twin-device="driver"] { top: 45%; left: 62%; } +.console-v2 .v2-twin-hotspots [data-twin-device="passenger"] { top: 57%; left: 52%; } +.console-v2 .v2-twin-hotspots [data-twin-device="reading"] { top: 36%; left: 55%; } +.console-v2 .v2-twin-hotspots [data-twin-device="ambient"] { top: 62%; left: 66%; } +.console-v2 .v2-twin-hotspots [data-twin-device="headlight"] { top: 66%; left: 86%; } +.console-v2 .v2-twin-hotspots [data-twin-device="climate"] { top: 48%; left: 73%; } + +@media (max-width: 1200px) { + .console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell.v2-output-page { + grid-template-columns: minmax(180px, 0.48fr) minmax(390px, 1.3fr) minmax(180px, 0.48fr); + } + + .console-v2 .v2-panel-visibility-controls button b { + display: none; + } +} + +/* Cohesive light cockpit visual refresh --------------------------------- */ +.console-v2.v2-passive-display.v2-interactive-sync { + --v2-canvas: #edf4f2; + --v2-line: rgba(16, 105, 99, 0.13); + --v2-shadow: 0 16px 40px rgba(38, 80, 77, 0.09); + background: + radial-gradient(circle at 76% -8%, rgba(93, 202, 187, 0.16), transparent 34%), + linear-gradient(145deg, #eef5f3 0%, #f7faf9 56%, #e9f3f0 100%); +} + +.console-v2.v2-passive-display.v2-interactive-sync .workspace { + background: + radial-gradient(circle at 73% -10%, rgba(93, 202, 187, 0.13), transparent 34%), + linear-gradient(145deg, #edf4f2 0%, #f7faf9 58%, #eaf3f1 100%); +} + +.console-v2.v2-passive-display.v2-interactive-sync .command-panel.v2-sidebar { + background: + radial-gradient(circle at 12% 2%, rgba(255, 255, 255, 0.92), transparent 24%), + linear-gradient(158deg, #e0f4f1 0%, #edf8f6 58%, #d2ebe7 132%); + border-right-color: rgba(15, 111, 104, 0.12); + box-shadow: inset -1px 0 0 rgba(255, 255, 255, 0.6); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-module-switcher { + background: rgba(249, 252, 251, 0.9); + border-bottom: 1px solid rgba(16, 105, 99, 0.1); + box-shadow: 0 5px 20px rgba(39, 82, 79, 0.045); + backdrop-filter: blur(14px); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-natural-panel { + background: + radial-gradient(circle at 88% 12%, rgba(126, 217, 204, 0.16), transparent 28%), + linear-gradient(145deg, rgba(255, 255, 255, 0.98), rgba(247, 252, 250, 0.96)); + border: 1px solid rgba(19, 111, 105, 0.11); + border-radius: 19px; + box-shadow: 0 12px 34px rgba(37, 82, 78, 0.075); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-task-overview { + background: linear-gradient(145deg, rgba(247, 253, 251, 0.96), rgba(230, 246, 242, 0.92)); + border-color: rgba(23, 122, 114, 0.12); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-sync-log { + background: rgba(251, 253, 252, 0.8); + border-color: rgba(20, 111, 104, 0.1); + box-shadow: 0 12px 28px rgba(35, 84, 80, 0.055); + backdrop-filter: blur(10px); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button { + color: #426967; + background: rgba(242, 250, 248, 0.94); + border: 1px solid rgba(20, 117, 109, 0.08); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.84); + transition: color 160ms ease, background 160ms ease, border-color 160ms ease, transform 160ms ease; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button:hover, +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button:focus-visible { + color: #0b6d67; + background: #e4f5f1; + border-color: rgba(13, 126, 117, 0.2); + transform: translateY(-1px); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button.active, +.console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button[aria-pressed="true"] { + color: #ffffff; + background: linear-gradient(135deg, #118a81, #0a6f69); + border-color: transparent; + box-shadow: 0 7px 16px rgba(13, 126, 117, 0.2); +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell.v2-output-page, +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell[data-open-panels="none"] { + gap: 10px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell > .twin-band, +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-sync-mount { + border: 1px solid rgba(17, 112, 105, 0.12); + border-radius: 18px; + box-shadow: + 0 14px 32px rgba(35, 78, 75, 0.075), + inset 0 1px 0 rgba(255, 255, 255, 0.78); +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell > .twin-band { + overflow: hidden; + background: linear-gradient(180deg, #fbfdfc, #eff6f4); +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell .twin-heading { + background: + linear-gradient(90deg, rgba(240, 249, 247, 0.98), rgba(251, 253, 252, 0.98)); + border-bottom-color: rgba(18, 113, 106, 0.1); +} + +.console-v2.v2-passive-display.v2-interactive-sync .joint-twin-shell .twin-stage { + background: + radial-gradient(ellipse at 53% 57%, rgba(108, 205, 190, 0.13), transparent 41%), + linear-gradient(165deg, #f7fbfa 0%, #eaf3f1 100%); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2DevicePanel { + background: linear-gradient(180deg, rgba(252, 254, 253, 0.98), rgba(239, 247, 245, 0.97)); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-board > header, +.console-v2.v2-passive-display.v2-interactive-sync .v2-extension-sync-heading { + min-height: 39px; + padding: 2px 2px 8px; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-board > header > button, +.console-v2.v2-passive-display.v2-interactive-sync .v2-extension-sync-heading > button { + color: #527371; + background: rgba(255, 255, 255, 0.78); + border: 1px solid rgba(19, 105, 99, 0.12); + box-shadow: 0 3px 9px rgba(37, 84, 80, 0.055); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-device-sync-board > header > button:hover, +.console-v2.v2-passive-display.v2-interactive-sync .v2-extension-sync-heading > button:hover { + color: #0b756f; + background: #e3f4f1; + border-color: rgba(13, 126, 117, 0.21); +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-synced-device { + background: rgba(255, 255, 255, 0.76); + border: 1px solid rgba(23, 110, 104, 0.085); + box-shadow: 0 4px 12px rgba(42, 87, 83, 0.045); + transition: background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease; +} + +.console-v2.v2-passive-display.v2-interactive-sync .v2-synced-device:hover, +.console-v2.v2-passive-display.v2-interactive-sync .v2-synced-device.active { + background: linear-gradient(145deg, #e8f7f3, #fbfdfc); + border-color: rgba(13, 126, 117, 0.22); + box-shadow: 0 8px 19px rgba(29, 100, 94, 0.09); + transform: translateY(-1px); +} + +/* The extension area now shares the same light surface hierarchy. */ +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-sync-mount { + background: + radial-gradient(circle at 84% 8%, rgba(118, 211, 198, 0.15), transparent 30%), + linear-gradient(180deg, rgba(251, 254, 253, 0.99), rgba(237, 247, 244, 0.98)); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-sync-heading small { + color: #287f79; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-sync-heading h3 { + color: #183536; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-gateway { + background: rgba(255, 255, 255, 0.74); + border: 1px solid rgba(21, 111, 104, 0.1); + box-shadow: 0 5px 14px rgba(39, 85, 81, 0.05); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-gateway > span { + color: #168b82; + background: linear-gradient(145deg, #e3f6f2, #d5efea); + box-shadow: inset 0 0 0 1px rgba(21, 137, 128, 0.08); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-gateway strong { + color: #294846; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-gateway small { + color: #718684; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-gateway > b { + color: #0d7972; + background: #e1f3ef; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-synced-device { + background: rgba(255, 255, 255, 0.78); + border: 1px solid rgba(21, 111, 104, 0.1); + box-shadow: 0 5px 14px rgba(39, 85, 81, 0.05); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-synced-device header > span { + color: #15877f; + background: #ddf2ee; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-synced-device header strong { + color: #294846; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-synced-device header small, +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-synced-device header b { + color: #738987; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-synced-device > div span { + color: #3d6d68; + background: #e7f4f1; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-empty { + min-height: 92px; + color: #668b87; + background: rgba(255, 255, 255, 0.52); + border: 1px dashed rgba(23, 121, 113, 0.15); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-empty > svg { + color: #4c9e97; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-empty strong { + color: #365957; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-empty span { + color: #7b908e; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-linkage { + border-top-color: rgba(21, 112, 105, 0.11); +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-linkage > svg { + color: #438f89; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-linkage small { + color: #738987; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-linkage strong { + color: #3d5f5c; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel .v2-extension-linkage > span { + color: #0d7972; +} + +.console-v2.v2-passive-display.v2-interactive-sync #v2ExtensionPanel.is-collapsed .v2-extension-sync-mount { + background: linear-gradient(180deg, rgba(238, 248, 245, 0.98), rgba(215, 238, 233, 0.98)); + border: 0; + border-radius: 13px; + box-shadow: none; +} + +@media (prefers-reduced-motion: reduce) { + .console-v2.v2-passive-display.v2-interactive-sync .v2-mode-rail .mode-chips button, + .console-v2.v2-passive-display.v2-interactive-sync .v2-synced-device { + transition: none; + } +} diff --git a/apps/web-console/console-v2.js b/apps/web-console/console-v2.js index 4613fdf..8083f9c 100644 --- a/apps/web-console/console-v2.js +++ b/apps/web-console/console-v2.js @@ -11,25 +11,11 @@ const $ = (selector, root = document) => root.querySelector(selector); const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]; - const initialRole = sessionStorage.getItem("cognitive-agent.demo-role") === "admin" - ? "admin" - : "user"; - const storedModule = sessionStorage.getItem("cognitive-agent.active-module"); - const ui = { - role: initialRole, controlMode: sessionStorage.getItem("cognitive-agent.control-mode") === "gesture" ? "gesture" : "natural", - activeModule: storedModule === "self-evolution" - ? "self-evolution" - : storedModule === "self-extension" - ? "self-extension" - : storedModule === "self-calibration" - ? "self-calibration" - : storedModule === "self-repair" - ? "self-repair" - : "self-orchestration", + activeModule: "self-orchestration", activePage: 0, sidebarCollapsed: sessionStorage.getItem("cognitive-agent.sidebar-collapsed") === "true", }; @@ -44,6 +30,15 @@ return node; } + function escapeHtml(value) { + return String(value ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); + } + function closeCustomDropdowns(except = null) { dropdownControls.forEach((control) => { if (control !== except) control.close(); @@ -246,7 +241,7 @@ } function enhanceConfiguredDropdowns() { - [$("#v2RoleSelect"), $("#vehicleSelect"), $("#v2ExecutionSelect")] + [$("#vehicleSelect")] .filter(Boolean) .forEach(enhanceSelect); } @@ -260,13 +255,6 @@
WELCOME TO THE CABIN
- Hi, - -
-
Hi,user
@@ -296,7 +284,6 @@ `); commandPanel.append(profile, control, config, footer); - $("#v2RoleSelect").value = ui.role; return $("#v2ConfigStack"); } @@ -355,21 +342,6 @@ configStack.append(providerField); } - const executionSelect = make("div", "v2-config-field v2-execution-field", ` -
- -
执行目标
- -
- ADMIN -
-

管理员可切换执行环境

`); - configStack.append(executionSelect); - if (executionField) { executionField.classList.add("v2-native-execution-field"); executionField.hidden = true; @@ -398,9 +370,9 @@ const kicker = $(".section-kicker", panelHeading); const title = $("h2", panelHeading); const intro = $(".panel-intro", panelHeading); - if (kicker) kicker.textContent = "SELF-ORCHESTRATION"; - if (title) title.textContent = "一句话,调好整车"; - if (intro) intro.textContent = "座椅、空调、天幕与氛围灯,一句话联动完成"; + if (kicker) kicker.textContent = "REMOTE ORCHESTRATION · LIVE SYNC"; + if (title) title.textContent = "一句话远程编排"; + if (intro) intro.textContent = "网页指令将通过同步链路发送至车机;车机任务与执行反馈在右侧实时更新"; naturalPanel.append(panelHeading); } @@ -428,7 +400,6 @@ gestureDrawer.classList.add("v2-inline-gesture"); const cameraStage = $(".gesture-camera-stage", gestureDrawer); const cameraToggle = $("#gestureStartButton", gestureDrawer); - const debugToggle = $("#gestureArmButton", gestureDrawer); const actionRail = $(".gesture-actions", gestureDrawer); const statusStrip = $(".gesture-status-strip", gestureDrawer); const gestureNow = $(".gesture-now", gestureDrawer); @@ -438,9 +409,8 @@ cameraToggle.setAttribute("aria-label", "开启摄像头"); cameraToggle.setAttribute("title", "开启摄像头"); } - if (actionRail && cameraToggle && debugToggle) { + if (actionRail && cameraToggle) { actionRail.classList.add("v2-gesture-action-rail"); - actionRail.insertBefore(debugToggle, cameraToggle); actionRail.append(cameraToggle); } @@ -465,42 +435,17 @@ } function buildModuleSwitcher(mainPanel) { - const modules = [ - { - id: "self-calibration", - label: "自标定", - available: true, - adminOnly: true, - }, - { id: "self-orchestration", label: "自编排", available: true }, - { id: "self-extension", label: "自扩展", available: true }, - { - id: "self-repair", - label: "自修复", - available: true, - adminOnly: true, - }, - { id: "self-evolution", label: "自进化", available: true }, - ]; const switcher = make("nav", "v2-module-switcher", ""); switcher.id = "v2ModuleSwitcher"; - switcher.setAttribute("role", "tablist"); - switcher.setAttribute("aria-label", "能力模块切换"); - modules.forEach((module, index) => { - const button = make("button", "v2-module-tab", `${module.label}`); - button.type = "button"; - button.id = `v2ModuleTab${index}`; - button.dataset.module = module.id; - button.setAttribute("role", "tab"); - button.setAttribute("aria-selected", "false"); - if (module.adminOnly) button.dataset.adminOnly = "true"; - if (!module.available) { - button.disabled = true; - button.setAttribute("aria-disabled", "true"); - button.title = module.adminOnly ? `${module.label}仅对 admin 开放` : `${module.label}模块待接入`; - } - switcher.append(button); - }); + switcher.dataset.unifiedSync = "true"; + switcher.setAttribute("aria-label", "智能座舱远程控制与同步状态"); + switcher.innerHTML = ` +
+ +
COCKPIT REMOTE · LIVE MIRROR

511工程-智能座舱

+
+
网页控制链路已启用
+
LIVE--:--:--
`; mainPanel.prepend(switcher); } @@ -515,7 +460,7 @@ LIVE STATE
- `); + `); mainPanel.append(output); const content = $("#v2OutputContent"); @@ -543,9 +488,523 @@ }); } + const displaySync = { + revision: -1, + requestId: null, + pollTimer: null, + deviceFrame: null, + activeDevice: null, + pinnedDevice: null, + logs: [], + logKeys: new Set(), + extensionFingerprint: "", + }; + + const readText = (selector, fallback = "--") => $(selector)?.textContent?.trim() || fallback; + + function seatDeviceRows(seat) { + const card = $(`.seat-card[data-seat="${seat}"]`); + if (!card) return [["状态", "等待反馈"]]; + const rows = [ + ["反馈通道", $("[data-seat-feedback]", card)?.textContent?.trim() || "等待反馈"], + ...$$('[data-function]', card).map((item) => [ + item.textContent.replace(item.querySelector("b")?.textContent || "", "").trim(), + $("b", item)?.textContent?.trim() || "--", + ]), + ...$$('.motion-axis', card).map((item) => [ + $("span", item)?.textContent?.trim() || "姿态", + $("b", item)?.textContent?.trim() || "--", + ]), + ]; + return rows.filter(([label]) => label); + } + + const syncedDevices = [ + { + id: "windows", name: "车窗", icon: "gallery-vertical-end", + rows: () => [["设备状态", readText("#windowState", "等待反馈")], ["左前窗", readText("#frontLeftWindow")], ["右前窗", readText("#frontRightWindow")], ["左后窗", readText("#rearLeftWindow")], ["右后窗", readText("#rearRightWindow")]], + }, + { + id: "shade", name: "遮阳帘", icon: "panels-top-left", + rows: () => [["设备状态", readText("#roofState", "等待反馈")], ["当前位置", readText("#shadePositionValue")], ["动作", readText("#shadeMotionState")], ["初始化", readText("#shadeInitializedState")], ["热保护", readText("#shadeThermalState")]], + }, + { id: "driver", name: "主驾座椅", icon: "armchair", rows: () => seatDeviceRows("driver") }, + { id: "passenger", name: "副驾座椅", icon: "armchair", rows: () => seatDeviceRows("passenger") }, + { + id: "reading", name: "阅读灯", icon: "book-open", + rows: () => [["开关状态", readText("#interiorLightPower", "等待反馈")], ["控制通道", "CH1 · INTERIOR"], ["控制能力", "开 / 关"]], + }, + { + id: "ambient", name: "氛围灯", icon: "sparkles", + rows: () => [["电源", readText("#ambientPower", "等待反馈")], ["模式", readText("#ambientMode")], ["前/后排亮度", readText("#ambientBrightness")], ["前/后排色号", readText("#ambientColorIndex")]], + }, + { + id: "headlight", name: "前大灯", icon: "car-front", + rows: () => [["设备状态", readText("#frontLightState", "等待反馈")], ["近光灯", readText("#lowBeamState")], ["远光灯", readText("#highBeamState")], ["雾灯", readText("#fogLightState")], ["转向灯", readText("#turnSignalState")]], + }, + { + id: "climate", name: "空调", icon: "fan", + rows: () => [["电源", readText("#climatePower", "等待反馈")], ["主驾温度", readText("#driverTemperature")], ["副驾温度", readText("#passengerTemperature")], ["风量", readText("#fanLevel")], ["主驾风向", readText("#driverAirDirection")], ["副驾风向", readText("#passengerAirDirection")], ["循环", readText("#cycleMode")], ["A/C", readText("#acState")], ["前除霜", readText("#defrostState")]], + }, + ]; + + function deviceSummary(device) { + const values = device.rows().map(([, value]) => value).filter(Boolean); + return values.slice(0, 3).join(" · ") || "等待反馈"; + } + + function renderSyncedDevices() { + const grid = $("#v2DeviceSyncGrid"); + if (!grid) return; + grid.innerHTML = syncedDevices.map((device) => { + const rows = device.rows(); + const detail = deviceSummary(device); + const waiting = /--|等待|同步中|未知/.test(detail); + return ``; + }).join(""); + if (displaySync.activeDevice) { + $(`.v2-synced-device[data-device="${displaySync.activeDevice}"]`)?.classList.add("active"); + } + window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); + } + + function scheduleSyncedDeviceRender() { + if (displaySync.deviceFrame) return; + displaySync.deviceFrame = requestAnimationFrame(() => { + displaySync.deviceFrame = null; + renderSyncedDevices(); + if (displaySync.activeDevice) presentTwinDevice(displaySync.activeDevice, { + pinned: Boolean(displaySync.pinnedDevice), + selectSeat: false, + }); + }); + } + + function appendSyncLog({ key = "", category = "sync", title, detail = "", status = "info" }) { + if (!title || (key && displaySync.logKeys.has(key))) return; + const item = { + key, + category, + title, + detail, + status, + time: new Intl.DateTimeFormat("zh-CN", { + hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, + }).format(new Date()), + }; + if (key) displaySync.logKeys.add(key); + displaySync.logs.unshift(item); + if (displaySync.logs.length > 40) { + const removed = displaySync.logs.pop(); + if (removed?.key) displaySync.logKeys.delete(removed.key); + } + renderSyncLogs(); + } + + function renderSyncLogs() { + const list = $("#v2SyncLogList"); + if (!list) return; + const filter = $("#v2LogFilter")?.value || "all"; + const items = displaySync.logs.filter((item) => filter === "all" || item.category === filter); + const icons = { task: "route", sync: "refresh-cw", extension: "usb", device: "activity" }; + list.innerHTML = items.length ? items.map((item) => ` +
  • + + +
    ${escapeHtml(item.title)}${escapeHtml(item.detail)}
    +
  • `).join("") : '
  • 暂无记录车机任务、设备反馈与外设事件会显示在这里
  • '; + window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); + } + + function panelVisible(key) { + const panel = key === "devices" ? $("#v2DevicePanel") : $("#v2ExtensionPanel"); + if (panel) return !panel.classList.contains("is-collapsed"); + return sessionStorage.getItem(`cognitive-agent.sync-panel.${key}`) !== "hidden"; + } + + function setSidePanelVisibility(key, visible) { + const panel = key === "devices" ? $("#v2DevicePanel") : $("#v2ExtensionPanel"); + if (!panel) return; + panel.hidden = false; + panel.classList.toggle("is-collapsed", !visible); + panel.dataset.collapsed = String(!visible); + sessionStorage.setItem(`cognitive-agent.sync-panel.${key}`, visible ? "visible" : "hidden"); + $$(`[data-panel-toggle="${key}"], [data-panel-close="${key}"]`).forEach((button) => { + button.classList.toggle("active", visible); + button.setAttribute("aria-pressed", String(visible)); + button.setAttribute("aria-label", `${visible ? "收起" : "展开"}${key === "devices" ? "车端设备状态" : "外设与扩展能力"}`); + const actionLabel = $("[data-panel-action-label]", button); + if (actionLabel) actionLabel.textContent = visible ? "收起" : "展开"; + const stateLabel = $("[data-panel-state-label]", button); + if (stateLabel) stateLabel.textContent = visible ? "已展开" : "已收起"; + }); + const openPanels = ["devices", "extensions"].filter((panelKey) => { + const candidate = panelKey === "devices" ? $("#v2DevicePanel") : $("#v2ExtensionPanel"); + return candidate && !candidate.classList.contains("is-collapsed"); + }); + $(".joint-twin-shell")?.setAttribute("data-open-panels", openPanels.join(" ") || "none"); + window.dispatchEvent(new Event("resize")); + } + + function presentTwinDevice(deviceId, { pinned = false, selectSeat = pinned } = {}) { + const device = syncedDevices.find((item) => item.id === deviceId); + const popover = $("#v2TwinDevicePopover"); + if (!device || !popover) return; + displaySync.activeDevice = deviceId; + if (pinned) displaySync.pinnedDevice = deviceId; + const rows = device.rows(); + popover.hidden = false; + popover.dataset.device = deviceId; + popover.dataset.pinned = String(Boolean(displaySync.pinnedDevice)); + popover.innerHTML = ` +
    LIVE DEVICE FEEDBACK${escapeHtml(device.name)}
    ${pinned ? "已固定" : "靠近查看"}
    +
    ${rows.map(([label, value]) => `
    ${escapeHtml(label)}
    ${escapeHtml(value)}
    `).join("")}
    `; + $$("[data-twin-device]").forEach((button) => button.classList.toggle("active", button.dataset.twinDevice === deviceId)); + $$(".v2-synced-device").forEach((button) => button.classList.toggle("active", button.dataset.device === deviceId)); + if (selectSeat && ["driver", "passenger"].includes(deviceId)) { + $(`[data-twin-seat="${deviceId}"]`)?.click(); + } + window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); + } + + function clearTwinDevicePreview({ force = false } = {}) { + if (displaySync.pinnedDevice && !force) return; + displaySync.activeDevice = null; + if (force) displaySync.pinnedDevice = null; + const popover = $("#v2TwinDevicePopover"); + if (popover) popover.hidden = true; + $$("[data-twin-device], .v2-synced-device").forEach((button) => button.classList.remove("active")); + } + + function buildTwinDeviceInteractions() { + const stage = $("#seatTwin"); + if (!stage || $("#v2TwinHotspots")) return; + const hotspots = make("div", "v2-twin-hotspots", syncedDevices.map((device) => ` + `).join("")); + hotspots.id = "v2TwinHotspots"; + const popover = make("aside", "v2-twin-device-popover", ""); + popover.id = "v2TwinDevicePopover"; + popover.hidden = true; + popover.setAttribute("aria-live", "polite"); + stage.append(hotspots, popover); + + hotspots.addEventListener("pointerdown", (event) => event.stopPropagation()); + hotspots.addEventListener("pointerover", (event) => { + const button = event.target.closest("[data-twin-device]"); + if (button && !displaySync.pinnedDevice) presentTwinDevice(button.dataset.twinDevice); + }); + hotspots.addEventListener("focusin", (event) => { + const button = event.target.closest("[data-twin-device]"); + if (button) presentTwinDevice(button.dataset.twinDevice); + }); + hotspots.addEventListener("pointerout", (event) => { + if (event.relatedTarget?.closest?.("#v2TwinDevicePopover")) return; + window.setTimeout(() => clearTwinDevicePreview(), 100); + }); + hotspots.addEventListener("click", (event) => { + const button = event.target.closest("[data-twin-device]"); + if (!button) return; + event.stopPropagation(); + const samePinned = displaySync.pinnedDevice === button.dataset.twinDevice; + if (samePinned) clearTwinDevicePreview({ force: true }); + else presentTwinDevice(button.dataset.twinDevice, { pinned: true }); + }); + popover.addEventListener("pointerdown", (event) => event.stopPropagation()); + window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); + } + + function taskKind(utterance, result, source = "") { + if (source === "web_console") return "网页远程编排"; + if (result?.mode_profile) return "自定义功能模式"; + const preset = $$(".mode-chips [data-mode-command]").find((button) => ( + String(utterance).includes(button.textContent.trim()) + || button.dataset.modeCommand === utterance + )); + return preset ? "预设功能模式" : utterance ? "一句话自定义编排" : "等待编排任务"; + } + + function renderTaskTimeline(task) { + const timeline = $("#v2TaskTimeline"); + if (!timeline) return; + const result = task?.result; + const trace = Array.isArray(result?.trace_events) ? result.trace_events : []; + const domains = Object.keys(result?.function_configs || {}); + const stages = task?.status === "running" + ? ["接收编排指令", "解析意图", "构建功能模式", "等待设备反馈"] + : trace.length + ? trace.slice(-4).map((item) => item.label || item.stage || item.event || "执行步骤") + : domains.length + ? ["接收编排指令", `编排 ${domains.length} 个设备域`, "下发执行计划", "同步执行结果"] + : ["等待车机或网页端下发编排任务"]; + timeline.innerHTML = stages.map((stage, index) => ` + + ${String(index + 1).padStart(2, "0")}${escapeHtml(stage)} + `).join(""); + } + + function setTaskPresentation(task = {}) { + const utterance = String(task.utterance || ""); + const result = task.result && typeof task.result === "object" ? task.result : null; + const input = $("#utterance"); + if (input && utterance && document.activeElement !== input) input.value = utterance; + const kind = taskKind(utterance, result, String(task.source || "")); + if ($("#v2TaskKind")) $("#v2TaskKind").textContent = kind; + if ($("#v2TaskCommand")) $("#v2TaskCommand").textContent = utterance || "等待车机端或网页端选择预设模式、输入一句话指令"; + const normalizedStatus = String(task.status || "idle").toLowerCase(); + const statusMap = { + idle: ["等待任务", "idle"], + running: ["构建 / 执行中", "running"], + succeeded: ["执行完成", "succeeded"], + partially_succeeded: ["部分完成", "partial"], + needs_confirmation: ["等待确认", "partial"], + failed: ["执行失败", "failed"], + }; + const [label, state] = statusMap[normalizedStatus] || statusMap.idle; + const badge = $("#v2TaskState"); + if (badge) { + badge.textContent = label; + badge.dataset.state = state; + } + $$(".mode-chips [data-mode-command]").forEach((button) => { + const active = Boolean(utterance) && ( + utterance === button.dataset.modeCommand + || utterance.includes(button.textContent.trim()) + ); + button.classList.toggle("v2-sync-active", active); + }); + renderTaskTimeline(task); + } + + function applyDisplaySnapshot(snapshot) { + const health = snapshot?.extension_health || {}; + const physicallyConnected = health.transport !== "simulation" + && Boolean(health.connected || health.peer_connected); + const synchronizedCatalog = Array.isArray(snapshot?.extension?.catalog) + ? snapshot.extension.catalog + : []; + const connected = physicallyConnected || synchronizedCatalog.length > 0; + const listening = Boolean(health.listening); + const usbState = $("#v2UsbState"); + if (usbState) { + const usbLabel = $("span", usbState); + if (usbLabel) usbLabel.textContent = physicallyConnected + ? "USB 外设已接入" + : synchronizedCatalog.length + ? `${new Set(synchronizedCatalog.map((item) => item.device_id)).size} 个外设已同步` + : listening ? "等待 USB 外设" : "扩展链路检查中"; + usbState.dataset.state = connected ? "online" : listening ? "listening" : "offline"; + } + if ($("#v2SyncTransport")) { + $("#v2SyncTransport").textContent = `${String(health.transport || "GSCU").toUpperCase()} · ${health.peer || health.listen || "等待连接"}`; + } + const vehicleOnline = health.vehicle?.connected !== false; + const vehicleBadge = $("#v2HeadUnitState"); + if (vehicleBadge) { + vehicleBadge.dataset.state = vehicleOnline ? "online" : "offline"; + $("span", vehicleBadge).textContent = vehicleOnline ? "车机链路在线" : "车机链路离线"; + } + const revision = Number(snapshot?.revision ?? -1); + if (revision !== displaySync.revision) { + displaySync.revision = revision; + const task = snapshot?.task || {}; + setTaskPresentation(task); + const sourceLabel = task.source === "web_console" ? "网页端" : "车机端"; + if (task.utterance) { + appendSyncLog({ + key: `task:${revision}:${task.status}`, + category: "task", + title: `${sourceLabel}${task.status === "running" ? "下发编排任务" : "任务状态已同步"}`, + detail: `${task.utterance} · ${task.status || "idle"}`, + status: ["succeeded", "partially_succeeded"].includes(task.status) ? "success" : task.status === "failed" ? "error" : "info", + }); + } + const result = task.result; + const requestId = result?.request_id || null; + if (result && requestId !== displaySync.requestId) { + displaySync.requestId = requestId; + window.CognitiveAgentConsole?.applySyncedResult?.(result, { + utterance: task.utterance || "", + }); + } + } + const extensionFingerprint = synchronizedCatalog + .map((item) => `${item.device_id || "external"}:${item.action || item.name || "capability"}`) + .sort() + .join("|"); + if (extensionFingerprint && extensionFingerprint !== displaySync.extensionFingerprint) { + displaySync.extensionFingerprint = extensionFingerprint; + appendSyncLog({ + key: `extension:${extensionFingerprint}`, + category: "extension", + title: "外设能力目录已同步", + detail: `${new Set(synchronizedCatalog.map((item) => item.device_id || "external")).size} 个外设 · ${synchronizedCatalog.length} 项能力`, + status: "success", + }); + } + window.dispatchEvent(new CustomEvent("cognitive-agent:display-sync", { detail: snapshot })); + } + + async function pollVehicleDisplaySync() { + try { + const response = await fetch("/api/vehicle-display-sync", { + credentials: "same-origin", + cache: "no-store", + headers: { Accept: "application/json" }, + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + applyDisplaySnapshot(await response.json()); + $("#v2MirrorState")?.setAttribute("data-state", "online"); + if ($("#v2MirrorState span")) $("#v2MirrorState span").textContent = "同步正常"; + appendSyncLog({ key: "sync:online", category: "sync", title: "网页同步链路已建立", detail: "车机任务与设备状态每 2 秒同步", status: "success" }); + } catch (_error) { + console.warn("[vehicle-display-sync]", _error); + $("#v2MirrorState")?.setAttribute("data-state", "offline"); + if ($("#v2MirrorState span")) $("#v2MirrorState span").textContent = "等待同步服务"; + } + } + + function enableRemoteOrchestration() { + const form = $("#requestForm"); + const input = $("#utterance"); + if (input) { + input.readOnly = false; + input.removeAttribute("aria-readonly"); + input.setAttribute("aria-label", "输入一句话远程编排车端功能"); + input.placeholder = "例如:副驾调到舒适姿态,空调 24℃,氛围灯改成暖橙色"; + } + form?.addEventListener("submit", () => { + const utterance = input?.value.trim(); + if (utterance) appendSyncLog({ + category: "task", + title: "网页端发送编排指令", + detail: utterance, + status: "info", + }); + }); + $$("[data-mode-command]").forEach((button) => { + button.removeAttribute("aria-disabled"); + button.title = "点击后由网页端发送至车机执行"; + }); + } + + function buildSyncControlLayer() { + document.body.classList.add("v2-passive-display", "v2-interactive-sync"); + document.body.dataset.module = "self-orchestration"; + enableRemoteOrchestration(); + + const sidebar = $(".v2-sidebar"); + const sidebarFooter = $(".v2-sidebar-footer", sidebar); + const syncSidebar = make("section", "v2-sync-sidebar", ` +
    REMOTE CLIENT

    511工程-智能座舱

    网页可远程编排,车机任务、设备反馈与 USB 外设能力保持同步。

    + +
    +
    RUNTIME / SYNC

    运行日志 / 同步记录

    +
      +
      +
      扩展链路GSCU · 等待连接
      `); + if (sidebar && sidebarFooter) sidebar.insertBefore(syncSidebar, sidebarFooter); + + const naturalPanel = $("#v2NaturalPanel"); + const taskOverview = make("section", "v2-task-overview", ` +
      当前车机任务等待车机端或网页端选择预设模式、输入一句话指令
      + 等待任务 +
      01等待车机或网页端下发编排任务
      `); + naturalPanel?.append(taskOverview); + + const jointShell = $(".joint-twin-shell"); + const cabinBand = $(".cabin-band", jointShell); + if (jointShell && cabinBand) { + const rightRail = make("aside", "v2-unified-right-rail", ` +
      +
      LIVE VEHICLE DEVICES

      车端设备状态

      实时反馈
      +
      +
      +
      `); + jointShell.insertBefore(rightRail, cabinBand); + const panelControls = make("div", "v2-panel-visibility-controls", ` + + `); + $(".twin-toolbar", jointShell)?.prepend(panelControls); + buildTwinDeviceInteractions(); + cabinBand.classList.add("v2-source-state-only"); + new MutationObserver(scheduleSyncedDeviceRender).observe(cabinBand, { + attributes: true, + childList: true, + characterData: true, + subtree: true, + }); + const stateBand = $(".state-band"); + if (stateBand) new MutationObserver(scheduleSyncedDeviceRender).observe(stateBand, { + attributes: true, + childList: true, + characterData: true, + subtree: true, + }); + } + setSidePanelVisibility("devices", panelVisible("devices")); + setSidePanelVisibility("extensions", panelVisible("extensions")); + document.addEventListener("click", (event) => { + const toggle = event.target.closest("[data-panel-toggle], [data-panel-close]"); + if (toggle) { + const key = toggle.dataset.panelToggle || toggle.dataset.panelClose; + setSidePanelVisibility(key, !panelVisible(key)); + } + }); + $("#v2DeviceSyncGrid")?.addEventListener("click", (event) => { + const card = event.target.closest("[data-device]"); + if (!card) return; + presentTwinDevice(card.dataset.device, { pinned: true }); + }); + $("#v2LogFilter")?.addEventListener("change", renderSyncLogs); + window.addEventListener("cognitive-agent:result", (event) => { + const result = event.detail || {}; + appendSyncLog({ + key: result.request_id ? `result:${result.request_id}` : "", + category: "task", + title: ["succeeded", "partially_succeeded"].includes(result.status) ? "编排任务执行完成" : "编排任务返回结果", + detail: `${result.summary || result.message || "执行反馈已同步"} · ${result.status || "unknown"}`, + status: ["succeeded", "partially_succeeded"].includes(result.status) ? "success" : result.status === "failed" ? "error" : "info", + }); + }); + window.addEventListener("cognitive-agent:request-complete", (event) => { + if (!event.detail?.error) return; + appendSyncLog({ category: "task", title: "编排任务执行失败", detail: event.detail.error.message || "请求失败", status: "error" }); + }); + window.addEventListener("cognitive-agent:connection", (event) => { + const online = event.detail?.status === "online"; + appendSyncLog({ + key: `connection:${event.detail?.status}`, + category: "sync", + title: online ? "车机服务连接正常" : "车机服务连接异常", + detail: online ? "远程控制与状态同步通道可用" : String(event.detail?.status || "offline"), + status: online ? "success" : "error", + }); + }); + renderSyncedDevices(); + setTaskPresentation({ status: "idle" }); + appendSyncLog({ key: "client:ready", category: "sync", title: "同步控制台已就绪", detail: "正在连接车机任务与设备状态服务", status: "info" }); + pollVehicleDisplaySync(); + displaySync.pollTimer = window.setInterval(pollVehicleDisplaySync, 2000); + const updateClock = () => { + if ($("#v2SyncClock")) $("#v2SyncClock").textContent = new Intl.DateTimeFormat("zh-CN", { + hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, + }).format(new Date()); + }; + updateClock(); + window.setInterval(updateClock, 1000); + } + function setPage(pageIndex) { - const maxPage = ui.role === "admin" ? pageDefinitions.length - 1 : 0; - ui.activePage = Math.max(0, Math.min(Number(pageIndex) || 0, maxPage)); + ui.activePage = 0; const definition = pageDefinitions[ui.activePage]; $(".v2-output-shell")?.classList.toggle("v2-twin-active", definition.index === 0); $$(".v2-output-page").forEach((page) => { @@ -654,128 +1113,31 @@ } } - function syncSidebarControlForModule(evolutionView = window.CognitiveAgentSelfEvolution?.getView?.()) { - const evolutionMode = ui.activeModule === "self-evolution"; - const caption = $(".v2-control-section > .v2-field-caption"); - if (caption) caption.textContent = evolutionMode ? "进化视图" : "控制方式"; - const definitions = evolutionMode - ? [ - { label: "座椅称重进化", icon: "scale", active: evolutionView !== "system" }, - { label: "系统能力日志", icon: "scroll-text", active: evolutionView === "system" }, - ] - : [ - { label: "自然语言控制", icon: "message-square-text", active: ui.controlMode === "natural" }, - { label: "手势控制", icon: "scan-face", active: ui.controlMode === "gesture" }, - ]; - $$('[data-v2-control]').forEach((button, index) => { - const definition = definitions[index]; - if (!definition) return; - const label = $("span", button); - const icon = $("svg, i", button); - if (label) label.textContent = definition.label; - if (icon) icon.setAttribute("data-lucide", definition.icon); - button.classList.toggle("active", definition.active); - button.setAttribute("aria-pressed", String(definition.active)); - }); - const switcher = $(".v2-control-switch"); - switcher?.setAttribute("aria-label", evolutionMode ? "自进化视图" : "控制方式"); - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - } - function setModule(module, { persist = true } = {}) { - if (["self-calibration", "self-repair"].includes(module) && ui.role !== "admin") { - setRole("admin", { allowModuleTransition: true }); - } - const allowed = new Set(["self-orchestration", "self-extension", "self-evolution"]); - if (ui.role === "admin") { - allowed.add("self-calibration"); - allowed.add("self-repair"); - } + const allowed = new Set(["self-orchestration", "self-extension"]); ui.activeModule = allowed.has(module) ? module : "self-orchestration"; - if (ui.activeModule === "self-extension" && ui.role !== "user") { - setRole("user"); - } if (persist) { sessionStorage.setItem("cognitive-agent.active-module", ui.activeModule); } document.body.dataset.module = ui.activeModule; - const roleSelect = $("#v2RoleSelect"); - if (roleSelect) { - roleSelect.disabled = ui.activeModule === "self-repair"; - dropdownControls.get(roleSelect)?.sync(); - } $$('.v2-module-tab').forEach((button) => { const active = button.dataset.module === ui.activeModule; button.classList.toggle("active", active); button.setAttribute("aria-selected", String(active)); button.tabIndex = active ? 0 : -1; }); - if (["self-extension", "self-calibration", "self-repair", "self-evolution"].includes(ui.activeModule)) { + if (ui.activeModule === "self-extension") { const drawer = $("#gestureDrawer"); if (drawer?.classList.contains("open")) $("#gestureCloseButton")?.click(); } else { setControlMode(ui.controlMode, { triggerGesture: false }); } - syncSidebarControlForModule(); window.dispatchEvent(new CustomEvent("cognitive-agent:module-change", { detail: { module: ui.activeModule }, })); window.setTimeout(() => window.dispatchEvent(new Event("resize")), 120); } - function setRole(role, { allowModuleTransition = false } = {}) { - if (ui.activeModule === "self-extension" && role !== "user" && !allowModuleTransition) { - role = "user"; - } - if (ui.activeModule === "self-repair" && role !== "admin") { - const roleSelect = $("#v2RoleSelect"); - if (roleSelect) { - roleSelect.value = "admin"; - dropdownControls.get(roleSelect)?.sync(); - } - return; - } - ui.role = role === "admin" ? "admin" : "user"; - sessionStorage.setItem("cognitive-agent.demo-role", ui.role); - document.body.dataset.demoRole = ui.role; - window.dispatchEvent(new CustomEvent("cognitive-agent:demo-role-change", { - detail: { role: ui.role }, - })); - $("#v2RoleSelect").value = ui.role; - dropdownControls.get($("#v2RoleSelect"))?.sync(); - $("#v2PageRail").hidden = ui.role !== "admin"; - const calibrationTab = $('.v2-module-tab[data-module="self-calibration"]'); - if (calibrationTab) { - calibrationTab.disabled = false; - calibrationTab.setAttribute("aria-disabled", "false"); - calibrationTab.title = ui.role === "admin" - ? "" - : "进入自标定时将自动切换为 admin"; - } - const repairTab = $('.v2-module-tab[data-module="self-repair"]'); - if (repairTab) { - repairTab.hidden = false; - repairTab.disabled = false; - repairTab.setAttribute("aria-disabled", "false"); - repairTab.title = ui.role === "admin" - ? "" - : "进入自修复时将自动切换为 admin"; - } - if (ui.role !== "admin") { - if (["self-calibration", "self-repair"].includes(ui.activeModule)) { - setModule("self-orchestration"); - } - setPage(0); - requestUserSafeExecutionMode(); - } else { - const note = $("#v2ExecutionNote"); - if (note) note.textContent = "管理员可切换虚拟 CAN、模拟台架与真实台架"; - const runButton = $("#runButton"); - if (runButton && !runButton.classList.contains("loading")) runButton.disabled = false; - syncExecutionSelector(); - } - } - function setSidebarCollapsed(collapsed) { ui.sidebarCollapsed = Boolean(collapsed); sessionStorage.setItem( @@ -804,7 +1166,7 @@ const runButton = $("#runButton"); if (!dryRunButton) return; if (!dryRunButton.classList.contains("active")) dryRunButton.click(); - if (note) note.textContent = "测试用户使用虚拟 CAN;真实台架仅由管理员显式启用"; + if (note) note.textContent = "user 固定使用虚拟 CAN 安全执行环境"; if (userTarget) userTarget.dataset.state = "ready"; if (userTargetText) userTargetText.textContent = "执行目标:虚拟 CAN"; if (runButton && !runButton.classList.contains("loading")) runButton.disabled = false; @@ -847,7 +1209,7 @@ $(".v2-sidebar-footer")?.classList.toggle("offline", !online); } syncExecutionSelector(); - if (ui.role === "user") requestUserSafeExecutionMode(); + requestUserSafeExecutionMode(); } function setVehicleLinkState(connected) { @@ -877,21 +1239,11 @@ } function bindEvents() { - $("#v2RoleSelect")?.addEventListener("change", (event) => setRole(event.target.value)); $$('[data-v2-control]').forEach((button) => { button.addEventListener("click", () => { - if (ui.activeModule === "self-evolution") { - const view = button.dataset.v2Control === "gesture" ? "system" : "weighing"; - window.CognitiveAgentSelfEvolution?.setView?.(view); - syncSidebarControlForModule(view); - return; - } setControlMode(button.dataset.v2Control); }); }); - window.addEventListener("cognitive-agent:evolution-view-change", (event) => { - if (ui.activeModule === "self-evolution") syncSidebarControlForModule(event.detail?.view); - }); $$('.v2-module-tab').forEach((button) => { button.addEventListener("click", () => { if (!button.disabled) setModule(button.dataset.module); @@ -932,6 +1284,16 @@ () => requestAnimationFrame(updateModeEdgeHints), { passive: true }, ); + modeChips?.addEventListener("wheel", (event) => { + if (modeChips.scrollWidth <= modeChips.clientWidth + 2) return; + const distance = Math.abs(event.deltaX) > Math.abs(event.deltaY) + ? event.deltaX + : event.deltaY; + if (!distance) return; + event.preventDefault(); + modeChips.scrollBy({ left: distance, behavior: "smooth" }); + window.requestAnimationFrame(updateModeEdgeHints); + }, { passive: false }); if (modeChips) { new MutationObserver(() => requestAnimationFrame(updateModeEdgeHints)) .observe(modeChips, { childList: true }); @@ -990,16 +1352,14 @@ gestureDrawer, ); buildModuleSwitcher(mainPanel); - window.CognitiveAgentSelfEvolution?.mount(mainPanel); - $(".pipeline", mainPanel)?.classList.add("v2-legacy-hidden"); $(".topbar")?.classList.add("v2-legacy-hidden"); $(".gesture-backdrop")?.classList.add("v2-legacy-hidden"); buildOutput(mainPanel); + buildSyncControlLayer(); bindEvents(); setControlMode(ui.controlMode, { triggerGesture: false }); setModule(ui.activeModule, { persist: false }); - setRole(ui.role); setSidebarCollapsed(ui.sidebarCollapsed); setPage(0); syncRuntimePresentation(); @@ -1014,7 +1374,7 @@ window.CognitiveAgentConsoleV2 = { enhanceSelect, getModule: () => ui.activeModule, - getRole: () => ui.role, + getRole: () => "user", setModule, }; diff --git a/apps/web-console/gesture-control.js b/apps/web-console/gesture-control.js index c092135..73d3de3 100755 --- a/apps/web-console/gesture-control.js +++ b/apps/web-console/gesture-control.js @@ -557,7 +557,6 @@ async function loadGestureRuntime() { state.runtime = await response.json(); state.engine = new GestureEngine(state.runtime.safety, executeGestureAction); renderMappingGrid(); - renderGestureDebugOptions(); if (!state.runtime.model_available) throw new Error("内置手势模型不可用,请检查工程资源"); } @@ -658,99 +657,6 @@ function renderMappingGrid() { select.innerHTML = Object.entries(ACTIONS).map(([value, item]) => ``).join(""); } -function renderGestureDebugOptions() { - const select = $("#gestureDebugSelect"); - if (!select || !state.runtime) return; - const tokens = [...new Set([ - "OPEN_PALM", - "CLOSED_FIST", - ...Object.keys(state.runtime.actions || {}), - ])]; - select.innerHTML = tokens.map((token) => { - const action = mappingForToken(token); - const actionLabel = action ? ACTIONS[action]?.label || action : token === "OPEN_PALM" ? "激活控制" : "停止当前动作"; - return ``; - }).join(""); -} - -function setGestureDebugOpen(open) { - const panel = $("#gestureDebugPanel"); - const button = $("#gestureArmButton"); - if (!panel || !button) return; - const allowed = document.body.dataset.demoRole === "admin"; - const nextOpen = allowed && open; - panel.hidden = !nextOpen; - button.classList.toggle("active", nextOpen); - button.setAttribute("aria-expanded", String(nextOpen)); -} - -function toggleGestureDebug() { - const panel = $("#gestureDebugPanel"); - setGestureDebugOpen(panel?.hidden ?? true); -} - -function syncGestureDebugRole(role = document.body.dataset.demoRole) { - const button = $("#gestureArmButton"); - if (!button) return; - const isAdmin = role === "admin"; - if (!isAdmin) setGestureDebugOpen(false); - button.disabled = !isAdmin; - button.classList.toggle("v2-decorative-control", !isAdmin); - if (isAdmin) { - button.removeAttribute("aria-hidden"); - button.removeAttribute("tabindex"); - button.setAttribute("aria-controls", "gestureDebugPanel"); - button.setAttribute("aria-expanded", String(!$("#gestureDebugPanel")?.hidden)); - button.setAttribute("aria-label", "手势调试"); - button.setAttribute("title", "手势调试"); - } else { - button.setAttribute("aria-hidden", "true"); - button.setAttribute("tabindex", "-1"); - button.removeAttribute("aria-controls"); - button.removeAttribute("aria-expanded"); - button.removeAttribute("aria-label"); - button.removeAttribute("title"); - } -} - -function sendSimulatedGesture() { - if (document.body.dataset.demoRole !== "admin") { - setGestureDebugOpen(false); - notify("仅管理员可发送模拟手势"); - return; - } - const token = $("#gestureDebugSelect")?.value; - if (!token || !state.engine) { - notify("手势调试能力尚未就绪"); - return; - } - const tokenName = TOKEN_NAMES[token] || token; - $("#gestureDetected").textContent = `模拟 · ${tokenName}`; - if (token === "OPEN_PALM") { - state.engine.setArmed(true); - $("#gestureExpected").textContent = "激活控制"; - notify("已发送模拟张掌手势"); - return; - } - if (token === "CLOSED_FIST") { - state.engine.stopMotion("管理员模拟握拳 · 已停止当前动作"); - $("#gestureExpected").textContent = "停止当前动作"; - notify("已发送模拟握拳手势"); - return; - } - const action = mappingForToken(token); - if (!action || !ACTIONS[action]) { - $("#gestureExpected").textContent = "未绑定动作"; - notify("该模拟手势尚未绑定动作"); - return; - } - state.lastRecognizedToken = token; - $("#gestureExpected").textContent = ACTIONS[action].label; - $("#gestureSafetyText").textContent = `管理员模拟手势:${tokenName}`; - executeGestureAction(action); - notify(`已发送模拟手势:${tokenName}`); -} - function updateCustomizeToken() { const token = state.lastRecognizedToken; $("#gestureCustomizeToken").textContent = token ? TOKEN_NAMES[token] || token : "请先摆出手势"; @@ -811,27 +717,17 @@ document.addEventListener("DOMContentLoaded", async () => { $("#gestureCloseButton")?.addEventListener("click", closeDrawer); $("#gestureBackdrop")?.addEventListener("click", closeDrawer); $("#gestureStartButton")?.addEventListener("click", toggleCamera); - $("#gestureArmButton")?.addEventListener("click", toggleGestureDebug); $("#gestureStopButton")?.addEventListener("click", () => state.engine?.setArmed(false)); - $("#gestureDebugSend")?.addEventListener("click", sendSimulatedGesture); $("#gestureCustomizeButton")?.addEventListener("click", toggleCustomize); $("#gestureBindButton")?.addEventListener("click", bindCurrentGesture); $("#gestureResetMapping")?.addEventListener("click", resetMapping); document.addEventListener("keydown", (event) => { if (event.key !== "Escape") return; - if (!$("#gestureDebugPanel")?.hidden) { - setGestureDebugOpen(false); - return; - } if ($("#gestureDrawer")?.classList.contains("open")) closeDrawer(); }); - window.addEventListener("cognitive-agent:demo-role-change", (event) => { - syncGestureDebugRole(event.detail?.role); - }); document.addEventListener("visibilitychange", () => { if (document.hidden && state.stream) stopCamera(); }); window.addEventListener("beforeunload", stopCamera); navigator.mediaDevices?.addEventListener?.("devicechange", handleCameraDeviceChange); - syncGestureDebugRole(); let runtimeError = null; try { await loadGestureRuntime(); diff --git a/apps/web-console/index.html b/apps/web-console/index.html index 60fe8e4..ccbbb49 100755 --- a/apps/web-console/index.html +++ b/apps/web-console/index.html @@ -8,27 +8,20 @@ - 智舱随行 · 整车智能控制台 + 511工程-智能座舱 - - - - - + + - - - - - - - - - + + + + +
      @@ -607,15 +600,7 @@
      - -
      diff --git a/apps/web-console/pwa.js b/apps/web-console/pwa.js index a1cb525..f9bb641 100644 --- a/apps/web-console/pwa.js +++ b/apps/web-console/pwa.js @@ -17,7 +17,9 @@ try { const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/", + updateViaCache: "none", }); + await registration.update(); if (registration.waiting) showUpdate(registration); registration.addEventListener("updatefound", () => { const worker = registration.installing; diff --git a/apps/web-console/self-calibration.css b/apps/web-console/self-calibration.css deleted file mode 100644 index d86e0b9..0000000 --- a/apps/web-console/self-calibration.css +++ /dev/null @@ -1,1672 +0,0 @@ -/* Self-calibration workspace ---------------------------------------------- */ - -.console-v2[data-module="self-calibration"] { - --v2-accent: #4f73b2; - --v2-accent-strong: #1e386b; - --v2-accent-soft: #e7ecf8; - --v2-sidebar: #dae3f5; - --v2-sidebar-deep: #b6c7ea; - --v2-line: rgba(30, 56, 107, 0.14); -} - -.console-v2 .v2-calibration-sidebar, -.console-v2 .v2-calibration-footer, -.console-v2 .v2-self-calibration { - display: none; -} - -.console-v2[data-module="self-calibration"] .v2-control-section, -.console-v2[data-module="self-calibration"] .v2-config-section, -.console-v2[data-module="self-calibration"] .v2-sidebar > .v2-sidebar-footer:not(.v2-calibration-footer), -.console-v2[data-module="self-calibration"] .v2-operation-shell, -.console-v2[data-module="self-calibration"] .v2-output-shell { - display: none; -} - -.console-v2[data-module="self-calibration"] .v2-sidebar { - background: - radial-gradient(circle at 14% 3%, rgba(255, 255, 255, 0.84), transparent 24%), - linear-gradient(158deg, var(--v2-sidebar) 0%, #eef2fa 61%, var(--v2-sidebar-deep) 132%); -} - -.console-v2[data-module="self-calibration"] .v2-role-select > .v2-dropdown-trigger { - max-width: none; - gap: 5px; -} - -.console-v2[data-module="self-calibration"] .v2-calibration-sidebar { - min-height: 0; - display: flex; - flex: 1; - flex-direction: column; - margin-top: clamp(22px, 3.4vh, 40px); -} - -.console-v2[data-module="self-calibration"] .v2-calibration-footer { - display: grid; -} - -.console-v2.v2-sidebar-collapsed[data-module="self-calibration"] .v2-calibration-sidebar, -.console-v2.v2-sidebar-collapsed[data-module="self-calibration"] .v2-calibration-footer { - display: none; -} - -.console-v2[data-module="self-calibration"] .main-panel { - grid-template-rows: 36px minmax(0, 1fr); -} - -.console-v2[data-module="self-calibration"] .v2-self-calibration { - min-width: 0; - min-height: 0; - display: grid; - grid-row: 2; - grid-template-rows: auto minmax(0, 1fr); - gap: 15px; - padding: var(--v2-module-title-block) 0 0; - overflow: hidden; -} - -.v2-calibration-sidebar > .v2-field-caption { - display: block; - margin: 0 0 8px; - color: #617193; - font-size: 13px; - font-weight: 750; -} - -.v2-calibration-mode-switch { - display: grid; - gap: 7px; -} - -.v2-calibration-mode-switch button { - min-height: var(--v2-sidebar-item-height); - display: grid; - grid-template-columns: 30px minmax(0, 1fr); - align-items: center; - gap: 8px; - padding: 0 15px; - color: #637677; - background: transparent; - border: 1px solid transparent; - border-radius: 13px; - font-size: 15px; - font-weight: 700; - text-align: left; - cursor: pointer; - transition: 160ms ease; -} - -.v2-calibration-mode-switch button svg { - width: 19px; - height: 19px; - justify-self: center; -} - -.v2-calibration-mode-switch button:hover { - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 34%, white); - border-color: color-mix(in srgb, var(--v2-accent) 10%, white); -} - -.v2-calibration-mode-switch button.active { - color: #111f20; - background: rgba(255, 255, 255, 0.94); - border-color: color-mix(in srgb, var(--v2-accent) 18%, white); - box-shadow: 0 10px 28px color-mix(in srgb, var(--v2-accent) 10%, transparent); -} - -.v2-calibration-mode-switch button.active svg { - color: var(--v2-accent); -} - -.v2-calibration-config-stack { - display: grid; - gap: 8px; - padding-left: 9px; - border-left: 1px solid color-mix(in srgb, var(--v2-accent) 14%, transparent); -} - -.v2-calibration-config-card { - min-width: 0; - min-height: var(--v2-sidebar-card-height); - display: grid; - grid-template-columns: 28px minmax(0, 1fr) auto; - align-items: center; - gap: 8px; - padding: 6px 8px; - color: #314565; - background: rgba(255, 255, 255, 0.72); - border: 1px solid rgba(255, 255, 255, 0.78); - border-radius: var(--v2-sidebar-card-radius); -} - -.v2-calibration-config-card > svg { - width: 17px; - height: 17px; - justify-self: center; - color: var(--v2-accent); -} - -.v2-calibration-config-card > div { - min-width: 0; - display: grid; -} - -.v2-calibration-config-card small { - color: #7786a2; - font-size: 8px; - font-weight: 700; -} - -.v2-calibration-config-card strong { - overflow: hidden; - color: #1e386b; - margin-top: 2px; - font-size: 11px; - font-weight: 850; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-config-card > span { - padding: 3px 5px; - color: #345f9d; - background: rgba(255, 255, 255, 0.68); - border-radius: 5px; - font: 800 7px "SFMono-Regular", Consolas, monospace; -} - -.v2-calibration-config-card[data-state="online"] > span { - color: #17745d; -} - -.v2-calibration-config-card[data-state="error"] > span { - color: #b43d38; -} - -.v2-calibration-config-card .v2-config-card-select { - width: 100%; -} - -.v2-calibration-config-card .v2-dropdown-trigger { - width: 100%; - height: 18px; - color: #1e386b; - font-size: 11px; - font-weight: 850; - text-align: left; -} - -.v2-calibration-target-note { - min-height: 28px; - margin: 7px 4px 8px; - color: #6f7d97; - font-size: 9px; - line-height: 1.45; -} - -.v2-calibration-connect, -.v2-calibration-settings-link { - width: 100%; - min-height: 42px; - display: grid; - grid-template-columns: 20px minmax(0, 1fr); - align-items: center; - gap: 9px; - padding: 9px 12px; - border-radius: 12px; - font-size: 11px; - font-weight: 850; - cursor: pointer; -} - -.v2-calibration-connect { - color: white; - background: linear-gradient(135deg, #5d82c2, #315eaa); - border: 0; - box-shadow: 0 10px 22px rgba(35, 71, 133, 0.2); -} - -.v2-calibration-connect svg, -.v2-calibration-settings-link svg { - width: 16px; - height: 16px; -} - -.v2-calibration-settings-link { - grid-template-columns: 20px minmax(0, 1fr) 16px; - margin-top: auto; - color: #536684; - background: rgba(255, 255, 255, 0.35); - border: 1px solid rgba(49, 94, 170, 0.11); - text-align: left; -} - -.v2-calibration-settings-link.active, -.v2-calibration-settings-link:hover { - color: #1e386b; - background: rgba(255, 255, 255, 0.72); -} - -.v2-calibration-footer > button { - color: #315eaa !important; - background: rgba(255, 255, 255, 0.72) !important; -} - -.v2-calibration-heading { - min-width: 0; - display: flex; - align-items: center; - justify-content: space-between; - gap: 18px; - margin-inline: var(--v2-module-title-inline); -} - -.v2-calibration-heading > div:first-child { - min-width: 0; -} - -.v2-calibration-heading .section-kicker, -.v2-calibration-panel .section-kicker, -.v2-calibration-axis-section .section-kicker { - display: block; - color: #5b77aa; - font: 800 8px "SFMono-Regular", Consolas, monospace; - letter-spacing: 0.16em; -} - -.v2-calibration-heading h1 { - margin: 4px 0 2px; - color: #1f2d30; - font-size: clamp(22px, 2vw, 31px); - line-height: 1; - letter-spacing: -0.045em; -} - -.v2-calibration-heading p { - margin: 0; - color: #839092; - font-size: 11px; -} - -.v2-calibration-statuses { - display: flex; - align-items: center; - gap: 8px; -} - -.v2-calibration-statuses > div { - min-width: 112px; - min-height: 43px; - display: grid; - grid-template-columns: 9px minmax(0, 1fr); - align-items: center; - gap: 8px; - padding: 7px 10px; - background: rgba(255, 255, 255, 0.82); - border: 1px solid rgba(42, 72, 74, 0.08); - border-radius: 12px; - box-shadow: 0 8px 20px rgba(37, 70, 72, 0.06); -} - -.v2-calibration-statuses > div > i { - width: 7px; - height: 7px; - border-radius: 50%; - background: #a9b3b3; - box-shadow: 0 0 0 4px rgba(126, 145, 145, 0.1); -} - -.v2-calibration-statuses > div > i.online { - background: #3ea884; - box-shadow: 0 0 0 4px rgba(62, 168, 132, 0.12); -} - -.v2-calibration-statuses > div > i.wait { - background: #d9a34c; - box-shadow: 0 0 0 4px rgba(217, 163, 76, 0.12); -} - -.v2-calibration-statuses > div > i.error { - background: #d95d55; - box-shadow: 0 0 0 4px rgba(217, 93, 85, 0.12); -} - -.v2-calibration-statuses span { - min-width: 0; - display: grid; -} - -.v2-calibration-statuses small { - color: #9aa4a5; - font: 700 7px "SFMono-Regular", Consolas, monospace; -} - -.v2-calibration-statuses strong { - overflow: hidden; - color: #425356; - font-size: 10px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-view { - min-width: 0; - min-height: 0; - padding: 1px 3px 22px 1px; - overflow: auto; - scrollbar-color: rgba(49, 94, 170, 0.3) transparent; - scrollbar-width: thin; -} - -.v2-calibration-view[hidden] { - display: none !important; -} - -.v2-calibration-panel, -.v2-calibration-axis-card { - background: - linear-gradient(152deg, rgba(255, 255, 255, 0.98), rgba(250, 252, 251, 0.91)); - border: 1px solid rgba(48, 78, 80, 0.08); - border-radius: 18px; - box-shadow: 0 13px 34px rgba(39, 70, 72, 0.07); -} - -.v2-calibration-panel > header, -.v2-calibration-axis-section > header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 12px; -} - -.v2-calibration-panel h2, -.v2-calibration-axis-section h2 { - margin: 3px 0 0; - color: #2c3d40; - font-size: clamp(15px, 1.25vw, 20px); - letter-spacing: -0.03em; -} - -.v2-calibration-hero-grid { - min-width: 0; - display: grid; - grid-template-columns: minmax(0, 1.72fr) minmax(270px, 0.72fr); - gap: 14px; -} - -.v2-calibration-stage { - min-height: clamp(390px, 51vh, 565px); - display: grid; - grid-template-rows: auto minmax(250px, 1fr) auto; - padding: 16px; -} - -.v2-calibration-badge { - padding: 5px 8px; - color: #18745e; - background: #e1f5ee; - border-radius: 7px; - font-size: 9px; - font-weight: 850; -} - -.v2-calibration-badge.wait { - color: #98713a; - background: #fff4df; -} - -.v2-calibration-badge.error { - color: #a84039; - background: #fce7e5; -} - -.v2-calibration-seat-scene { - min-height: 0; - position: relative; - overflow: hidden; - background: - radial-gradient(circle at 50% 44%, rgba(218, 227, 245, 0.95), transparent 44%), - linear-gradient(180deg, #fafbfe, #edf2fa); - border: 1px solid rgba(49, 83, 84, 0.07); - border-radius: 15px; -} - -.v2-calibration-floor-grid { - position: absolute; - inset: 58% -20% -18%; - z-index: 0; - opacity: 0.34; - background-image: - linear-gradient(rgba(68, 99, 151, 0.17) 1px, transparent 1px), - linear-gradient(90deg, rgba(68, 99, 151, 0.17) 1px, transparent 1px); - background-size: 34px 34px; - transform: perspective(360px) rotateX(58deg); - transform-origin: center top; -} - -.v2-calibration-seat-scene .seat-model-host { - position: absolute; - inset: 0; - z-index: 1; - overflow: hidden; -} - -.v2-calibration-seat-scene .calibration-cartoon-viewer { - cursor: grab; - touch-action: none; - user-select: none; -} - -.v2-calibration-seat-scene .calibration-cartoon-viewer.dragging { - cursor: grabbing; -} - -.v2-calibration-seat-scene .calibration-cartoon-viewer.axis-hover { - cursor: ns-resize; -} - -.v2-calibration-seat-scene .calibration-cartoon-viewer.axis-hover[data-hover-axis="0"] { - cursor: ew-resize; -} - -.v2-calibration-seat-scene .calibration-cartoon-viewer.axis-dragging { - cursor: grabbing; -} - -.v2-calibration-seat-scene .seat-model-host canvas { - width: 100%; - height: 100%; - display: block; - outline: 0; - pointer-events: none; - touch-action: none; -} - -.v2-calibration-seat-scene .v2-repair-seat-fallback { - inset: 4px 18px 18px; - transform: scale(0.82); -} - -.v2-calibration-seat-scene .repair-css-halo { - bottom: 10px; -} - -.v2-calibration-seat-scene .model-loading { - position: absolute; - inset: 0; - display: grid; - place-content: center; - justify-items: center; - gap: 8px; - color: #6b7890; - background: radial-gradient(circle at 50% 48%, rgba(205, 217, 241, 0.72), transparent 52%); - transition: opacity 280ms ease, visibility 280ms ease; -} - -.v2-calibration-seat-scene .model-loading strong { - color: #344867; - font-size: 11px; -} - -.v2-calibration-seat-scene .model-loading small { - color: #8794aa; - font: 8px Consolas, monospace; - letter-spacing: 0.12em; -} - -.v2-calibration-seat-scene .model-loading.error strong { - color: #b5413a; -} - -.v2-calibration-seat-scene .model-spinner { - width: 27px; - height: 27px; - border: 2px solid rgba(79, 115, 178, 0.16); - border-top-color: var(--v2-accent); - border-radius: 50%; - animation: calibration-spin 0.8s linear infinite; -} - -@keyframes calibration-spin { - to { transform: rotate(360deg); } -} - -.v2-calibration-seat-scene .seat-model-host.is-ready .model-loading { - visibility: hidden; - opacity: 0; - pointer-events: none; -} - -.v2-calibration-seat-scene .orbit-hint { - position: absolute; - bottom: 10px; - left: 50%; - z-index: 4; - padding: 5px 9px; - color: #7a898b; - background: rgba(255, 255, 255, 0.74); - border: 1px solid rgba(57, 91, 92, 0.1); - border-radius: 999px; - font: 8px Consolas, monospace; - opacity: 0; - transform: translateX(-50%); - transition: opacity 180ms ease; - pointer-events: none; - white-space: nowrap; -} - -.v2-calibration-seat-scene .seat-model-host.is-ready:hover .orbit-hint { - opacity: 1; -} - -.v2-axis-tag { - position: absolute; - z-index: 4; - display: flex; - align-items: center; - gap: 5px; - padding: 5px 8px; - color: #6d7c7e; - background: rgba(255, 255, 255, 0.84); - border: 1px solid rgba(56, 92, 94, 0.1); - border-radius: 8px; - box-shadow: 0 7px 18px rgba(46, 78, 80, 0.07); - font-size: 8px; - cursor: not-allowed; - pointer-events: auto; - touch-action: none; - user-select: none; - backdrop-filter: blur(8px); - transform: translate3d(-1000px, -1000px, 0); - transition: opacity 120ms ease, border-color 120ms ease, box-shadow 120ms ease; - will-change: transform; -} - -.v2-axis-tag[data-control-enabled="true"] { - cursor: grab; -} - -.v2-axis-tag[data-control-enabled="true"].dragging { - cursor: grabbing; -} - -.v2-axis-tag:focus-visible { - outline: 2px solid rgba(49, 94, 170, 0.42); - outline-offset: 2px; -} - -.v2-axis-tag > i { - width: 5px; - height: 5px; - flex: 0 0 auto; - background: #5d82c2; - border: 1px solid rgba(255, 255, 255, 0.9); - border-radius: 50%; - box-shadow: 0 0 0 3px rgba(79, 115, 178, 0.13); -} - -.v2-axis-tag > span { - display: flex; - gap: 5px; - white-space: nowrap; -} - -.v2-axis-tag b { - color: #315eaa; -} - -.v2-axis-tag.active { - border-color: rgba(49, 94, 170, 0.42); - box-shadow: 0 7px 22px rgba(49, 94, 170, 0.18); -} - -.v2-axis-tag[data-hidden="true"] { - opacity: 0; -} - -.v2-calibration-label-lines { - position: absolute; - inset: 0; - z-index: 3; - width: 100%; - height: 100%; - overflow: visible; - pointer-events: none; -} - -.v2-calibration-label-lines line { - stroke: rgba(49, 94, 170, 0.42); - stroke-width: 1.15; - stroke-linecap: round; - stroke-dasharray: 2 3; - vector-effect: non-scaling-stroke; -} - -.v2-calibration-label-lines line[data-hidden="true"] { - opacity: 0; -} - -.v2-calibration-operation { - min-width: 0; - min-height: 44px; - display: grid; - grid-template-columns: 8px minmax(0, 1fr) auto; - align-items: center; - gap: 10px; - margin-top: 10px; - padding: 7px 10px; - background: #f6f9f8; - border-radius: 11px; -} - -.v2-calibration-operation > i { - width: 7px; - height: 7px; - border-radius: 50%; - background: var(--v2-accent); - box-shadow: 0 0 0 5px rgba(79, 115, 178, 0.12); -} - -.v2-calibration-operation > div { - min-width: 0; - display: grid; -} - -.v2-calibration-operation small { - color: #97a1a2; - font-size: 8px; -} - -.v2-calibration-operation strong { - overflow: hidden; - color: #46575a; - font-size: 10px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-operation > span { - color: #95a0a1; - font: 700 8px Consolas, monospace; -} - -.v2-calibration-operation > span b { - color: #315eaa; -} - -.v2-calibration-workflow { - min-height: 390px; - display: flex; - flex-direction: column; - padding: 17px; -} - -.v2-calibration-workflow > p { - margin: 13px 0 16px; - color: #849193; - font-size: 10px; - line-height: 1.55; -} - -.v2-calibration-flow { - display: grid; - gap: 0; -} - -.v2-calibration-flow > div { - min-height: 58px; - display: grid; - grid-template-columns: 35px minmax(0, 1fr); - align-items: center; - gap: 10px; - padding: 8px 9px; - color: #718083; - background: #f7f9f9; - border: 1px solid rgba(50, 80, 81, 0.06); - border-radius: 12px; - transition: 150ms ease; -} - -.v2-calibration-flow > div > span { - color: #9ca7a8; - font: 800 10px Consolas, monospace; -} - -.v2-calibration-flow > div > div { - display: grid; -} - -.v2-calibration-flow strong { - color: #526266; - font-size: 10px; -} - -.v2-calibration-flow small { - color: #9ba5a6; - font-size: 8px; -} - -.v2-calibration-flow > div.active { - background: #eef3fb; - border-color: rgba(49, 94, 170, 0.2); - box-shadow: inset 3px 0 var(--v2-accent); -} - -.v2-calibration-flow > div.active > span, -.v2-calibration-flow > div.active strong { - color: #315eaa; -} - -.v2-calibration-flow > div.done { - background: #edf7f3; -} - -.v2-calibration-flow > i { - width: 1px; - height: 10px; - margin-left: 26px; - background: rgba(85, 112, 113, 0.18); -} - -.v2-calibration-primary { - min-height: 42px; - display: inline-flex; - align-items: center; - justify-content: center; - gap: 9px; - padding: 9px 13px; - color: white; - background: linear-gradient(135deg, #5d82c2, #315eaa); - border: 0; - border-radius: 11px; - box-shadow: 0 10px 24px rgba(35, 71, 133, 0.2); - font-size: 10px; - font-weight: 850; - cursor: pointer; -} - -.v2-calibration-primary:disabled { - color: #9ba4a4; - background: #e9eeee; - box-shadow: none; - cursor: not-allowed; -} - -.v2-calibration-primary svg { - width: 15px; - height: 15px; -} - -.v2-calibration-workflow > .v2-calibration-primary { - width: 100%; - margin-top: auto; -} - -.v2-calibration-safety { - display: grid; - grid-template-columns: 24px minmax(0, 1fr); - align-items: center; - gap: 8px; - margin-top: 10px; - padding: 9px; - color: #55736d; - background: #eef7f4; - border-radius: 10px; -} - -.v2-calibration-safety svg { - width: 17px; - height: 17px; - justify-self: center; - color: #3f907c; -} - -.v2-calibration-safety p { - margin: 0; - font-size: 8px; - line-height: 1.5; -} - -.v2-calibration-axis-section { - margin-top: 15px; -} - -.v2-calibration-axis-section > header { - align-items: flex-end; - margin: 0 3px 9px; -} - -.v2-calibration-axis-section > header p { - margin: 0; - color: #929d9e; - font-size: 9px; -} - -.v2-calibration-axis-grid { - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 10px; -} - -.v2-calibration-axis-card { - min-width: 0; - padding: 12px; -} - -.v2-calibration-axis-card > header { - display: grid; - grid-template-columns: auto minmax(0, 1fr) auto; - align-items: center; - gap: 7px; -} - -.v2-calibration-axis-card > header > span { - color: #7084a8; - font: 800 7px Consolas, monospace; -} - -.v2-calibration-axis-card > header > strong { - overflow: hidden; - color: #435457; - font-size: 10px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-axis-card > header > b { - color: #408974; - font-size: 8px; -} - -.v2-calibration-axis-card > header > b.moving { - color: #315eaa; -} - -.v2-calibration-axis-reading { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 8px; - margin: 13px 0 8px; -} - -.v2-calibration-axis-reading strong { - color: #26383b; - font-size: clamp(15px, 1.35vw, 21px); -} - -.v2-calibration-axis-reading span { - color: #9ba5a6; - font: 700 7px Consolas, monospace; -} - -.v2-calibration-axis-card input[type="range"] { - width: 100%; - height: 4px; - accent-color: var(--v2-accent); - cursor: pointer; -} - -.v2-calibration-range-labels { - display: flex; - justify-content: space-between; - margin-top: 4px; - color: #a1aaaa; - font-size: 7px; -} - -.v2-calibration-axis-actions { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 5px; - margin-top: 10px; -} - -.v2-calibration-axis-actions button, -.v2-calibration-actions button, -.v2-calibration-settings-card > button:not(.v2-calibration-primary) { - min-height: 30px; - padding: 6px 7px; - color: #6b7779; - background: #f3f6f5; - border: 1px solid rgba(53, 84, 85, 0.08); - border-radius: 8px; - font-size: 8px; - font-weight: 800; - cursor: pointer; -} - -.v2-calibration-axis-actions button:nth-child(2), -.v2-calibration-actions button:first-child { - color: #315eaa; - background: #eef3fb; -} - -.v2-calibration-axis-actions button:disabled { - cursor: not-allowed; - opacity: 0.48; -} - -.v2-calibration-stereo-grid { - display: grid; - grid-template-columns: minmax(0, 0.94fr) minmax(0, 1.06fr); - gap: 14px; -} - -.v2-calibration-mqtt-panel, -.v2-calibration-video-panel, -.v2-calibration-mapping-panel { - padding: 16px; -} - -.v2-calibration-metrics { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 7px; - margin: 15px 0 9px; -} - -.v2-calibration-metrics > div { - min-width: 0; - display: grid; - gap: 3px; - padding: 10px; - background: #f6f9f8; - border-radius: 10px; -} - -.v2-calibration-metrics small { - color: #98a3a4; - font-size: 8px; -} - -.v2-calibration-metrics strong { - color: #3c5053; - font-size: 17px; -} - -.v2-calibration-detail, -.v2-calibration-form-note { - margin: 8px 0; - color: #8e999a; - font-size: 8px; - line-height: 1.45; -} - -.v2-calibration-pose-areas { - min-height: 182px; - display: grid; - align-content: start; - gap: 7px; -} - -.v2-calibration-empty { - align-self: center; - margin: 38px auto; - color: #98a3a4; - font-size: 9px; - text-align: center; -} - -.v2-calibration-pose-row { - min-width: 0; - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - gap: 4px 10px; - padding: 9px 10px; - background: #f6f9f8; - border-radius: 10px; -} - -.v2-calibration-pose-row strong { - overflow: hidden; - color: #425457; - font-size: 9px; - text-overflow: ellipsis; -} - -.v2-calibration-pose-row span { - color: #315eaa; - font: 800 8px Consolas, monospace; -} - -.v2-calibration-pose-row small { - grid-column: 1 / -1; - color: #93a0a1; - font: 7px Consolas, monospace; -} - -.v2-calibration-actions { - display: flex; - flex-wrap: wrap; - gap: 6px; - margin-top: 10px; -} - -.v2-calibration-actions button { - padding-inline: 12px; -} - -.v2-calibration-video-frame { - min-height: clamp(260px, 41vh, 440px); - position: relative; - margin-top: 14px; - overflow: hidden; - background: - radial-gradient(circle at 50% 45%, rgba(89, 121, 178, 0.18), transparent 45%), - #17233b; - border-radius: 13px; -} - -.v2-calibration-video-frame img { - width: 100%; - height: 100%; - position: absolute; - inset: 0; - z-index: 2; - display: none; - object-fit: contain; -} - -.v2-calibration-video-frame img.playing { - display: block; -} - -#calibrationVideoPlaceholder { - height: 100%; - position: absolute; - inset: 0; - display: grid; - place-content: center; - justify-items: center; - gap: 7px; - color: #a8bcbc; -} - -#calibrationVideoPlaceholder svg { - width: 33px; - height: 33px; - color: #8da8d8; -} - -#calibrationVideoPlaceholder strong { - font-size: 11px; -} - -#calibrationVideoPlaceholder small { - color: #718487; - font-size: 8px; -} - -.v2-calibration-mapping-panel { - margin-top: 14px; -} - -.v2-calibration-mapping-rows { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 8px; - margin-top: 13px; -} - -.v2-calibration-mapping-row { - min-width: 0; - display: grid; - grid-template-columns: 42px 72px minmax(80px, 1fr) 72px; - align-items: center; - gap: 8px; - padding: 9px 10px; - background: #f6f9f8; - border-radius: 10px; - font-size: 8px; -} - -.v2-calibration-mapping-row strong { - color: #46595b; -} - -.v2-calibration-mapping-row span, -.v2-calibration-mapping-row b { - color: #839193; - font: 700 7px Consolas, monospace; -} - -.v2-calibration-mapping-row b { - text-align: right; -} - -.v2-calibration-mapping-row > div { - height: 5px; - overflow: hidden; - background: #e1e9e7; - border-radius: 999px; -} - -.v2-calibration-mapping-row i { - height: 100%; - display: block; - background: linear-gradient(90deg, #9ab2dd, #315eaa); - border-radius: inherit; -} - -/* Unified live calibration workspace ------------------------------------ */ - -.v2-calibration-live-view { - height: 100%; - display: grid; - grid-template-rows: minmax(275px, 1fr) auto; - gap: 10px; - padding: 1px 3px 6px 1px; - overflow: hidden; -} - -.v2-calibration-live-grid { - min-width: 0; - min-height: 0; - display: grid; - grid-template-columns: minmax(420px, 1.06fr) minmax(380px, 0.94fr); - gap: 10px; -} - -.v2-calibration-live-grid > .v2-calibration-panel { - min-width: 0; - min-height: 0; - height: 100%; - padding: 12px; - overflow: hidden; -} - -.v2-calibration-live-grid .v2-calibration-stage { - display: grid; - grid-template-rows: auto minmax(150px, 1fr) auto; -} - -.v2-calibration-live-grid .v2-calibration-stage > header, -.v2-calibration-live-grid .v2-calibration-video-panel > header { - align-items: center; -} - -.v2-calibration-live-grid .v2-calibration-panel h2 { - font-size: clamp(14px, 1.12vw, 18px); -} - -.v2-calibration-live-grid .v2-calibration-operation { - min-height: 38px; - margin-top: 7px; - padding-block: 5px; -} - -.v2-calibration-live-grid .v2-axis-tag { - padding: 4px 6px; - font-size: 7px; -} - -.v2-calibration-live-grid .v2-calibration-video-panel { - display: grid; - grid-template-rows: auto minmax(150px, 1fr) auto auto; -} - -.v2-calibration-live-grid .v2-calibration-video-frame { - min-height: 0; - margin-top: 8px; -} - -.v2-calibration-live-grid .v2-calibration-video-panel .v2-calibration-detail { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-live-grid .v2-calibration-actions { - margin-top: 5px; -} - -.v2-calibration-live-grid .v2-calibration-actions button { - min-height: 26px; - padding: 4px 9px; -} - -.v2-calibration-live-grid .v2-calibration-mqtt-panel { - display: flex; - flex-direction: column; -} - -.v2-calibration-live-grid .v2-calibration-metrics { - gap: 5px; - margin: 8px 0 5px; -} - -.v2-calibration-live-grid .v2-calibration-metrics > div { - gap: 1px; - padding: 6px 7px; - border-radius: 8px; -} - -.v2-calibration-live-grid .v2-calibration-metrics strong { - font-size: 13px; -} - -.v2-calibration-live-grid .v2-calibration-detail { - margin: 4px 0; -} - -.v2-calibration-live-grid .v2-calibration-pose-areas { - min-height: 38px; - max-height: 92px; - display: grid; - grid-template-columns: 1fr; - gap: 4px; - overflow: auto; - scrollbar-width: thin; -} - -.v2-calibration-live-grid .v2-calibration-empty { - align-self: center; - margin: 10px auto; - font-size: 8px; -} - -.v2-calibration-live-grid .v2-calibration-pose-row { - gap: 2px 6px; - padding: 3px 6px; - border-radius: 8px; -} - -.v2-calibration-live-grid .v2-calibration-pose-row strong { - font-size: 8px; - line-height: 1.1; -} - -.v2-calibration-live-grid .v2-calibration-pose-row span { - font-size: 7px; - line-height: 1.1; -} - -.v2-calibration-live-grid .v2-calibration-pose-row small { - font-size: 6px; - line-height: 1.1; -} - -.v2-calibration-live-mapping { - min-height: 0; - margin-top: 6px; - padding-top: 6px; - border-top: 1px solid rgba(49, 94, 170, 0.1); -} - -.v2-calibration-subheading { - display: flex; - align-items: baseline; - justify-content: space-between; -} - -.v2-calibration-subheading span { - color: #5b77aa; - font: 800 7px Consolas, monospace; - letter-spacing: 0.12em; -} - -.v2-calibration-subheading strong { - color: #596a6d; - font-size: 9px; -} - -.v2-calibration-live-mapping .v2-calibration-mapping-rows { - grid-template-columns: 1fr; - gap: 2px; - margin-top: 4px; -} - -.v2-calibration-live-mapping .v2-calibration-mapping-row { - grid-template-columns: 34px 52px minmax(28px, 1fr) 47px; - gap: 5px; - padding: 2px 6px; - border-radius: 7px; - font-size: 7px; - line-height: 1; -} - -.v2-calibration-live-mapping .v2-calibration-mapping-row span, -.v2-calibration-live-mapping .v2-calibration-mapping-row b { - font-size: 6px; -} - -.v2-calibration-live-axes { - min-width: 0; - margin: 0; - padding: 10px 11px 8px; -} - -.v2-calibration-live-axes > .v2-calibration-live-toolbar { - display: grid; - grid-template-columns: minmax(128px, 0.54fr) minmax(340px, 1.5fr) minmax(155px, 0.64fr); - align-items: center; - gap: 10px; - margin: 0 0 8px; -} - -.v2-calibration-axis-title { - min-width: 0; -} - -.v2-calibration-axis-title h2 { - margin-top: 1px; -} - -.v2-calibration-axis-title small { - display: block; - overflow: hidden; - margin-top: 2px; - color: #919d9e; - font-size: 7px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-live-toolbar .v2-calibration-flow { - min-width: 0; - display: grid; - grid-template-columns: minmax(0, 1fr) 12px minmax(0, 1fr) 12px minmax(0, 1fr); - align-items: center; -} - -.v2-calibration-live-toolbar .v2-calibration-flow > div { - min-height: 36px; - grid-template-columns: 24px minmax(0, 1fr); - gap: 5px; - padding: 4px 6px; - border-radius: 9px; -} - -.v2-calibration-live-toolbar .v2-calibration-flow > div > span { - font-size: 8px; -} - -.v2-calibration-live-toolbar .v2-calibration-flow strong { - font-size: 8px; -} - -.v2-calibration-live-toolbar .v2-calibration-flow small { - overflow: hidden; - font-size: 6px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-calibration-live-toolbar .v2-calibration-flow > i { - width: 100%; - height: 1px; - margin: 0; -} - -.v2-calibration-live-toolbar > .v2-calibration-primary { - width: 100%; - min-height: 36px; - padding: 7px 9px; - font-size: 8px; -} - -.v2-calibration-live-axes .v2-calibration-axis-card { - padding: 8px 9px; - border-radius: 13px; - box-shadow: 0 8px 22px rgba(39, 70, 72, 0.055); -} - -.v2-calibration-live-axes .v2-calibration-axis-reading { - margin: 7px 0 4px; -} - -.v2-calibration-live-axes .v2-calibration-axis-reading strong { - font-size: clamp(13px, 1.1vw, 17px); -} - -.v2-calibration-live-axes .v2-calibration-axis-actions { - margin-top: 6px; -} - -.v2-calibration-live-axes .v2-calibration-axis-actions button { - min-height: 25px; - padding: 4px 5px; -} - -.v2-calibration-live-safety { - min-height: 24px; - grid-template-columns: 18px minmax(0, 1fr); - gap: 5px; - margin-top: 6px; - padding: 4px 7px; -} - -.v2-calibration-live-safety svg { - width: 13px; - height: 13px; -} - -.v2-calibration-live-safety p { - display: flex; - gap: 7px; - align-items: baseline; - font-size: 7px; -} - -.v2-calibration-live-safety span { - color: #718985; -} - -.v2-calibration-settings-grid { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 13px; -} - -.v2-calibration-settings-card { - min-width: 0; - display: flex; - flex-direction: column; - gap: 10px; - padding: 17px; -} - -.v2-calibration-settings-card > header { - display: grid; - grid-template-columns: 38px minmax(0, 1fr); - align-items: center; - justify-content: start; - gap: 10px; -} - -.v2-calibration-settings-card > header > span { - width: 36px; - height: 36px; - display: grid; - place-items: center; - color: white; - background: linear-gradient(135deg, #5d82c2, #315eaa); - border-radius: 10px; - font: 850 9px Consolas, monospace; -} - -.v2-calibration-settings-card > header small { - color: #657da8; - font: 750 7px Consolas, monospace; - letter-spacing: 0.1em; -} - -.v2-calibration-settings-card > header h2 { - margin-top: 1px; -} - -.v2-calibration-settings-card label { - display: grid; - gap: 5px; - color: #718083; - font-size: 8px; - font-weight: 750; -} - -.v2-calibration-settings-card input { - width: 100%; - min-width: 0; - height: 36px; - padding: 7px 9px; - color: #415356; - background: #f5f8f7; - border: 1px solid rgba(54, 85, 86, 0.09); - border-radius: 9px; - outline: 0; - font-size: 9px; -} - -.v2-calibration-settings-card input:focus { - border-color: rgba(49, 94, 170, 0.42); - box-shadow: 0 0 0 3px rgba(79, 115, 178, 0.12); -} - -.v2-calibration-two-col { - min-width: 0; - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 8px; -} - -.v2-calibration-settings-card > button { - margin-top: auto; -} - -@media (max-height: 820px) { - .console-v2[data-module="self-calibration"] .v2-calibration-sidebar { - margin-top: 14px; - } - - .v2-calibration-sidebar .v2-section-heading h2 { - margin-bottom: 10px; - } - - .v2-calibration-sidebar > .v2-field-caption { - margin-bottom: 5px; - font-size: 11px; - } - - .v2-calibration-mode-switch button { - min-height: 41px; - grid-template-columns: 21px minmax(0, 1fr); - padding: 0 9px; - font-size: 10px; - } - - .v2-calibration-mode-switch button svg { - width: 17px; - height: 17px; - } - - .v2-calibration-config-card { - min-height: 38px; - } -} - -@media (max-width: 1180px) { - .v2-calibration-hero-grid { - grid-template-columns: minmax(0, 1.5fr) minmax(245px, 0.75fr); - } - - .v2-calibration-statuses > div { - min-width: 94px; - } - - .v2-calibration-axis-grid { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } - - .v2-calibration-live-grid { - grid-template-columns: minmax(390px, 1.06fr) minmax(340px, 0.94fr); - } - - .v2-calibration-live-axes .v2-calibration-axis-grid { - grid-template-columns: repeat(4, minmax(0, 1fr)); - } - - .v2-calibration-live-axes > .v2-calibration-live-toolbar { - grid-template-columns: minmax(118px, 0.48fr) minmax(300px, 1.45fr) minmax(140px, 0.62fr); - } - - .v2-calibration-settings-grid { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } -} - -@media (max-width: 900px) { - .console-v2[data-module="self-calibration"] .v2-self-calibration { - overflow: auto; - } - - .v2-calibration-heading { - align-items: flex-start; - flex-direction: column; - } - - .v2-calibration-statuses { - width: 100%; - } - - .v2-calibration-statuses > div { - min-width: 0; - flex: 1; - } - - .v2-calibration-view { - overflow: visible; - } - - .v2-calibration-live-view { - height: auto; - grid-template-rows: auto auto; - overflow: visible; - } - - .v2-calibration-hero-grid, - .v2-calibration-stereo-grid, - .v2-calibration-live-grid { - grid-template-columns: 1fr; - } - - .v2-calibration-live-grid > .v2-calibration-panel { - min-height: 330px; - } - - .v2-calibration-live-axes > .v2-calibration-live-toolbar { - grid-template-columns: 1fr; - } - - .v2-calibration-live-axes .v2-calibration-axis-grid { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } - - .v2-calibration-workflow { - min-height: 360px; - } -} - -@media (max-width: 680px) { - .v2-calibration-statuses { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - } - - .v2-calibration-axis-grid, - .v2-calibration-mapping-rows, - .v2-calibration-settings-grid { - grid-template-columns: 1fr; - } - - .v2-calibration-mapping-row { - grid-template-columns: 38px 64px minmax(60px, 1fr) 64px; - } -} - -@media (prefers-reduced-motion: reduce) { - .v2-calibration-seat-scene .model-spinner { - animation-duration: 2.4s; - } -} diff --git a/apps/web-console/self-calibration.js b/apps/web-console/self-calibration.js deleted file mode 100644 index 52b7950..0000000 --- a/apps/web-console/self-calibration.js +++ /dev/null @@ -1,665 +0,0 @@ -(function () { - "use strict"; - - const API_ROOT = "/api/calibration"; - const TARGET_KEY = "cognitive-agent.calibration-target"; - const pageTitles = { - live: ["SELF-CALIBRATION", "座椅与双目联合标定", "同步标定座椅姿态、四轴 Hall 与 ZED 实时画面"], - system: ["SELF-CALIBRATION · SETTINGS", "连接与运行设置", "配置 CAN、MQTT 与 RTSP 接入参数"], - }; - const phaseLabels = { - 0: "待命", - 1: "寻找最近点", - 2: "寻找最远点", - 3: "返回最近点", - 4: "完成", - 5: "失败", - 6: "已停止", - }; - - const $ = (selector, root = document) => root.querySelector(selector); - const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]; - - let currentState = null; - let eventSource = null; - let reconnectTimer = 0; - let toastTimer = 0; - let settingsHydrated = false; - let activeView = "live"; - let bootstrapResetComplete = false; - - function buildShell() { - const sidebar = $(".v2-sidebar"); - const mainPanel = $(".main-panel"); - const moduleSwitcher = $("#v2ModuleSwitcher"); - if (!sidebar || !mainPanel || !moduleSwitcher || $("#v2SelfCalibration")) return false; - - const calibrationSidebar = document.createElement("section"); - calibrationSidebar.className = "v2-sidebar-section v2-calibration-sidebar"; - calibrationSidebar.innerHTML = ` -
      - CALIBRATION DESK -

      控制台

      -
      - 标定工作台 -
      - -
      -
      - 配置信息 -
      -
      当前车型腾势 N7
      N7
      -
      推理模型GPT-5.6-sol
      READY
      -
      - -
      - 执行目标 -
      - -
      -
      - IDLE -
      -
      -

      选择执行目标后连接台架

      - - `; - sidebar.insertBefore(calibrationSidebar, $(".v2-sidebar-footer")); - - const calibrationFooter = document.createElement("footer"); - calibrationFooter.className = "v2-sidebar-footer v2-calibration-footer"; - calibrationFooter.innerHTML = ` - -
      自标定安全链路尚未连接台架
      - `; - sidebar.append(calibrationFooter); - - const root = document.createElement("section"); - root.className = "v2-self-calibration"; - root.id = "v2SelfCalibration"; - root.setAttribute("aria-label", "N7 自标定工作台"); - root.innerHTML = ` -
      -
      - SELF-CALIBRATION -

      座椅与双目联合标定

      -

      同步标定座椅姿态、四轴 Hall 与 ZED 实时画面

      -
      -
      -
      CAN未连接
      -
      MOTOR等待状态
      -
      MQTT等待数据
      -
      -
      - -
      -
      -
      -
      DIGITAL TWIN

      实时座椅姿态

      待命
      -
      -
      -
      - -
      - - 正在构建座椅数字孪生 - CALIBRATION · CARTOON TWIN -
      -
      拖动空白处旋转 · 拖动轴标签或座椅部件调轴 · 滚轮缩放 · 双击复位
      -
      - -
      靠背 0.0°
      -
      前后 0.00 cm
      -
      腿托 0.0°
      -
      高度 0.00 cm
      -
      -
      -
      当前任务等待设备检测
      JOB — -
      -
      - -
      -
      ZED LIVE · RTSP

      ZED 实时画面

      未启动
      -
      ZED 双目实时画面
      ZED 双目画面RTSP → MJPEG 实时转发
      -

      视频接收尚未启动

      -
      -
      - -
      - -
      -
      -
      LIVE AXES

      四轴实时控制

      滑块设定位置 · 端点按钮单次执行
      -
      -
      01
      最近点建立机械零位
      - -
      02
      最远点测量完整量程
      - -
      03
      返回近点验证端点一致
      -
      - -
      -
      -

      安全租约已启用运动期间每 500 ms 心跳;超时由固件自动 STOP。

      -
      -
      - - `; - moduleSwitcher.insertAdjacentElement("afterend", root); - - const target = $("#calibrationExecutionSelect"); - target.value = sessionStorage.getItem(TARGET_KEY) === "simulation" - ? "simulation" - : "hardware"; - window.CognitiveAgentConsoleV2?.enhanceSelect(target); - return true; - } - - function isAdmin() { - return window.CognitiveAgentConsoleV2?.getRole() === "admin" - || document.body.dataset.demoRole === "admin"; - } - - function isActive() { - return isAdmin() && document.body.dataset.module === "self-calibration"; - } - - function toast(message, error = false) { - const node = $("#toast"); - if (!node) return; - node.textContent = message; - node.className = error ? "toast show error" : "toast show"; - window.clearTimeout(toastTimer); - toastTimer = window.setTimeout(() => { - node.className = "toast"; - }, 3600); - } - - async function api(path, body = {}) { - const response = await fetch(`${API_ROOT}${path}`, { - method: "POST", - credentials: "same-origin", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - "X-Cognitive-Agent-Role": "admin", - }, - body: JSON.stringify(body), - }); - const data = await response.json().catch(() => ({ - message: `HTTP ${response.status}`, - })); - if (!response.ok) throw new Error(data.message || data.error || `HTTP ${response.status}`); - if (data.state) render(data.state); - return data; - } - - async function fetchState() { - const response = await fetch(`${API_ROOT}/state`, { - credentials: "same-origin", - headers: { - Accept: "application/json", - "X-Cognitive-Agent-Role": "admin", - }, - }); - const data = await response.json().catch(() => ({})); - if (!response.ok) throw new Error(data.message || data.error || `HTTP ${response.status}`); - render(data); - return data; - } - - async function run(action, success = "") { - try { - await action(); - if (success) toast(success); - } catch (error) { - toast(error.message || String(error), true); - } - } - - function statusClass(state) { - if (["online", "subscribed", "simulated", "playing"].includes(state)) return "online"; - if (["connecting", "idle"].includes(state)) return "wait"; - if (state === "error") return "error"; - return ""; - } - - function setStatusDot(selector, state) { - const node = $(selector); - if (node) node.className = statusClass(state); - } - - function render(state) { - if (!state?.transport || !state?.controller) return; - currentState = state; - const { transport, controller, mqtt } = state; - setStatusDot("#calibrationCanDot", transport.state); - setStatusDot( - "#calibrationMotorDot", - controller.motor_ready ? "online" : transport.state === "online" ? "connecting" : transport.state, - ); - setStatusDot("#calibrationMqttDot", mqtt.state); - - $("#calibrationCanState").textContent = transport.state === "online" - ? transport.mode === "simulation" ? "仿真在线" : "实机在线" - : transport.state === "connecting" ? "连接中" - : transport.state === "error" ? "连接异常" : "未连接"; - $("#calibrationMotorState").textContent = controller.motor_ready - ? controller.armed ? "已解锁" : "已就绪" - : "等待状态"; - $("#calibrationMqttState").textContent = mqtt.state === "simulated" - ? "仿真数据" - : mqtt.state === "subscribed" ? "已订阅" - : mqtt.state === "connecting" ? "连接中" : "未连接"; - $("#calibrationPhaseBadge").textContent = - state.operation.phase_name || phaseLabels[state.operation.phase] || "待命"; - $("#calibrationPhaseBadge").className = `v2-calibration-badge ${ - [5, 6].includes(state.operation.phase) - ? "error" - : state.operation.phase === 0 ? "wait" : "" - }`; - $("#calibrationOperationLabel").textContent = state.operation.label; - $("#calibrationJobId").textContent = controller.job_id || "—"; - $("#calibrationTransportDetail").textContent = transport.detail; - $("#calibrationConnectionText").textContent = transport.detail; - - const targetState = $("#calibrationTargetState"); - targetState.textContent = transport.state === "online" ? "READY" - : transport.state === "connecting" ? "LINK" : transport.state === "error" ? "ERROR" : "IDLE"; - $("#calibrationTargetCard").dataset.state = transport.state; - $("#calibrationTargetNote").textContent = transport.detail; - - renderWorkflow(state.operation.phase); - renderAxes(state.axes, controller.job_active, transport.state === "online"); - renderSeat(state.axes); - const seatViewer = $("#calibrationSeatViewer"); - const axisControlEnabled = transport.state === "online" && !controller.job_active; - if (seatViewer) { - seatViewer.dataset.axisControlEnabled = String(axisControlEnabled); - } - $$('[data-seat-axis-label]').forEach((label) => { - label.dataset.controlEnabled = String(axisControlEnabled); - label.setAttribute("aria-disabled", String(!axisControlEnabled)); - }); - renderVideo(state.video); - $("#calibrationStartAll").disabled = - transport.state !== "online" || controller.job_active; - if (!settingsHydrated) hydrateSettings(state.settings, state.video.ffmpeg_available); - } - - function renderWorkflow(phase) { - $$(".v2-calibration-flow > div").forEach((step) => { - const value = Number(step.dataset.phase); - step.classList.toggle("active", phase === value); - step.classList.toggle("done", phase === 4 || (phase > value && phase < 5)); - }); - } - - function createAxisCards(axes) { - const container = $("#calibrationAxisCards"); - if (!container) return; - axes.forEach((axis) => { - const card = document.createElement("article"); - card.className = "v2-calibration-axis-card"; - card.dataset.axis = axis.id; - card.innerHTML = ` -
      AXIS 0${axis.id + 1}就绪
      -
      0HALL 0 / 0
      - -
      近端 0%远端 100%
      -
      `; - $("header strong", card).textContent = axis.title; - const slider = $('input[type="range"]', card); - slider.addEventListener("input", () => { - $(".v2-calibration-axis-reading strong", card).textContent = - formatPhysical(axis, Number(slider.value)); - }); - slider.addEventListener("change", () => run( - () => api("/move", { axis: axis.id, permille: Number(slider.value) }), - )); - $('[data-seek="near"]', card).addEventListener("click", () => run( - () => api("/seek", { axis: axis.id, far: false }), - )); - $('[data-seek="far"]', card).addEventListener("click", () => run( - () => api("/seek", { axis: axis.id, far: true }), - )); - $("[data-axis-calibrate]", card).addEventListener("click", () => run( - () => api("/start", { axis: axis.id }), - `${axis.name}自动标定已启动`, - )); - container.append(card); - }); - } - - function renderAxes(axes, busy, online) { - if (!$("#calibrationAxisCards")?.children.length) createAxisCards(axes); - axes.forEach((axis) => { - const card = $(`.v2-calibration-axis-card[data-axis="${axis.id}"]`); - if (!card) return; - const slider = $('input[type="range"]', card); - if (document.activeElement !== slider) slider.value = axis.permille; - $(".v2-calibration-axis-reading strong", card).textContent = - formatPhysical(axis, Number(slider.value)); - $(".v2-calibration-axis-reading span", card).textContent = - `HALL ${axis.hall} / ${axis.range || "—"}`; - const state = $("header b", card); - state.textContent = axis.fault ? "故障" - : axis.calibrating ? "标定中" - : axis.moving ? axis.direction - : axis.position_valid ? "就绪" : "位置未知"; - state.className = axis.moving || axis.calibrating ? "moving" : ""; - slider.disabled = busy || !online; - $$(".v2-calibration-axis-actions button", card).forEach((button) => { - button.disabled = busy || !online; - }); - }); - } - - function formatPhysical(axis, permille) { - const value = axis.physical_range * permille / 1000; - return axis.unit === "cm" ? `${value.toFixed(2)} ${axis.unit}` : `${value.toFixed(1)}${axis.unit}`; - } - - function renderSeat(axes) { - if (!axes?.length) return; - const longitudinal = axes.find((axis) => axis.id === 0) || axes[0]; - const legrest = axes.find((axis) => axis.id === 1) || axes[1]; - const backrest = axes.find((axis) => axis.id === 2) || axes[2]; - const height = axes.find((axis) => axis.id === 3) || axes[3]; - const pose = { - longitudinalM: - (longitudinal.permille / 1000 - 0.5) * longitudinal.physical_range * 0.01, - verticalM: (0.5 - height.permille / 1000) * height.physical_range * 0.01, - backrestDeg: backrest.physical_value, - legrestDeg: legrest.physical_value, - }; - window.n7SeatPose = pose; - window.dispatchEvent(new CustomEvent("n7-seat-pose", { detail: pose })); - window.dispatchEvent(new CustomEvent("calibration-seat-state", { - detail: { - axes: [ - { motor: 0, position_pct: longitudinal.permille / 10 }, - { motor: 1, position_pct: height.permille / 10 }, - { motor: 2, position_pct: backrest.permille / 10 }, - { motor: 3, position_pct: legrest.permille / 10 }, - ], - state: axes.some((axis) => axis.fault) - ? "FAILED" - : axes.some((axis) => axis.moving || axis.calibrating) ? "WORKING" : "IDLE", - }, - })); - $("#calibrationTagLong").textContent = `${longitudinal.physical_value.toFixed(2)} cm`; - $("#calibrationTagLeg").textContent = `${legrest.physical_value.toFixed(1)}°`; - $("#calibrationTagBack").textContent = `${backrest.physical_value.toFixed(1)}°`; - $("#calibrationTagHeight").textContent = `${height.physical_value.toFixed(2)} cm`; - [ - ["longitudinal", longitudinal], - ["legrest", legrest], - ["backrest", backrest], - ["height", height], - ].forEach(([name, axis]) => { - const label = $(`[data-seat-axis-label="${name}"]`); - if (!label) return; - label.setAttribute("aria-valuenow", String(Math.round(axis.permille))); - label.setAttribute("aria-valuetext", formatPhysical(axis, axis.permille)); - }); - } - - function previewSeatAxis(event) { - if (!currentState?.axes?.length) return; - const viewer = $("#calibrationSeatViewer"); - if (viewer?.dataset.axisControlEnabled !== "true") return; - const axisId = Number(event.detail?.axis); - const permille = Math.max(0, Math.min(1000, Number(event.detail?.permille))); - if (!Number.isInteger(axisId) || !Number.isFinite(permille)) return; - const axes = currentState.axes.map((axis) => ({ ...axis })); - const axis = axes.find((item) => item.id === axisId); - if (!axis) return; - axis.permille = permille; - axis.physical_value = axis.physical_range * permille / 1000; - const card = $(`.v2-calibration-axis-card[data-axis="${axisId}"]`); - if (card) { - const slider = $('input[type="range"]', card); - slider.value = String(permille); - $(".v2-calibration-axis-reading strong", card).textContent = formatPhysical(axis, permille); - } - renderSeat(axes); - } - - function commitSeatAxis(event) { - const viewer = $("#calibrationSeatViewer"); - if (viewer?.dataset.axisControlEnabled !== "true") return; - const axis = Number(event.detail?.axis); - const permille = Math.max(0, Math.min(1000, Math.round(Number(event.detail?.permille)))); - if (!Number.isInteger(axis) || !Number.isFinite(permille)) return; - run(() => api("/move", { axis, permille })); - } - - function renderVideo(video) { - const friendly = { idle: "未启动", connecting: "连接中", playing: "播放中", error: "异常" }; - $("#calibrationVideoBadge").textContent = friendly[video.state] || video.state; - $("#calibrationVideoBadge").className = `v2-calibration-badge ${ - video.state === "error" ? "error" : video.state === "idle" ? "wait" : "" - }`; - $("#calibrationVideoDetail").textContent = video.detail; - const image = $("#calibrationVideoImage"); - if (video.state === "playing" && !image.classList.contains("playing")) { - image.src = `${API_ROOT}/video/stream?role=admin&t=${Date.now()}`; - image.classList.add("playing"); - } - if (!["playing", "connecting"].includes(video.state)) { - image.classList.remove("playing"); - image.removeAttribute("src"); - } - } - - function hydrateSettings(settings, ffmpegAvailable) { - settingsHydrated = true; - $("#calibrationCanInterface").value = settings.can.interface; - $("#calibrationCanChannel").value = settings.can.channel; - $("#calibrationCanBitrate").value = settings.can.bitrate; - $("#calibrationCanPython").value = settings.can.python_executable || ""; - $("#calibrationCanDll").value = settings.can.dll_path || ""; - $("#calibrationCanDeviceType").value = settings.can.device_type ?? 41; - $("#calibrationCanDeviceIndex").value = settings.can.device_index ?? 0; - $("#calibrationMqttHost").value = settings.mqtt.host; - $("#calibrationMqttPort").value = settings.mqtt.port; - $("#calibrationMqttTopic").value = settings.mqtt.topic; - $("#calibrationVideoHost").value = settings.video.host; - $("#calibrationVideoPort").value = settings.video.port; - $("#calibrationVideoPath").value = settings.video.path; - $("#calibrationFfmpegHint").textContent = ffmpegAvailable - ? "已检测到 FFmpeg,可转发 RTSP。" - : "未检测到 FFmpeg;其余功能不受影响。"; - } - - function collectSettings() { - return { - can: { - mode: $("#calibrationExecutionSelect").value, - interface: $("#calibrationCanInterface").value.trim(), - channel: $("#calibrationCanChannel").value.trim(), - bitrate: Number($("#calibrationCanBitrate").value), - python_executable: $("#calibrationCanPython").value.trim(), - dll_path: $("#calibrationCanDll").value.trim(), - device_type: Number($("#calibrationCanDeviceType").value), - device_index: Number($("#calibrationCanDeviceIndex").value), - resistance: 1, - }, - mqtt: { - host: $("#calibrationMqttHost").value.trim(), - port: Number($("#calibrationMqttPort").value), - topic: $("#calibrationMqttTopic").value.trim(), - }, - video: { - host: $("#calibrationVideoHost").value.trim(), - port: Number($("#calibrationVideoPort").value), - path: $("#calibrationVideoPath").value.trim(), - }, - }; - } - - function showView(view) { - activeView = pageTitles[view] ? view : "live"; - $$(".v2-calibration-view").forEach((page) => { - const active = page.dataset.calibrationPage === activeView; - page.hidden = !active; - page.classList.toggle("active", active); - }); - $$("[data-calibration-view]").forEach((button) => { - button.classList.toggle("active", button.dataset.calibrationView === activeView); - }); - $("#calibrationSettingsLink").classList.toggle("active", activeView === "system"); - const [kicker, title, description] = pageTitles[activeView]; - $("#calibrationPageKicker").textContent = kicker; - $("#calibrationPageTitle").textContent = title; - $("#calibrationPageDescription").textContent = description; - window.setTimeout(() => window.dispatchEvent(new Event("resize")), 80); - } - - function updateTargetPresentation() { - const simulation = $("#calibrationExecutionSelect").value === "simulation"; - sessionStorage.setItem(TARGET_KEY, simulation ? "simulation" : "hardware"); - $("#calibrationConnectTarget span").textContent = - simulation ? "连接标定仿真台架" : "连接真实台架"; - if (!currentState || currentState.transport.state === "disconnected") { - $("#calibrationTargetNote").textContent = - simulation ? "完整 CAN 协议仿真,不驱动实体设备" : "本机 admin 可连接真实 CAN 台架"; - } - } - - function connectTarget() { - const settings = collectSettings(); - return run(async () => { - await api("/settings", settings); - await api("/can/connect", { can: settings.can }); - }, settings.can.mode === "simulation" ? "标定仿真台架已连接" : "真实台架连接完成"); - } - - function closeEvents() { - window.clearTimeout(reconnectTimer); - reconnectTimer = 0; - eventSource?.close(); - eventSource = null; - } - - function connectEvents() { - if (!isActive() || eventSource) return; - eventSource = new EventSource(`${API_ROOT}/events?role=admin`); - eventSource.onmessage = (event) => { - try { - render(JSON.parse(event.data)); - } catch (error) { - console.error("自标定状态解析失败", error); - } - }; - eventSource.onerror = () => { - closeEvents(); - if (isActive()) reconnectTimer = window.setTimeout(connectEvents, 1600); - }; - } - - function activate() { - if (!isActive()) { - closeEvents(); - return; - } - fetchState().then(async (state) => { - if (bootstrapResetComplete) return; - bootstrapResetComplete = true; - if (state.transport?.mode === "simulation") { - await api("/session/reset"); - } - }).catch((error) => toast(`自标定服务连接失败:${error.message}`, true)); - connectEvents(); - } - - function bindEvents() { - $$("[data-calibration-view]").forEach((button) => { - button.addEventListener("click", () => showView(button.dataset.calibrationView)); - }); - $("#calibrationSettingsLink").addEventListener("click", () => showView("system")); - $("#calibrationExecutionSelect").addEventListener("change", updateTargetPresentation); - $("#calibrationConnectTarget").addEventListener("click", connectTarget); - $("#calibrationGlobalStop").addEventListener("click", () => run( - () => api("/stop"), - "全轴 STOP 已确认", - )); - $("#calibrationStartAll").addEventListener("click", () => run( - () => api("/start", { axis: "all" }), - "四轴自动标定已启动", - )); - $("#calibrationVideoStart").addEventListener("click", () => run( - () => api("/video/start"), - "正在启动 RTSP 接收", - )); - $("#calibrationVideoStop").addEventListener("click", () => run( - () => api("/video/stop"), - "视频接收已停止", - )); - $("#calibrationCanForm").addEventListener("submit", (event) => { - event.preventDefault(); - connectTarget(); - }); - $("#calibrationMqttForm").addEventListener("submit", (event) => { - event.preventDefault(); - run(() => api("/settings", collectSettings()), "MQTT 设置已保存"); - }); - $("#calibrationVideoForm").addEventListener("submit", (event) => { - event.preventDefault(); - run(() => api("/settings", collectSettings()), "RTSP 设置已保存"); - }); - window.addEventListener("cognitive-agent:module-change", activate); - window.addEventListener("cognitive-agent:demo-role-change", activate); - window.addEventListener("calibration-seat-axis-preview", previewSeatAxis); - window.addEventListener("calibration-seat-axis-commit", commitSeatAxis); - window.addEventListener("beforeunload", closeEvents); - } - - function init() { - if (!buildShell()) return; - bindEvents(); - updateTargetPresentation(); - showView(activeView); - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - activate(); - } - - document.addEventListener("DOMContentLoaded", init); -}()); diff --git a/apps/web-console/self-evolution.css b/apps/web-console/self-evolution.css deleted file mode 100644 index b96a601..0000000 --- a/apps/web-console/self-evolution.css +++ /dev/null @@ -1,1381 +0,0 @@ -/* Self-evolution journal ------------------------------------------------- */ - -.console-v2 .v2-self-evolution { - display: none; -} - -.console-v2[data-module="self-evolution"] .main-panel { - grid-template-rows: 36px minmax(0, 1fr); -} - -.console-v2[data-module="self-evolution"] .v2-operation-shell, -.console-v2[data-module="self-evolution"] .v2-output-shell { - display: none; -} - -.console-v2[data-module="self-evolution"] .v2-self-evolution { - min-width: 0; - min-height: 0; - display: block; - grid-row: 2; - overflow: auto; - background: - radial-gradient(circle at 10% 0%, color-mix(in srgb, var(--v2-accent-soft) 68%, white), transparent 27%), - var(--v2-surface); - border: 1px solid color-mix(in srgb, var(--v2-accent) 14%, transparent); - border-radius: clamp(17px, 1.4vw, 24px); - box-shadow: var(--v2-shadow); -} - -.v2-evolution-shell { - min-width: 820px; - min-height: 100%; - display: grid; - grid-template-rows: auto minmax(330px, 1fr) auto; -} - -.v2-evolution-overview { - min-width: 0; - display: grid; - grid-template-columns: minmax(300px, 1fr) auto; - align-items: start; - gap: clamp(20px, 3vw, 48px); - padding: var(--v2-module-title-block) var(--v2-module-title-inline); - border-bottom: 1px solid var(--v2-line); -} - -.v2-evolution-heading .section-kicker { - display: inline-flex; - align-items: center; - gap: 7px; - color: var(--v2-accent-strong); - font-size: 9px; - font-weight: 850; - letter-spacing: 0.18em; -} - -.v2-evolution-heading .section-kicker svg { - width: 15px; - height: 15px; -} - -.v2-evolution-heading h1 { - margin: 8px 0 0; - color: var(--v2-ink); - font-size: clamp(24px, 2vw, 34px); - line-height: 1.06; - letter-spacing: -0.04em; -} - -.v2-evolution-heading > p { - margin: 9px 0 0; - color: var(--v2-muted); - font-size: 14px; - line-height: 1.6; -} - -.v2-evolution-summary { - min-width: 430px; - display: grid; - grid-template-columns: 1.25fr repeat(3, 1fr); - margin: 0; - overflow: hidden; - background: color-mix(in srgb, var(--v2-accent-soft) 38%, white); - border: 1px solid color-mix(in srgb, var(--v2-accent) 13%, transparent); - border-radius: 14px; -} - -.v2-evolution-summary > div { - min-width: 0; - display: grid; - align-content: center; - padding: 11px 14px; - border-left: 1px solid var(--v2-line); -} - -.v2-evolution-summary > div:first-child { - border-left: 0; -} - -.v2-evolution-summary dt, -.v2-evolution-summary small { - color: var(--v2-muted); - font-size: 8px; - font-weight: 750; -} - -.v2-evolution-summary dd { - margin: 2px 0 0; - color: var(--v2-ink); - font: 850 19px/1.1 "SFMono-Regular", Consolas, "Microsoft YaHei", monospace; -} - -.v2-evolution-summary .v2-evolution-current dd { - color: var(--v2-accent-strong); -} - -.v2-evolution-workspace { - min-width: 0; - min-height: 0; - display: grid; - grid-template-columns: clamp(225px, 21vw, 290px) minmax(0, 1fr); -} - -.v2-evolution-timeline { - min-width: 0; - padding: 20px 18px 18px 24px; - background: color-mix(in srgb, var(--v2-accent-soft) 13%, white); - border-right: 1px solid var(--v2-line); -} - -.v2-evolution-timeline-heading { - padding: 0 8px 12px 15px; -} - -.v2-evolution-timeline-heading span, -.v2-evolution-next small { - display: block; - color: var(--v2-accent-strong); - font-size: 8px; - font-weight: 850; - letter-spacing: 0.16em; -} - -.v2-evolution-timeline-heading strong { - display: block; - margin-top: 4px; - color: var(--v2-ink); - font-size: 13px; -} - -.v2-evolution-version-list { - position: relative; - display: grid; - gap: 4px; -} - -.v2-evolution-version-list::before { - width: 1px; - position: absolute; - inset: 11px auto 11px 6px; - content: ""; - background: color-mix(in srgb, var(--v2-accent) 24%, transparent); -} - -.v2-evolution-version { - min-width: 0; - position: relative; - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - gap: 2px 10px; - padding: 8px 9px 8px 25px; - color: var(--v2-muted); - text-align: left; - background: transparent; - border: 0; - border-radius: var(--v2-sidebar-card-radius); - cursor: pointer; -} - -.v2-evolution-version::before { - width: 7px; - height: 7px; - position: absolute; - top: 14px; - left: 3px; - z-index: 1; - content: ""; - background: white; - border: 2px solid color-mix(in srgb, var(--v2-accent) 42%, #a8b4b4); - border-radius: 50%; -} - -.v2-evolution-version:hover { - color: var(--v2-ink); - background: color-mix(in srgb, var(--v2-accent-soft) 38%, transparent); -} - -.v2-evolution-version.active { - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 72%, white); -} - -.v2-evolution-version.active::before { - background: var(--v2-accent); - border-color: white; - box-shadow: 0 0 0 4px color-mix(in srgb, var(--v2-accent) 14%, transparent); -} - -.v2-evolution-version > span { - display: flex; - align-items: center; - gap: 8px; -} - -.v2-evolution-version strong { - color: currentColor; - font: 850 12px/1.2 "SFMono-Regular", Consolas, monospace; -} - -.v2-evolution-version time, -.v2-evolution-version small { - color: var(--v2-muted); - font-size: 8px; -} - -.v2-evolution-version b { - grid-column: 1 / -1; - overflow: hidden; - color: var(--v2-ink); - font-size: 11px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-evolution-version small { - grid-column: 2; - grid-row: 1; - align-self: center; - white-space: nowrap; -} - -.v2-evolution-detail { - min-width: 0; - padding: clamp(20px, 2.2vw, 32px) clamp(24px, 2.7vw, 42px) 20px; -} - -.v2-evolution-detail-heading { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; -} - -.v2-evolution-detail-heading > div { - display: flex; - align-items: center; - gap: 10px; -} - -.v2-evolution-status { - padding: 4px 9px; - color: var(--v2-accent-strong); - background: var(--v2-accent-soft); - border-radius: 999px; - font-size: 10px; - font-weight: 850; -} - -.v2-evolution-detail-version { - color: var(--v2-muted); - font: 800 11px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-evolution-detail-heading time { - color: var(--v2-muted); - font: 750 10px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-evolution-detail > h2 { - margin: 12px 0 0; - color: var(--v2-ink); - font-size: clamp(20px, 1.7vw, 28px); - line-height: 1.15; - letter-spacing: -0.035em; -} - -.v2-evolution-lead { - max-width: 860px; - margin: 7px 0 0; - color: var(--v2-muted); - font-size: 11px; - line-height: 1.6; -} - -.v2-evolution-detail-grid { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(240px, 0.92fr); - gap: clamp(24px, 3vw, 48px); - margin-top: 18px; - padding-top: 16px; - border-top: 1px solid var(--v2-line); -} - -.v2-evolution-detail-grid h3 { - display: flex; - align-items: center; - gap: 7px; - margin: 0 0 12px; - color: var(--v2-ink); - font-size: 11px; -} - -.v2-evolution-detail-grid h3 svg { - width: 14px; - height: 14px; - color: var(--v2-accent); -} - -.v2-evolution-changes > div { - display: grid; - gap: 10px; -} - -.v2-evolution-changes > div > div { - min-width: 0; - display: grid; - grid-template-columns: 22px minmax(0, 1fr); - gap: 9px; -} - -.v2-evolution-changes > div > div > svg { - width: 22px; - height: 22px; - padding: 5px; - color: var(--v2-accent-strong); - background: var(--v2-accent-soft); - border-radius: 50%; -} - -.v2-evolution-changes p { - margin: 0; -} - -.v2-evolution-changes p strong, -.v2-evolution-changes p span { - display: block; -} - -.v2-evolution-changes p strong { - color: var(--v2-ink); - font-size: 10px; -} - -.v2-evolution-changes p span { - margin-top: 2px; - color: var(--v2-muted); - font-size: 9px; - line-height: 1.45; -} - -.v2-evolution-evidence > div { - display: grid; - gap: 12px; -} - -.v2-evolution-metric > div { - min-width: 0; - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; -} - -.v2-evolution-metric > div > span { - overflow: hidden; - color: var(--v2-ink); - font-size: 9px; - font-weight: 750; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-evolution-metric p { - display: flex; - align-items: center; - gap: 5px; - margin: 0; - white-space: nowrap; -} - -.v2-evolution-metric del { - color: #98a5a6; - font-size: 8px; - text-decoration-thickness: 1px; -} - -.v2-evolution-metric p svg { - width: 10px; - height: 10px; - color: var(--v2-muted); -} - -.v2-evolution-metric p strong { - color: var(--v2-accent-strong); - font-size: 10px; -} - -.v2-evolution-progress { - width: 100%; - height: 5px; - display: block; - margin-top: 5px; - overflow: hidden; - background: color-mix(in srgb, var(--v2-accent-soft) 50%, #e7eceb); - border-radius: 999px; -} - -.v2-evolution-progress i { - width: var(--evolution-progress); - height: 100%; - display: block; - background: linear-gradient(90deg, color-mix(in srgb, var(--v2-accent) 55%, white), var(--v2-accent)); - border-radius: inherit; - transition: width 220ms ease; -} - -.v2-evolution-validation { - display: grid; - grid-template-columns: auto minmax(0, 1fr); - align-items: center; - gap: 14px; - margin-top: 18px; - padding-top: 14px; - border-top: 1px solid var(--v2-line); -} - -.v2-evolution-module-tags { - display: flex; - flex-wrap: wrap; - gap: 5px; -} - -.v2-evolution-module-tags span, -.v2-evolution-next-steps span { - padding: 4px 8px; - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 62%, white); - border: 1px solid color-mix(in srgb, var(--v2-accent) 12%, transparent); - border-radius: 999px; - font-size: 8px; - font-weight: 800; - white-space: nowrap; -} - -.v2-evolution-validation > p { - min-width: 0; - display: flex; - align-items: center; - justify-content: flex-end; - gap: 7px; - margin: 0; - color: var(--v2-muted); - font-size: 9px; - text-align: right; -} - -.v2-evolution-validation > p svg { - width: 14px; - height: 14px; - flex: 0 0 auto; - color: var(--v2-accent); -} - -.console-v2 [data-evolution-scope="admin"] { - display: none; -} - -.console-v2[data-demo-role="admin"] [data-evolution-scope="user"] { - display: none; -} - -.console-v2[data-demo-role="admin"] [data-evolution-scope="admin"] { - display: inline; -} - -.v2-evolution-next { - min-width: 0; - display: grid; - grid-template-columns: 38px minmax(280px, 1fr) auto; - align-items: center; - gap: 13px; - padding: 13px clamp(22px, 2.2vw, 34px); - background: color-mix(in srgb, var(--v2-accent-soft) 58%, white); - border-top: 1px solid color-mix(in srgb, var(--v2-accent) 15%, transparent); -} - -.v2-evolution-next-icon { - width: 36px; - height: 36px; - display: grid; - place-items: center; - color: white; - background: var(--v2-accent); - border-radius: 11px; - box-shadow: 0 7px 18px color-mix(in srgb, var(--v2-accent) 22%, transparent); -} - -.v2-evolution-next-icon svg { - width: 16px; - height: 16px; -} - -.v2-evolution-next strong { - display: inline-block; - margin-top: 2px; - color: var(--v2-ink); - font-size: 12px; -} - -.v2-evolution-next p { - display: inline; - margin: 0 0 0 8px; - color: var(--v2-muted); - font-size: 9px; -} - -.v2-evolution-next-steps { - display: flex; - align-items: center; - gap: 6px; -} - -.v2-evolution-next-steps svg { - width: 12px; - height: 12px; - color: var(--v2-accent); -} - -/* Seat-weighing self-evolution ------------------------------------------- */ - -.console-v2 .v2-self-evolution { - --evolution-warning: #c4772b; - --evolution-warning-soft: #fff4e7; -} - -.console-v2[data-module="self-evolution"] .v2-self-evolution { - position: relative; - overflow: hidden; -} - -.v2-self-evolution .v2-evolution-shell { - height: auto; - min-width: 920px; - min-height: 0; - position: absolute; - inset: 0; - grid-template-rows: auto minmax(0, 1fr) auto; -} - -.v2-self-evolution .v2-evolution-overview { - grid-template-columns: minmax(360px, 1fr) minmax(480px, 0.94fr); - align-items: center; - gap: clamp(18px, 2.2vw, 34px); - padding-block: clamp(14px, 1.8vh, 21px); -} - -.v2-evolution-title-row { - display: flex; - align-items: flex-start; - gap: 14px; -} - -.v2-evolution-title-row > div { - min-width: 0; -} - -.v2-demo-data { - display: inline-flex; - align-items: center; - gap: 4px; - margin-top: 1px; - padding: 4px 8px; - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 78%, white); - border: 1px solid color-mix(in srgb, var(--v2-accent) 13%, transparent); - border-radius: 999px; - font-size: 8px; - font-weight: 800; - white-space: nowrap; -} - -.v2-demo-data svg { - width: 11px; - height: 11px; -} - -.v2-self-evolution .v2-evolution-heading h1 { - margin-top: 6px; -} - -.v2-self-evolution .v2-evolution-heading > p { - max-width: 660px; - margin-top: 6px; -} - -.v2-self-evolution .v2-evolution-summary { - width: 100%; - min-width: 0; -} - -.v2-self-evolution .v2-evolution-summary > div { - padding: 10px 12px; -} - -.v2-self-evolution .v2-evolution-summary dd { - font-size: clamp(16px, 1.3vw, 19px); -} - -.v2-evolution-page { - min-width: 0; - min-height: 0; - overflow: hidden; -} - -.v2-evolution-page[hidden], -.v2-evolution-next[hidden] { - display: none !important; -} - -.v2-weighing-workspace { - min-width: 0; - height: 100%; - min-height: 0; - display: grid; - grid-template-columns: clamp(235px, 20vw, 292px) minmax(0, 1fr); -} - -.v2-family-panel { - min-width: 0; - min-height: 0; - padding: 20px 16px 16px 24px; - background: color-mix(in srgb, var(--v2-accent-soft) 13%, white); - border-right: 1px solid var(--v2-line); -} - -.v2-family-heading { - padding: 0 8px 12px; -} - -.v2-family-heading span { - display: block; - color: var(--v2-accent-strong); - font: 850 8px/1.2 "SFMono-Regular", Consolas, monospace; - letter-spacing: 0.17em; -} - -.v2-family-heading strong { - display: block; - margin-top: 5px; - color: var(--v2-ink); - font-size: 14px; -} - -.v2-family-list { - position: relative; - display: grid; - gap: 4px; -} - -.v2-family-list::before { - width: 1px; - position: absolute; - inset: 15px auto 15px 7px; - content: ""; - background: color-mix(in srgb, var(--v2-accent) 28%, transparent); -} - -.v2-family-model { - min-width: 0; - min-height: 58px; - position: relative; - display: grid; - grid-template-columns: 13px minmax(0, 1fr) auto; - align-items: center; - gap: 8px; - padding: 8px 9px 8px 2px; - color: var(--v2-muted); - text-align: left; - background: transparent; - border: 0; - border-radius: 12px; - cursor: pointer; - transition: background 160ms ease, transform 160ms ease; -} - -.v2-family-model:hover { - background: color-mix(in srgb, var(--v2-accent-soft) 42%, white); -} - -.v2-family-model.active { - background: color-mix(in srgb, var(--v2-accent-soft) 76%, white); -} - -.v2-family-marker { - width: 9px; - height: 9px; - position: relative; - z-index: 1; - display: block; - background: white; - border: 2px solid color-mix(in srgb, var(--v2-accent) 58%, #99a9a8); - border-radius: 50%; -} - -.v2-family-model.active .v2-family-marker { - background: var(--v2-accent); - border-color: white; - box-shadow: 0 0 0 5px color-mix(in srgb, var(--v2-accent) 13%, transparent); -} - -.v2-family-copy { - min-width: 0; - display: grid; - gap: 4px; -} - -.v2-family-copy > span { - min-width: 0; - display: flex; - align-items: center; - gap: 6px; -} - -.v2-family-copy strong { - color: var(--v2-ink); - font-size: 11px; -} - -.v2-family-copy em { - padding: 2px 5px; - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 72%, white); - border-radius: 999px; - font-size: 7px; - font-style: normal; - font-weight: 800; - white-space: nowrap; -} - -.v2-family-copy em[data-model-state="cold"], -.v2-family-copy em[data-model-state="generic"] { - color: #718080; - background: #eef3f2; -} - -.v2-family-copy > span > small { - color: var(--v2-muted); - font: 750 8px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-family-copy > small { - overflow: hidden; - color: var(--v2-muted); - font-size: 8px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-family-error { - display: grid; - justify-items: end; - color: var(--v2-accent-strong); -} - -.v2-family-error strong { - font: 850 12px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-family-error small { - margin-top: 3px; - color: var(--v2-muted); - font-size: 7px; -} - -.v2-privacy-note { - display: grid; - grid-template-columns: 19px minmax(0, 1fr); - gap: 8px; - margin: 15px 8px 0; - padding: 10px; - color: var(--v2-muted); - background: rgba(255, 255, 255, 0.66); - border: 1px solid var(--v2-line); - border-radius: 10px; -} - -.v2-privacy-note svg { - width: 16px; - height: 16px; - color: var(--v2-accent); -} - -.v2-privacy-note p { - margin: 0; - font-size: 8px; - line-height: 1.55; -} - -.v2-model-state-guide { - display: flex; - flex-wrap: wrap; - gap: 5px 9px; - margin: 11px 8px 0; -} - -.v2-model-state-guide span { - display: inline-flex; - align-items: center; - gap: 4px; - color: var(--v2-muted); - font-size: 7px; -} - -.v2-model-state-guide span::before { - width: 5px; - height: 5px; - content: ""; - background: var(--v2-accent); - border-radius: 50%; -} - -.v2-model-state-guide span[data-state="cold"]::before { background: #a3afae; } -.v2-model-state-guide span[data-state="learning"]::before { background: #d29a36; } -.v2-model-state-guide span[data-state="warning"]::before { background: var(--evolution-warning); } - -.v2-weighing-detail { - min-width: 0; - min-height: 0; - padding: 18px clamp(22px, 2.4vw, 36px) 17px; - overflow: auto; -} - -.v2-weighing-detail-heading, -.v2-model-title-row, -.v2-convergence-card > header, -.v2-linkage-card > header, -.v2-parameter-section > header, -.v2-model-events > header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 15px; -} - -.v2-weighing-detail-heading > div:first-child { - display: flex; - align-items: center; - gap: 9px; -} - -.v2-model-badge { - padding: 4px 9px; - color: var(--v2-accent-strong); - background: var(--v2-accent-soft); - border-radius: 999px; - font-size: 8px; - font-weight: 850; -} - -.v2-model-badge[data-model-state="learning"] { - color: #9a6818; - background: #fff3d7; -} - -.v2-model-badge[data-model-state="cold"], -.v2-model-badge[data-model-state="generic"] { - color: #677575; - background: #edf2f2; -} - -.v2-model-code { - color: var(--v2-muted); - font: 750 8px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-home-sync { - display: grid; - justify-items: end; - gap: 3px; -} - -.v2-home-sync strong { - display: flex; - align-items: center; - gap: 6px; - color: var(--v2-accent-strong); - font-size: 9px; -} - -.v2-home-sync strong i { - width: 6px; - height: 6px; - background: #20a993; - border-radius: 50%; - box-shadow: 0 0 0 3px rgba(32, 169, 147, 0.1); -} - -.v2-home-sync small { - color: var(--v2-muted); - font: 700 7px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-model-title-row { - align-items: flex-end; - margin-top: 9px; - padding-bottom: 11px; - border-bottom: 1px solid var(--v2-line); -} - -.v2-model-title-row h2 { - margin: 0; - color: var(--v2-ink); - font-size: clamp(19px, 1.55vw, 25px); - line-height: 1.15; - letter-spacing: -0.035em; -} - -.v2-model-title-row p { - max-width: 700px; - margin: 5px 0 0; - color: var(--v2-muted); - font-size: 9px; - line-height: 1.5; -} - -.v2-play-evolution { - min-height: 30px; - display: inline-flex; - align-items: center; - gap: 6px; - padding: 0 10px; - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 65%, white); - border: 1px solid color-mix(in srgb, var(--v2-accent) 15%, transparent); - border-radius: 8px; - font-size: 8px; - font-weight: 800; - cursor: pointer; - white-space: nowrap; -} - -.v2-play-evolution:hover:not(:disabled) { - color: white; - background: var(--v2-accent); -} - -.v2-play-evolution:disabled { - cursor: default; - opacity: 0.45; -} - -.v2-play-evolution.playing svg { - animation: evolutionPulse 700ms ease-in-out infinite alternate; -} - -@keyframes evolutionPulse { - to { transform: scale(1.25); } -} - -.v2-play-evolution svg { - width: 12px; - height: 12px; -} - -.v2-weighing-core { - min-width: 0; - display: grid; - grid-template-columns: minmax(410px, 1.75fr) minmax(235px, 0.88fr); - gap: 14px; - margin-top: 12px; -} - -.v2-convergence-card, -.v2-linkage-card { - min-width: 0; - padding: 11px 12px; - background: color-mix(in srgb, var(--v2-accent-soft) 10%, white); - border: 1px solid var(--v2-line); - border-radius: 11px; -} - -.v2-convergence-card h3, -.v2-linkage-card h3, -.v2-parameter-section h3, -.v2-model-events h3 { - margin: 0; - color: var(--v2-ink); - font-size: 12px; -} - -.v2-chart-legend { - display: flex; - align-items: center; - gap: 13px; -} - -.v2-chart-legend span { - display: inline-flex; - align-items: center; - gap: 5px; - color: var(--v2-muted); - font-size: 7px; - white-space: nowrap; -} - -.v2-chart-legend span::before { - width: 14px; - height: 2px; - content: ""; - background: var(--v2-accent); -} - -.v2-chart-legend span[data-line="baseline"]::before { background: #9aa8a7; } -.v2-chart-legend span[data-line="target"]::before { height: 1px; background: #d97c36; } - -.v2-chart-wrap { - min-height: 164px; - position: relative; - margin-top: 4px; -} - -.v2-chart-wrap svg { - width: 100%; - height: auto; - display: block; - overflow: visible; -} - -.v2-chart-grid line { - stroke: #e5ebea; - stroke-width: 1; -} - -.v2-chart-grid text, -.v2-chart-labels text { - fill: #899897; - font: 9px "SFMono-Regular", Consolas, monospace; -} - -.v2-chart-labels text { text-anchor: middle; } -.v2-baseline-line { stroke: #9aa8a7; stroke-width: 1.5; stroke-dasharray: 7 5; } -.v2-target-line { stroke: #d97c36; stroke-width: 1.4; stroke-dasharray: 5 4; } -.v2-chart-area { fill: color-mix(in srgb, var(--v2-accent-soft) 50%, transparent); } -.v2-personal-line { fill: none; stroke: var(--v2-accent); stroke-width: 4; stroke-linecap: round; stroke-linejoin: round; } -.v2-chart-point circle:not(.hit) { fill: white; stroke: var(--v2-accent); stroke-width: 3; } -.v2-chart-point.current circle:not(.hit) { fill: var(--v2-accent); stroke: white; } -.v2-chart-point .hit { fill: transparent; stroke: transparent; cursor: pointer; } -.v2-chart-point:focus { outline: none; } -.v2-chart-point:focus circle:not(.hit) { stroke-width: 5; } -.v2-current-label rect { fill: color-mix(in srgb, var(--v2-accent-soft) 88%, white); } -.v2-current-label text { fill: var(--v2-accent-strong); font: 800 9px "SFMono-Regular", Consolas, monospace; text-anchor: middle; } - -.v2-chart-empty { - position: absolute; - inset: 38px 20px 20px 46px; - display: grid; - place-content: center; - justify-items: center; - gap: 5px; - color: var(--v2-muted); - background: rgba(255, 255, 255, 0.82); - border: 1px dashed var(--v2-line); - border-radius: 9px; - text-align: center; -} - -.v2-chart-empty svg { width: 20px; height: 20px; color: var(--v2-accent); } -.v2-chart-empty strong { color: var(--v2-ink); font-size: 9px; } -.v2-chart-empty span { font-size: 8px; } - -.v2-sample-insight { - min-height: 14px; - margin: 1px 0 0 47px; - color: var(--v2-muted); - font-size: 7px; - line-height: 1.4; -} - -.v2-linkage-card > header span { - color: var(--v2-accent-strong); - font-size: 9px; - font-weight: 800; -} - -.v2-linkage-card ol { - display: grid; - gap: 0; - margin: 9px 0 0; - padding: 0; - list-style: none; -} - -.v2-linkage-card li { - min-width: 0; - min-height: 35px; - position: relative; - display: grid; - grid-template-columns: 21px minmax(0, 1fr) auto; - align-items: start; - gap: 7px; -} - -.v2-linkage-card li::before { - width: 1px; - position: absolute; - top: 20px; - bottom: -1px; - left: 10px; - content: ""; - background: color-mix(in srgb, var(--v2-accent) 20%, #dfe6e5); -} - -.v2-linkage-card li:last-child::before { display: none; } - -.v2-linkage-card li > span { - width: 20px; - height: 20px; - position: relative; - z-index: 1; - display: grid; - place-items: center; - color: #7d8b8a; - background: #eef3f2; - border-radius: 50%; - font: 800 10px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-linkage-card li[data-step-state="done"] > span, -.v2-linkage-card li[data-step-state="active"] > span { - color: var(--v2-accent-strong); - background: var(--v2-accent-soft); -} - -.v2-linkage-card li p { - min-width: 0; - display: grid; - gap: 2px; - margin: 0; -} - -.v2-linkage-card li strong { color: var(--v2-ink); font-size: 11.5px; } -.v2-linkage-card li small { overflow: hidden; color: var(--v2-muted); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; } -.v2-linkage-card li em { color: var(--v2-muted); font-size: 10px; font-style: normal; white-space: nowrap; } -.v2-linkage-card li[data-step-state="done"] em { color: var(--v2-accent-strong); } -.v2-linkage-card li[data-step-state="active"] em { color: #a77320; } - -.v2-linkage-guard { - display: grid; - grid-template-columns: 17px minmax(0, 1fr); - gap: 7px; - margin-top: 5px; - padding: 7px 8px; - color: var(--v2-muted); - background: color-mix(in srgb, var(--v2-accent-soft) 30%, white); - border-radius: 8px; -} - -.v2-linkage-guard svg { width: 15px; height: 15px; color: var(--v2-accent); } -.v2-linkage-guard p { display: grid; gap: 2px; margin: 0; } -.v2-linkage-guard strong { color: var(--v2-ink); font-size: 10px; } -.v2-linkage-guard span { font-size: 9.5px; line-height: 1.5; } - -.v2-parameter-section { - margin-top: 11px; -} - -.v2-parameter-section > header p, -.v2-model-events > header p { - margin: 0; - color: var(--v2-muted); - font-size: 9.5px; -} - -.v2-parameter-grid { - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 8px; - margin-top: 7px; -} - -.v2-parameter-card { - min-width: 0; - padding: 8px 9px; - background: color-mix(in srgb, var(--v2-accent-soft) 9%, white); - border: 1px solid var(--v2-line); - border-radius: 9px; -} - -.v2-parameter-card > div { - min-width: 0; - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; -} - -.v2-parameter-card strong { - overflow: hidden; - color: var(--v2-ink); - font-size: 11.5px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-parameter-card > div > span { - color: var(--v2-accent-strong); - font-size: 10px; - font-weight: 850; - white-space: nowrap; -} - -.v2-parameter-card > div > span[data-evolution-scope="admin"] { - align-items: center; - gap: 4px; - font: 750 9.5px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-parameter-card > div > span svg { width: 9px; height: 9px; } -.v2-parameter-card > div em { color: #8e9b9a; font-style: normal; } -.v2-parameter-card > div b { color: var(--v2-accent-strong); } - -.v2-parameter-card > small { - display: block; - margin-top: 4px; - overflow: hidden; - color: var(--v2-muted); - font-size: 9.5px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-parameter-progress { - width: 100%; - height: 3px; - display: block; - margin-top: 7px; - overflow: hidden; - background: #e8efee; - border-radius: 99px; -} - -.v2-parameter-progress i { - width: var(--parameter-progress); - height: 100%; - display: block; - background: var(--v2-accent); - border-radius: inherit; -} - -.v2-model-events { - margin-top: 10px; -} - -.v2-model-events > header { - padding-bottom: 5px; - border-bottom: 1px solid var(--v2-line); -} - -.v2-model-events > div { - display: grid; -} - -.v2-model-event { - min-width: 0; - display: grid; - grid-template-columns: 76px minmax(180px, 1.4fr) minmax(95px, 0.7fr) minmax(100px, 0.7fr) auto; - align-items: center; - gap: 10px; - padding: 6px 0; - color: var(--v2-muted); - border-bottom: 1px solid color-mix(in srgb, var(--v2-line) 65%, transparent); - font-size: 10px; -} - -.v2-model-event:last-child { border-bottom: 0; } -.v2-model-event time { color: var(--v2-ink); font: 750 9.5px/1 "SFMono-Regular", Consolas, monospace; } -.v2-model-event strong { overflow: hidden; color: var(--v2-ink); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; } -.v2-model-event span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.v2-model-event em { color: var(--v2-accent-strong); font-size: 10px; font-style: normal; font-weight: 800; white-space: nowrap; } -.v2-model-event.warning em { color: var(--evolution-warning); } - -.v2-self-evolution .v2-evolution-next { - position: relative; - z-index: 5; - grid-template-columns: 38px minmax(280px, 1fr) minmax(140px, 190px); - padding-block: 9px; -} - -.v2-milestone-progress { - display: grid; - justify-items: end; - gap: 4px; -} - -.v2-milestone-progress strong { - color: var(--v2-accent-strong); - font: 850 10px/1 "SFMono-Regular", Consolas, monospace; -} - -.v2-milestone-progress > span { - width: 100%; - height: 4px; - display: block; - overflow: hidden; - background: rgba(255, 255, 255, 0.8); - border-radius: 99px; -} - -.v2-milestone-progress > span i { - width: 0; - height: 100%; - display: block; - background: var(--v2-accent); - border-radius: inherit; - transition: width 240ms ease; -} - -.v2-milestone-progress small { - color: var(--v2-muted); - font-size: 7px; -} - -.v2-self-evolution[data-evolution-view="system"] .v2-evolution-shell { - grid-template-rows: auto minmax(0, 1fr); -} - -.v2-self-evolution[data-evolution-view="system"] .v2-evolution-page[data-evolution-page="system"] { - overflow: auto; -} - -.v2-self-evolution[data-evolution-view="system"] .v2-evolution-workspace { - min-height: 100%; -} - -.console-v2 [data-evolution-scope="admin"] { - display: none; -} - -.console-v2[data-demo-role="admin"] [data-evolution-scope="user"] { - display: none; -} - -.console-v2[data-demo-role="admin"] [data-evolution-scope="admin"] { - display: inline-flex; -} - -@media (max-width: 1250px) { - .v2-self-evolution .v2-evolution-overview { - grid-template-columns: minmax(320px, 0.8fr) minmax(430px, 1fr); - } - - .v2-weighing-core { - grid-template-columns: minmax(390px, 1.55fr) minmax(220px, 0.8fr); - } - - .v2-family-panel { - padding-left: 18px; - } -} - -@media (max-height: 790px) { - .v2-self-evolution .v2-evolution-overview { padding-block: 11px; } - .v2-self-evolution .v2-evolution-heading h1 { font-size: 23px; } - .v2-self-evolution .v2-evolution-heading > p { margin-top: 3px; font-size: 9px; } - .v2-family-panel { padding-top: 14px; } - .v2-family-model { min-height: 50px; } - .v2-weighing-detail { padding-top: 13px; } - .v2-chart-wrap { min-height: 145px; } - .v2-convergence-card, .v2-linkage-card { padding-block: 8px; } - .v2-linkage-card li { min-height: 32px; } -} diff --git a/apps/web-console/self-evolution.js b/apps/web-console/self-evolution.js deleted file mode 100644 index 30436f7..0000000 --- a/apps/web-console/self-evolution.js +++ /dev/null @@ -1,494 +0,0 @@ -(function () { - "use strict"; - - const $ = (selector, root = document) => root.querySelector(selector); - const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]; - - const familyModels = [ - { - id: "user-a", - name: "用户 A", - code: "USER-A", - version: "v1.7", - state: "enabled", - stateLabel: "已启用", - statusNote: "专属模型已启用", - error: 0.18, - samples: 8, - sampleTarget: 11, - sync: "2026.08.14 · 08:29", - errors: [0.50, 0.44, 0.38, 0.32, 0.27, 0.23, 0.20, 0.18], - parameters: [ - { name: "零点偏移补偿", user: "已优化", before: "+0.38", after: "+0.11", progress: 88 }, - { name: "坐姿角度补偿", user: "稳定", before: "0.64", after: "0.91", progress: 91 }, - { name: "压力分布权重", user: "已优化", before: "0.72", after: "0.93", progress: 93 }, - { name: "温度漂移补偿", user: "学习中", before: "42%", after: "76%", progress: 76 }, - ], - events: [ - { time: "08.14 08:29", title: "模型 v1.7 验证通过并启用", meta: "有效样本 8", result: "±0.22 → ±0.18 kg", state: "已发布" }, - { time: "08.14 08:27", title: "家庭称重与座椅采样配对", meta: "身份匹配成功", result: "采样质量 96%", state: "已进入学习" }, - { time: "08.12 19:06", title: "模型 v1.6 参数更新", meta: "有效样本 7", result: "±0.24 → ±0.22 kg", state: "已验证" }, - ], - adminReference: "家庭体脂秤 62.40 kg · 座椅估计 62.58 kg", - }, - { - id: "user-b", - name: "用户 B", - code: "USER-B", - version: "v1.3", - state: "learning", - stateLabel: "学习中", - statusNote: "4 / 6 个有效样本", - error: 0.31, - samples: 4, - sampleTarget: 6, - sync: "2026.08.13 · 20:18", - errors: [0.50, 0.43, 0.37, 0.31], - parameters: [ - { name: "零点偏移补偿", user: "学习中", before: "+0.41", after: "+0.24", progress: 62 }, - { name: "坐姿角度补偿", user: "学习中", before: "0.61", after: "0.76", progress: 58 }, - { name: "压力分布权重", user: "已优化", before: "0.69", after: "0.82", progress: 70 }, - { name: "温度漂移补偿", user: "等待样本", before: "18%", after: "34%", progress: 34 }, - ], - events: [ - { time: "08.13 20:22", title: "新参数验证未优于 v1.3,保持旧模型", meta: "本次未参与发布", result: "±0.31 → ±0.34 kg", state: "已回滚", tone: "warning" }, - { time: "08.13 20:19", title: "检测到坐姿不稳定", meta: "异常样本已隔离", result: "采样质量 61%", state: "未参与更新", tone: "warning" }, - { time: "08.10 07:51", title: "第 4 组有效样本完成配对", meta: "身份匹配成功", result: "±0.37 → ±0.31 kg", state: "学习中" }, - ], - adminReference: "家庭体脂秤 71.25 kg · 异常座椅估计 71.59 kg", - }, - { - id: "user-c", - name: "用户 C", - code: "USER-C", - version: "—", - state: "cold", - stateLabel: "冷启动", - statusNote: "等待首次家庭称重", - error: 0.50, - samples: 0, - sampleTarget: 6, - sync: "尚未同步", - errors: [], - parameters: [ - { name: "零点偏移补偿", user: "等待数据", before: "—", after: "—", progress: 0 }, - { name: "坐姿角度补偿", user: "等待数据", before: "—", after: "—", progress: 0 }, - { name: "压力分布权重", user: "等待数据", before: "—", after: "—", progress: 0 }, - { name: "温度漂移补偿", user: "等待数据", before: "—", after: "—", progress: 0 }, - ], - events: [ - { time: "等待中", title: "尚无可用的车家配对样本", meta: "需要先在家庭体脂秤完成称重", result: "使用通用模型", state: "±0.50 kg" }, - ], - adminReference: "尚无家庭体脂秤参考值", - }, - { - id: "guest", - name: "访客", - code: "GENERIC", - version: "通用", - state: "generic", - stateLabel: "通用模型", - statusNote: "未识别用户使用通用模型", - error: 0.50, - samples: 0, - sampleTarget: 0, - sync: "无需同步", - errors: [0.50], - parameters: [ - { name: "零点偏移补偿", user: "通用参数", before: "0.00", after: "0.00", progress: 50 }, - { name: "坐姿角度补偿", user: "通用参数", before: "0.50", after: "0.50", progress: 50 }, - { name: "压力分布权重", user: "通用参数", before: "0.68", after: "0.68", progress: 50 }, - { name: "温度漂移补偿", user: "通用参数", before: "50%", after: "50%", progress: 50 }, - ], - events: [ - { time: "当前策略", title: "未识别用户不创建专属模型", meta: "不保存个人参考体重", result: "通用模型基线", state: "±0.50 kg" }, - ], - adminReference: "访客模式不记录精确体重", - }, - ]; - - const systemEntries = [ - { - version: "v0.5", date: "2026.08.12", status: "当前版本", title: "统一主题与权限体验", - summary: "把权限、主题与核心交互收束到同一套体验规则,让不同模块看起来、用起来都属于同一个系统。", - changes: [["主题统一", "自扩展固定使用 user 绿色主题,避免权限语义混用。"], ["孪生同步", "3D 模型渲染、玩具动作和车端动作统一跟随当前主题。"], ["能力扩充", "新增自进化入口,让 user 与 admin 共同查看演进过程。"]], - modules: ["自扩展", "数字孪生", "权限体系"], metrics: [["主题一致性", "72%", "100%", 100], ["可见能力模块", "4 个", "5 个", 92], ["待修正视觉项", "4 项", "0 项", 100]], - userValidation: "核心板块已完成主题复核,权限色与交互反馈保持一致。", adminValidation: "前端契约 11/11 · 自标定/自修复检查 8/8", - }, - { - version: "v0.4", date: "2026.08.11", status: "稳定版本", title: "自修复闭环增强", - summary: "从发现异常走向诊断、修复与验证闭环,同时补齐离线场景的默认内容,确保功能状态始终可见。", - changes: [["故障覆盖", "补充六类量产故障用例,覆盖更真实的车端异常。"], ["修复闭环", "形成发现、定位、决策、执行、验证五阶段流程。"], ["离线韧性", "服务暂时离线时仍保留默认案例和演示路径。"]], - modules: ["自修复", "故障诊断", "离线体验"], metrics: [["故障用例", "2 类", "6 类", 86], ["修复阶段", "3 阶段", "5 阶段", 92], ["离线可用性", "空白", "可演示", 100]], - userValidation: "断开服务后仍可理解自修复能力,并可继续浏览默认案例。", adminValidation: "默认数据回退、流程状态与接口异常路径均已验证。", - }, - { - version: "v0.3", date: "2026.08.10", status: "能力升级", title: "外设与车端统一编排", - summary: "将玩具动作、车端设备动作与数字孪生放进同一个控制流程,减少跨区域理解和操作成本。", - changes: [["动作融合", "玩具动作与车端设备动作进入统一动作界面。"], ["布局优化", "孪生界面位于左侧,动作界面固定在右侧。"], ["映射精简", "移除重复外框,让实时映射关系更直接。"]], - modules: ["自扩展", "外设学习", "整车控制"], metrics: [["动作入口", "2 处", "1 处", 100], ["映射层级", "3 层", "2 层", 88], ["协同对象", "玩具", "玩具 + 车端", 94]], - userValidation: "动作与孪生左右分区清晰,学习结果可以直接用于统一控制。", adminValidation: "外设连接状态、动作映射与车端执行链路保持独立可追踪。", - }, - { - version: "v0.2", date: "2026.08.09", status: "体系建立", title: "多权限主题体系", - summary: "建立 user 与 admin 的视觉身份,使权限差异不只体现在可用功能,也能被用户直观感知。", - changes: [["角色主题", "user 使用绿色,admin 使用蓝色,形成稳定的权限认知。"], ["能力边界", "按角色控制模块入口,同时保留清晰的切换反馈。"], ["模型联动", "数字孪生模型与界面主题保持同色语义。"]], - modules: ["权限体系", "主题系统", "数字孪生"], metrics: [["角色主题", "1 套", "2 套", 100], ["权限反馈", "文字", "视觉 + 文字", 90], ["主题联动", "界面", "界面 + 模型", 96]], - userValidation: "绿色主题贯穿 user 可用能力,角色身份更加明确。", adminValidation: "角色切换事件可同步驱动界面变量与模型渲染参数。", - }, - { - version: "v0.1", date: "2026.08.08", status: "起点版本", title: "整车认知控制台诞生", - summary: "完成从自然语言意图到整车状态回读的第一条闭环,建立后续能力持续进化的共同底座。", - changes: [["自然语言控制", "用贴近日常表达的指令控制座舱功能。"], ["整车孪生", "把座椅、空调、车窗等状态集中映射到一个界面。"], ["执行回读", "串联 CAN 计划、设备执行与状态反馈。"]], - modules: ["自编排", "数字孪生", "CAN 执行"], metrics: [["能力模块", "0 个", "1 个", 100], ["控制链路", "分散", "闭环", 92], ["状态视图", "单设备", "整车", 96]], - userValidation: "自然语言、执行过程与结果反馈首次形成连续体验。", adminValidation: "意图解析、CAN 编译计划与硬件回读具备完整追踪链路。", - }, - ]; - - let playbackTimer = null; - let activeModelId = "user-a"; - let visibleSamples = null; - - function make(tag, className, html) { - const node = document.createElement(tag); - if (className) node.className = className; - if (html != null) node.innerHTML = html; - return node; - } - - function formatError(value) { - return `±${Number(value).toFixed(2)}`; - } - - function memberButtons() { - return familyModels.map((model, index) => ` - `).join(""); - } - - function systemVersionButtons() { - return systemEntries.map((entry, index) => ` - `).join(""); - } - - function shellTemplate() { - return ` -
      -
      -
      -
      -
      SELF-EVOLUTION · SEAT WEIGHING

      座椅称重模型进化

      - 演示数据 -
      -

      通过车家联动持续校准家庭成员专属模型,让称重误差从 ±0.50 kg 逐步收敛至 ±0.10 kg。

      -
      -
      -
      - -
      -
      - - -
      -
      -
      -
      车家同步正常
      -
      -
      -

      - -
      - -
      -
      -

      验证误差收敛趋势

      通用模型专属模型目标误差
      -
      -

      -
      - -
      -

      本轮车家联动闭环

      -
        -
        -
        -
        - -
        -

        模型参数持续进化

        展示可解释参数状态管理员可见参数前后值与发布保障

        -
        -
        - -
        -

        最近进化记录

        仅显示与当前用户相关的状态

        -
        -
        -
        -
        -
        - - - -
        - -
        NEXT MILESTONE · TARGET ±0.10 kg继续积累高质量车家配对样本

        -
        -
        -
        `; - } - - function summaryTemplate(model, view) { - if (view === "system") { - return `
        当前版本
        v0.5
        能力融合期
        累计迭代
        5
        个版本
        能力改进
        12
        项记录
        最近更新
        08.12
        2026
        `; - } - return `
        当前用户
        ${model.name}
        ${model.state === "generic" ? "隐私访客模式" : model.statusNote}
        当前验证误差
        ${formatError(model.error)}
        kg · 演示数据
        目标误差
        ±0.10
        kg
        有效样本
        ${model.samples}
        ${model.sampleTarget ? `组车家配对` : "无需配对"}
        `; - } - - function chartTemplate(model, count = model.errors.length) { - const values = model.errors.slice(0, count); - const width = 720; - const left = 48; - const right = 698; - const top = 18; - const bottom = 184; - const y = (error) => top + ((0.52 - error) / 0.44) * (bottom - top); - const x = (index) => values.length <= 1 ? left : left + (index / (Math.max(model.errors.length, 2) - 1)) * (right - left); - const grid = [0.5, 0.4, 0.3, 0.2, 0.1].map((error) => ` - ±${error.toFixed(2)}`).join(""); - const points = values.map((error, index) => `${x(index)},${y(error)}`).join(" "); - const circles = values.map((error, index) => ` - - - `).join(""); - const labels = model.errors.map((_, index) => `样本${index + 1}`).join(""); - const area = values.length > 1 ? `` : ""; - const line = values.length > 1 ? `` : ""; - const current = values.length ? values[values.length - 1] : null; - return ` - ${grid} - ${area}${line}${circles}${labels} - ${current != null ? `当前 ${formatError(current)}` : ""} - ${values.length ? "" : `
        等待首组车家配对样本当前继续使用通用模型 ±0.50 kg
        `}`; - } - - function linkageTemplate(model) { - const baseSteps = [ - ["家庭体脂秤", "收到用户参考体重"], ["用户 ID 匹配", "家庭账号与车端身份一致"], ["座椅稳定采样", "坐姿、温度、座椅位置质量合格"], ["专属参数更新", "生成候选参数并离线验证"], ["验证并发布", "优于旧模型后正式生效"], - ]; - let done = model.state === "enabled" ? 5 : model.state === "learning" ? 3 : 0; - if (model.state === "generic") done = 0; - const list = baseSteps.map(([title, copy], index) => { - const state = index < done ? "done" : index === done && model.state === "learning" ? "active" : "pending"; - const label = state === "done" ? "已完成" : state === "active" ? "进行中" : "等待"; - return `
      1. ${index + 1}

        ${title}${copy}

        ${label}
      2. `; - }).join(""); - const guard = model.id === "user-b" - ? `

        退化保护已触发候选模型误差上升至 ±0.34 kg,已自动回滚并保留 v1.3。

        ` - : model.state === "enabled" - ? `

        发布保护正常只有验证结果优于当前模型时才会发布新参数。

        ` - : `

        专属模型尚未发布样本不足时保持通用模型,不以未验证参数影响称重。

        `; - return { list, guard, done }; - } - - function parameterTemplate(model) { - return model.parameters.map((item) => ` -
        -
        ${item.name}${item.user}${item.before}${item.after}
        - ${item.user === "等待数据" ? "等待有效车家样本" : "根据近期有效样本持续校准"}参数窗口 8 组 · 可回滚 · MODEL ${model.version} - -
        `).join(""); - } - - function eventTemplate(model) { - return model.events.map((event) => ` -
        ${event.title}${event.meta}${event.result}${event.state}
        `).join(""); - } - - function renderModel(root, modelId, { keepPlayback = false } = {}) { - const model = familyModels.find((item) => item.id === modelId) || familyModels[0]; - activeModelId = model.id; - if (!keepPlayback) { - clearInterval(playbackTimer); - playbackTimer = null; - visibleSamples = null; - $("#v2PlayEvolution", root)?.classList.remove("playing"); - const playLabel = $("#v2PlayEvolution span", root); - if (playLabel) playLabel.textContent = "演示进化过程"; - } - $("#v2EvolutionSummary", root).innerHTML = summaryTemplate(model, "weighing"); - $$("[data-family-model]", root).forEach((button) => { - const active = button.dataset.familyModel === model.id; - button.classList.toggle("active", active); - button.setAttribute("aria-pressed", String(active)); - }); - const badge = $("#v2ModelStateBadge", root); - badge.textContent = model.state === "enabled" ? "专属模型已启用" : model.stateLabel; - badge.dataset.modelState = model.state; - $("#v2ModelCode", root).textContent = `MODEL ${model.version} · ${model.code}`; - $("#v2HomeSyncState", root).textContent = model.state === "generic" ? "访客隐私模式" : model.sync === "尚未同步" ? "等待车家同步" : "车家同步正常"; - $("#v2HomeSyncTime", root).textContent = model.sync; - $("#v2ModelTitle", root).textContent = `${model.name} · ${model.state === "generic" ? "通用称重模型" : "个性化称重模型"}`; - $("#v2ModelLead", root).textContent = model.state === "enabled" ? "最近一次家庭参考值与车端座椅采样已完成配对,新参数通过验证并正式生效。" : model.state === "learning" ? "专属参数仍在学习;样本不足或验证退化时,车端继续使用已验证模型。" : model.state === "cold" ? "尚未收到家庭体脂秤参考值,当前安全使用通用模型。" : "未识别用户不会创建个人参数或保存精确体重。"; - const play = $("#v2PlayEvolution", root); - play.disabled = model.errors.length < 2; - play.title = play.disabled ? "当前没有可回放的专属模型样本" : "按有效样本顺序回放误差收敛过程"; - $("#v2EvolutionChart", root).innerHTML = chartTemplate(model, visibleSamples ?? model.errors.length); - $("#v2SampleInsight", root).textContent = model.errors.length > 1 ? `已从通用模型基线 ±0.50 kg 收敛至 ${formatError(model.error)} kg;点击曲线节点可查看该次样本。` : "个性化模型仅使用身份匹配、时间有效且座椅采样稳定的数据。"; - const linkage = linkageTemplate(model); - $("#v2LinkageSteps", root).innerHTML = linkage.list; - $("#v2LinkageGuard", root).innerHTML = linkage.guard; - $("#v2LinkageProgress", root).textContent = `${linkage.done} / 5 已完成`; - $("#v2ParameterGrid", root).innerHTML = parameterTemplate(model); - $("#v2EventList", root).innerHTML = eventTemplate(model); - $("#v2AdminReference", root).textContent = model.adminReference; - const remaining = Math.max(0, model.sampleTarget - model.samples); - const percent = model.sampleTarget ? Math.min(100, Math.round((model.samples / model.sampleTarget) * 100)) : 100; - $("#v2MilestoneCopy", root).textContent = model.state === "generic" ? "访客称重不会进入任何家庭成员的参数空间。" : model.state === "cold" ? "完成家庭体脂秤绑定后,首次有效配对将启动专属模型学习。" : remaining ? `预计再完成 ${remaining} 组有效样本后进入目标精度验证阶段。` : "样本数量已满足要求,正在持续验证 ±0.10 kg 目标。"; - $("#v2MilestoneCount", root).textContent = model.sampleTarget ? `${model.samples} / ${model.sampleTarget} 组` : "隐私模式"; - $("#v2MilestonePercent", root).textContent = model.sampleTarget ? `当前学习进度 ${percent}%` : "不留存个人数据"; - $("#v2MilestoneBar", root).style.width = `${percent}%`; - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - } - - function renderSystemEntry(root, index) { - const entry = systemEntries[index]; - if (!entry) return; - $("#v2SystemStatus", root).textContent = entry.status; - $("#v2SystemVersion", root).textContent = entry.version; - const date = $("#v2SystemDate", root); - date.textContent = entry.date; - date.dateTime = entry.date.replaceAll(".", "-"); - $("#v2SystemTitle", root).textContent = entry.title; - $("#v2SystemLead", root).textContent = entry.summary; - $("#v2SystemChangeList", root).innerHTML = entry.changes.map(([label, copy]) => `

        ${label}${copy}

        `).join(""); - $("#v2SystemMetrics", root).innerHTML = entry.metrics.map(([label, before, after, progress]) => `
        ${label}

        ${before}${after}

        `).join(""); - $("#v2SystemModules", root).innerHTML = entry.modules.map((module) => `${module}`).join(""); - $("#v2SystemUserValidation", root).textContent = entry.userValidation; - $("#v2SystemAdminValidation", root).textContent = entry.adminValidation; - $$("[data-system-evolution-index]", root).forEach((button, buttonIndex) => { - const active = buttonIndex === index; - button.classList.toggle("active", active); - button.setAttribute("aria-pressed", String(active)); - }); - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - } - - function setView(root, view) { - const system = view === "system"; - clearInterval(playbackTimer); - playbackTimer = null; - $$("[data-evolution-page]", root).forEach((page) => { - const active = page.dataset.evolutionPage === view; - page.classList.toggle("active", active); - page.hidden = !active; - }); - $("#v2EvolutionKicker", root).textContent = system ? "SELF-EVOLUTION · SYSTEM JOURNAL" : "SELF-EVOLUTION · SEAT WEIGHING"; - $("#v2EvolutionPageTitle", root).textContent = system ? "系统能力日志" : "座椅称重模型进化"; - $("#v2EvolutionPageIntro", root).textContent = system ? "保留每次问题发现、能力升级与验证结果,持续记录控制台系统能力演进。" : "通过车家联动持续校准家庭成员专属模型,让称重误差从 ±0.50 kg 逐步收敛至 ±0.10 kg。"; - $("#v2EvolutionDataBadge", root).innerHTML = system - ? '历史记录' - : '演示数据'; - $("#v2EvolutionSummary", root).innerHTML = summaryTemplate(familyModels.find((item) => item.id === activeModelId), view); - const footer = $("#v2EvolutionFooter", root); - footer.hidden = system; - root.dataset.evolutionView = view; - window.dispatchEvent(new CustomEvent("cognitive-agent:evolution-view-change", { - detail: { view }, - })); - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - } - - function playEvolution(root) { - const model = familyModels.find((item) => item.id === activeModelId); - if (!model || model.errors.length < 2) return; - clearInterval(playbackTimer); - let count = 1; - visibleSamples = count; - const button = $("#v2PlayEvolution", root); - button.classList.add("playing"); - $("#v2PlayEvolution span", root).textContent = "正在回放"; - renderModel(root, model.id, { keepPlayback: true }); - playbackTimer = window.setInterval(() => { - count += 1; - visibleSamples = count; - renderModel(root, model.id, { keepPlayback: true }); - if (count >= model.errors.length) { - clearInterval(playbackTimer); - playbackTimer = null; - button.classList.remove("playing"); - $("#v2PlayEvolution span", root).textContent = "再次回放"; - } - }, 520); - } - - function bind(root) { - $(".v2-family-list", root).addEventListener("click", (event) => { - const button = event.target.closest("[data-family-model]"); - if (button) renderModel(root, button.dataset.familyModel); - }); - $(".v2-evolution-version-list", root).addEventListener("click", (event) => { - const button = event.target.closest("[data-system-evolution-index]"); - if (button) renderSystemEntry(root, Number(button.dataset.systemEvolutionIndex)); - }); - $("#v2PlayEvolution", root).addEventListener("click", () => playEvolution(root)); - $("#v2EvolutionChart", root).addEventListener("click", (event) => { - const point = event.target.closest("[data-sample-index]"); - const model = familyModels.find((item) => item.id === activeModelId); - if (!point || !model) return; - const index = Number(point.dataset.sampleIndex); - $("#v2SampleInsight", root).textContent = `样本 ${index + 1}:验证误差 ${formatError(model.errors[index])} kg。该节点来自固定演示数据,不代表实时算法结果。`; - }); - $("#v2EvolutionChart", root).addEventListener("keydown", (event) => { - if (!["Enter", " "].includes(event.key)) return; - const point = event.target.closest("[data-sample-index]"); - if (point) { event.preventDefault(); point.dispatchEvent(new MouseEvent("click", { bubbles: true })); } - }); - } - - function mount(mainPanel) { - const existing = $("#v2SelfEvolution", mainPanel); - if (existing) return existing; - const evolution = make("section", "v2-self-evolution", shellTemplate()); - evolution.id = "v2SelfEvolution"; - evolution.dataset.evolutionView = "weighing"; - evolution.setAttribute("aria-label", "自进化 · 座椅称重个性化模型进化"); - mainPanel.append(evolution); - bind(evolution); - renderModel(evolution, activeModelId); - renderSystemEntry(evolution, 0); - setView(evolution, "weighing"); - return evolution; - } - - window.CognitiveAgentSelfEvolution = { - mount, - getView: () => $("#v2SelfEvolution")?.dataset.evolutionView || "weighing", - setView: (view) => { - const root = $("#v2SelfEvolution"); - if (root) setView(root, view === "system" ? "system" : "weighing"); - }, - }; -}()); diff --git a/apps/web-console/self-extension.css b/apps/web-console/self-extension.css index 3b2e746..3a5b58f 100644 --- a/apps/web-console/self-extension.css +++ b/apps/web-console/self-extension.css @@ -7,15 +7,6 @@ [data-extension-type="mechanical"] { --extension-card-color: #758e94; } [data-extension-type="other"] { --extension-card-color: #579a88; } -.console-v2[data-module="self-extension"] { - --v2-accent: #0e7773; - --v2-accent-strong: #095d5a; - --v2-accent-soft: #d8f4f1; - --v2-sidebar: #d8f4f2; - --v2-sidebar-deep: #c7eeeb; - --v2-line: rgba(18, 85, 83, 0.14); -} - .console-v2 .v2-extension-sidebar, .console-v2 .v2-extension-footer, .console-v2 .v2-self-extension, @@ -23,39 +14,6 @@ display: none; } -/* 自扩展不区分演示角色;admin/user 切换仅属于自编排。 */ -.console-v2[data-module="self-extension"] .v2-role-select { - display: none; -} - -.console-v2[data-module="self-extension"] .v2-extension-profile-title { - min-width: 0; - display: flex; - align-items: baseline; - gap: 5px; - color: #091c1e; - font-size: clamp(20px, 1.6vw, 26px); - font-weight: 900; - letter-spacing: -0.04em; -} - -.console-v2[data-module="self-extension"] .v2-extension-profile-title strong { - color: inherit; - font: inherit; -} - -.console-v2[data-module="self-extension"][data-demo-role="admin"] .v2-sidebar { - background: - radial-gradient(circle at 14% 3%, rgba(255, 255, 255, 0.8), transparent 24%), - linear-gradient(158deg, var(--v2-sidebar) 0%, #e8f8f6 60%, var(--v2-sidebar-deep) 130%); -} - -.console-v2[data-module="self-extension"][data-demo-role="admin"] .v2-avatar { - background: - radial-gradient(circle at 28% 25%, rgba(255, 255, 255, 0.95), transparent 18%), - linear-gradient(135deg, #0b4d4b 3%, #70b7b1 49%, #d1efeb 52%, #276d69 100%); -} - .console-v2[data-module="self-extension"] .v2-control-section, .console-v2[data-module="self-extension"] .v2-config-section, .console-v2[data-module="self-extension"] .v2-sidebar > .v2-sidebar-footer:not(.v2-extension-footer), @@ -98,34 +56,36 @@ .v2-extension-pet { --pet-x: 0px; --pet-y: 0px; - width: 126px; - height: 126px; - position: absolute; - right: 18px; - bottom: 16px; + width: clamp(154px, 15vw, 196px); + aspect-ratio: 1; + position: fixed; + right: max(18px, env(safe-area-inset-right)); + bottom: max(18px, env(safe-area-inset-bottom)); z-index: 24; - display: grid; - place-items: end center; + display: block; transform: translate3d(var(--pet-x), var(--pet-y), 0); - filter: drop-shadow(0 14px 16px rgba(9, 66, 63, 0.2)); + filter: drop-shadow(0 12px 14px rgba(9, 66, 63, 0.18)); touch-action: none; user-select: none; } .v2-extension-pet-bubble { - max-width: 158px; position: absolute; - right: 54px; - bottom: 89px; - padding: 7px 9px; + right: calc(100% - 36px); + bottom: calc(100% - 42px); + width: 176px; + max-width: calc(100vw - 24px); + box-sizing: border-box; + padding: 10px 12px; color: #285153; background: rgba(255, 255, 255, 0.94); border: 1px solid rgba(14, 119, 115, 0.18); border-radius: 11px 11px 2px 11px; box-shadow: 0 9px 24px rgba(22, 72, 70, 0.12); - font-size: 8px; + font-size: 13px; font-weight: 800; - line-height: 1.45; + line-height: 1.5; + overflow-wrap: break-word; opacity: 0; transform: translateY(5px) scale(0.96); transform-origin: right bottom; @@ -141,191 +101,163 @@ } .v2-extension-pet-body { - width: 76px; - height: 77px; + width: 100%; + height: 100%; position: relative; display: block; padding: 0; color: inherit; - background: linear-gradient(145deg, #f4fffd 0%, #bfe9e5 54%, #7bc3bd 100%); - border: 2px solid rgba(7, 86, 82, 0.48); - border-radius: 25px 25px 22px 22px; - box-shadow: - inset 0 3px 0 rgba(255, 255, 255, 0.82), - inset 0 -6px 12px rgba(9, 93, 89, 0.13), - 0 6px 0 #326f6c; + background: transparent; + border: 0; + border-radius: 0; + box-shadow: none; cursor: grab; - animation: extension-pet-float 3.2s ease-in-out infinite; + appearance: none; } .v2-extension-pet[data-dragging="true"] .v2-extension-pet-body { cursor: grabbing; - animation-play-state: paused; } -.v2-extension-pet-ear { - width: 22px; - height: 24px; +.v2-extension-pet-image { + width: 100%; + height: 100%; + display: block; + object-fit: contain; + pointer-events: none; +} + +.v2-extension-pet-entrance-canvas { + width: 100%; + height: 100%; position: absolute; - top: -12px; - z-index: -1; - background: linear-gradient(145deg, #dff8f5, #75bbb6); - border: 2px solid rgba(7, 86, 82, 0.48); - border-radius: 7px 15px 5px 13px; + inset: 0; + z-index: 4; + display: block; + opacity: 0; + pointer-events: none; + will-change: transform; } -.v2-extension-pet-ear.left { left: 3px; transform: rotate(-20deg); } -.v2-extension-pet-ear.right { right: 3px; transform: scaleX(-1) rotate(-20deg); } +.v2-extension-pet[data-entering="true"] .v2-extension-pet-entrance-canvas { + opacity: 1; +} -.v2-extension-pet-antenna { - width: 2px; - height: 17px; +.v2-extension-pet[data-entering="true"] .v2-extension-pet-image, +.v2-extension-pet[data-entering="true"] .v2-extension-pet-tail-canvas, +.v2-extension-pet[data-entering="true"] .v2-extension-pet-blink, +.v2-extension-pet[data-entering="true"] .v2-extension-pet-mouth-closed { + opacity: 0; +} + +.v2-extension-pet[data-entering="true"] .v2-extension-pet-bubble { + opacity: 0; + transform: translateY(5px) scale(0.96); +} + +.v2-extension-pet[data-entering="true"] .v2-extension-pet-body { + cursor: default; +} + +.v2-extension-pet-tail-canvas { + width: 100%; + height: 100%; position: absolute; - top: -21px; - left: 50%; - background: #397f7b; - transform: translateX(-50%); + inset: 0; + z-index: 1; + display: block; + object-fit: contain; + opacity: 0; + pointer-events: none; } -.v2-extension-pet-antenna i { - width: 8px; - height: 8px; +.v2-extension-pet[data-tail-waving="true"] .v2-extension-pet-tail-canvas { + opacity: 1; +} + +.v2-extension-pet[data-tail-waving="true"] .v2-extension-pet-image { + opacity: 0; +} + +.v2-extension-pet-blink { position: absolute; - top: -5px; - left: -3px; - background: #ffbd62; - border: 1px solid #9f6630; - border-radius: 50%; - box-shadow: 0 0 0 4px rgba(255, 189, 98, 0.17); - animation: extension-pet-signal 1.8s ease-in-out infinite; + inset: 0; + z-index: 2; + opacity: 0; + pointer-events: none; + transition: opacity 28ms linear; } -.v2-extension-pet-face { - width: 58px; - height: 34px; +.v2-extension-pet[data-blinking="true"] .v2-extension-pet-blink { + opacity: 1; +} + +.v2-extension-pet-blink-eye { position: absolute; - top: 9px; - left: 7px; - background: linear-gradient(180deg, #164e50, #0d383a); - border: 2px solid rgba(255, 255, 255, 0.65); - border-radius: 16px; - box-shadow: inset 0 4px 10px rgba(0, 0, 0, 0.2); + top: 31.3%; + height: 6.2%; + background: #919baa; + border-radius: 48%; } -.v2-extension-pet-face .eye { - width: 8px; - height: 10px; +.v2-extension-pet-blink-eye.left { + left: 23.7%; + width: 4%; +} + +.v2-extension-pet-blink-eye.right { + left: 35.9%; + width: 5.3%; +} + +.v2-extension-pet-blink-eye::after { + content: ""; position: absolute; - top: 9px; - background: #bdfaf2; - border-radius: 50%; - box-shadow: 0 0 7px rgba(141, 255, 241, 0.72); - animation: extension-pet-blink 4.6s infinite; + top: 48%; + right: 12%; + left: 12%; + height: 27%; + border-top: 2px solid #050606; + border-radius: 50% 50% 0 0; } -.v2-extension-pet-face .eye.left { left: 12px; } -.v2-extension-pet-face .eye.right { right: 12px; } - -.v2-extension-pet-face b { - width: 6px; - height: 4px; +.v2-extension-pet-mouth-closed { position: absolute; - top: 19px; - left: 50%; - background: #ffc17a; - border-radius: 50% 50% 65% 65%; - transform: translateX(-50%); + left: 27%; + top: 39.8%; + z-index: 3; + width: 7%; + height: 5.9%; + border-radius: 46%; + background: + linear-gradient(#050606, #050606) center top / 1.5px 34% no-repeat, + #fbfaf7; + pointer-events: none; + opacity: 1; } -.v2-extension-pet-face em { - width: 13px; - height: 6px; +.v2-extension-pet-mouth-closed::before { + content: ""; position: absolute; - top: 22px; - left: 50%; - border-bottom: 2px solid #bdfaf2; - border-radius: 50%; - transform: translateX(-50%); + top: 13%; + left: 13%; + width: 38%; + height: 34%; + border-bottom: 1.5px solid #050606; + border-radius: 0 0 70% 70%; + transform: rotate(-7deg); } -.v2-extension-pet[data-mood="happy"] .v2-extension-pet-face .eye { - height: 5px; - top: 13px; - background: transparent; - border-top: 2px solid #bdfaf2; - border-radius: 50%; -} - -.v2-extension-pet-screen { - width: 36px; - height: 17px; +.v2-extension-pet-mouth-closed::after { + content: ""; position: absolute; - bottom: 7px; - left: 18px; - display: flex; - align-items: center; - justify-content: center; - gap: 4px; - color: #eafffb; - background: #277c78; - border: 1px solid rgba(6, 79, 75, 0.5); - border-radius: 7px; - font: 900 6px Consolas, monospace; -} - -.v2-extension-pet-screen i { - width: 5px; - height: 5px; - background: #80f0bd; - border-radius: 50%; - box-shadow: 0 0 5px rgba(128, 240, 189, 0.8); -} - -.v2-extension-pet-foot { - width: 21px; - height: 10px; - position: absolute; - bottom: -12px; - background: #5ba5a0; - border: 2px solid #326f6c; - border-radius: 4px 4px 9px 9px; -} - -.v2-extension-pet-foot.left { left: 8px; } -.v2-extension-pet-foot.right { right: 8px; } - -.v2-extension-pet-tail { - width: 27px; - height: 11px; - position: absolute; - right: -21px; - bottom: 12px; - z-index: -1; - border: 5px solid #4d9994; - border-left: 0; - border-radius: 0 13px 13px 0; - transform-origin: left center; - animation: extension-pet-tail 1.1s ease-in-out infinite alternate; -} - -@keyframes extension-pet-float { - 0%, 100% { transform: translateY(0) rotate(-1deg); } - 50% { transform: translateY(-5px) rotate(1deg); } -} - -@keyframes extension-pet-blink { - 0%, 45%, 49%, 100% { transform: scaleY(1); } - 47% { transform: scaleY(0.12); } -} - -@keyframes extension-pet-signal { - 0%, 100% { opacity: 0.72; transform: scale(0.86); } - 50% { opacity: 1; transform: scale(1.15); } -} - -@keyframes extension-pet-tail { - from { transform: rotate(-14deg); } - to { transform: rotate(16deg); } + top: 13%; + right: 13%; + width: 38%; + height: 34%; + border-bottom: 1.5px solid #050606; + border-radius: 0 0 70% 70%; + transform: rotate(7deg); } .v2-extension-sidebar > .v2-field-caption { @@ -2233,3 +2165,253 @@ form > .v2-extension-primary { } } + +/* Unified extension capability mirror ------------------------------------ */ + +.v2-extension-sync-mount { + min-height: 0; + display: grid; + grid-template-rows: auto auto minmax(0, 1fr) auto; + gap: 6px; + padding: 10px; + overflow: hidden; + background: linear-gradient(145deg, #102b2d, #173c3d); + border: 1px solid rgba(40, 165, 154, 0.2); + border-radius: 17px; + box-shadow: 0 14px 34px rgba(17, 49, 50, 0.15); +} + +.v2-extension-sync-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.v2-extension-sync-heading small { + color: #66bdb5; + font: 850 8px/1.2 "SFMono-Regular", Consolas, monospace; + letter-spacing: 0.14em; +} + +.v2-extension-sync-heading h3 { + margin: 3px 0 0; + color: #f3fffd; + font-size: 14px; +} + +.v2-extension-sync-heading > span { + display: inline-flex; + align-items: center; + gap: 6px; + color: #a9c3c0; + font-size: 8px; + font-weight: 800; + white-space: nowrap; +} + +.v2-extension-sync-heading > span i { + width: 6px; + height: 6px; + background: #758e8c; + border-radius: 50%; +} + +.v2-extension-sync-heading > span[data-state="online"] i { + background: #25c896; + box-shadow: 0 0 0 5px rgba(37, 200, 150, 0.1); +} + +.v2-extension-sync-heading > span[data-state="listening"] i { + background: #e6b45f; +} + +.v2-extension-gateway { + min-width: 0; + display: grid; + grid-template-columns: 34px minmax(0, 1fr) auto; + align-items: center; + gap: 9px; + padding: 8px; + background: rgba(255, 255, 255, 0.055); + border: 1px solid rgba(130, 210, 202, 0.09); + border-radius: 11px; +} + +.v2-extension-gateway > span { + width: 34px; + height: 34px; + display: grid; + place-items: center; + color: #77d3c9; + background: rgba(77, 190, 179, 0.1); + border-radius: 10px; +} + +.v2-extension-gateway > span svg { + width: 16px; +} + +.v2-extension-gateway > div { + min-width: 0; + display: grid; + gap: 2px; +} + +.v2-extension-gateway strong { + color: #effbf9; + font-size: 10px; +} + +.v2-extension-gateway small { + overflow: hidden; + color: #91aaa8; + font-size: 8px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.v2-extension-gateway > b { + padding: 4px 6px; + color: #74c5bd; + background: rgba(90, 186, 177, 0.08); + border-radius: 6px; + font: 800 7px "SFMono-Regular", Consolas, monospace; +} + +.v2-extension-device-list { + min-height: 0; + max-height: 124px; + overflow: auto; +} + +.v2-extension-sync-mount[data-has-devices="true"] .v2-extension-gateway { + display: none; +} + +.v2-extension-synced-device { + padding: 8px; + background: rgba(255, 255, 255, 0.045); + border-radius: 10px; +} + +.v2-extension-synced-device header { + display: grid; + grid-template-columns: 28px minmax(0, 1fr) auto; + align-items: center; + gap: 8px; +} + +.v2-extension-synced-device header > span { + width: 28px; + height: 28px; + display: grid; + place-items: center; + color: #76cfc6; + background: rgba(87, 191, 180, 0.1); + border-radius: 8px; +} + +.v2-extension-synced-device header svg { + width: 14px; +} + +.v2-extension-synced-device header > div { + display: grid; + gap: 1px; +} + +.v2-extension-synced-device header strong { + color: #effaf8; + font-size: 9px; +} + +.v2-extension-synced-device header small, +.v2-extension-synced-device header b { + color: #8da7a5; + font-size: 7px; +} + +.v2-extension-synced-device > div { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 7px; +} + +.v2-extension-synced-device > div span { + padding: 3px 6px; + color: #b9d8d4; + background: rgba(95, 190, 180, 0.08); + border-radius: 999px; + font-size: 7px; +} + +.v2-extension-sync-mount .v2-extension-empty { + display: flex; + align-items: center; + justify-content: center; + gap: 9px; + min-height: 34px; + color: #668986; + background: rgba(255, 255, 255, 0.035); + border: 0; + border-radius: 9px; +} + +.v2-extension-empty > svg { + width: 19px; +} + +.v2-extension-empty div { + display: grid; + gap: 2px; +} + +.v2-extension-empty strong { + color: #bad0cd; + font-size: 9px; +} + +.v2-extension-empty span { + font-size: 7px; +} + +.v2-extension-linkage { + min-width: 0; + display: grid; + grid-template-columns: 25px minmax(0, 1fr) auto; + align-items: center; + gap: 7px; + padding-top: 7px; + border-top: 1px solid rgba(134, 203, 197, 0.1); +} + +.v2-extension-linkage > svg { + width: 15px; + color: #6faaa5; +} + +.v2-extension-linkage > div { + min-width: 0; + display: grid; + gap: 1px; +} + +.v2-extension-linkage small { + color: #708f8c; + font-size: 7px; +} + +.v2-extension-linkage strong { + overflow: hidden; + color: #c2d8d5; + font-size: 8px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.v2-extension-linkage > span { + color: #69bfb6; + font: 800 7px "SFMono-Regular", Consolas, monospace; +} diff --git a/apps/web-console/self-extension.js b/apps/web-console/self-extension.js index 1007a0b..8932bea 100644 --- a/apps/web-console/self-extension.js +++ b/apps/web-console/self-extension.js @@ -18,6 +18,79 @@ const $ = (selector, root = document) => root.querySelector(selector); const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]; + function rgbToHsl(red, green, blue) { + const r = red / 255; + const g = green / 255; + const b = blue / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const lightness = (max + min) / 2; + const delta = max - min; + if (!delta) return [0, 0, lightness]; + const saturation = delta / (1 - Math.abs(2 * lightness - 1)); + let hue; + if (max === r) hue = ((g - b) / delta) % 6; + else if (max === g) hue = (b - r) / delta + 2; + else hue = (r - g) / delta + 4; + return [((hue * 60) + 360) % 360, saturation, lightness]; + } + + function hslToRgb(hue, saturation, lightness) { + const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation; + const section = hue / 60; + const intermediate = chroma * (1 - Math.abs((section % 2) - 1)); + let rgb = [0, 0, 0]; + if (section < 1) rgb = [chroma, intermediate, 0]; + else if (section < 2) rgb = [intermediate, chroma, 0]; + else if (section < 3) rgb = [0, chroma, intermediate]; + else if (section < 4) rgb = [0, intermediate, chroma]; + else if (section < 5) rgb = [intermediate, 0, chroma]; + else rgb = [chroma, 0, intermediate]; + const match = lightness - chroma / 2; + return rgb.map((channel) => Math.round((channel + match) * 255)); + } + + function parseCssRgb(value) { + const color = String(value || "").trim(); + const shortHex = color.match(/^#([\da-f])([\da-f])([\da-f])$/i); + if (shortHex) return shortHex.slice(1).map((channel) => parseInt(channel + channel, 16)); + const hex = color.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i); + if (hex) return hex.slice(1).map((channel) => parseInt(channel, 16)); + const rgb = color.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i); + return rgb ? rgb.slice(1).map(Number) : null; + } + + function createThemedPetDataUrl(sourceImage, accentColor) { + const accent = parseCssRgb(accentColor); + if (!accent || !sourceImage.naturalWidth || !sourceImage.naturalHeight) return ""; + const [targetHue] = rgbToHsl(...accent); + const canvas = document.createElement("canvas"); + canvas.width = sourceImage.naturalWidth; + canvas.height = sourceImage.naturalHeight; + const context = canvas.getContext("2d", { willReadFrequently: true }); + if (!context) return ""; + context.drawImage(sourceImage, 0, 0); + const imageData = context.getImageData(0, 0, canvas.width, canvas.height); + const { data } = imageData; + for (let index = 0; index < data.length; index += 4) { + if (data[index + 3] === 0) continue; + const red = data[index]; + const green = data[index + 1]; + const blue = data[index + 2]; + const maximum = Math.max(red, green, blue); + const minimum = Math.min(red, green, blue); + const saturation = maximum ? (maximum - minimum) / maximum : 0; + const blueDominance = blue - Math.max(red, green); + // Only the deliberately saturated blue apparel is themed. The gray-blue fur stays intact. + if (blueDominance < 24 || saturation < 0.32) continue; + const [, sourceSaturation, lightness] = rgbToHsl(red, green, blue); + const themed = hslToRgb(targetHue, sourceSaturation, lightness); + [data[index], data[index + 1], data[index + 2]] = themed; + } + context.putImageData(imageData, 0, 0); + return canvas.toDataURL("image/png"); + } + function preset(key, name, aliases, category = "custom", risk = "low", visual = null) { return { key, name, aliases, category, risk, visual }; } @@ -291,6 +364,10 @@ let sharedTwinBand = null; let sharedTwinHome = null; let petTimer = null; + let petBlinkTimer = null; + let petBlinkResetTimer = null; + let petTailTimer = null; + let petTailFrame = null; let petPhraseIndex = 0; function uid(prefix) { @@ -322,12 +399,11 @@ } function initialState() { - const device = clone(DEFAULT_DEVICE); return { version: 5, - devices: [device], - capabilities: seedPresets(device), - selectedDeviceByType: { light: device.id }, + devices: [], + capabilities: [], + selectedDeviceByType: {}, sessionStartedAt: null, settings: { actionDelayMs: 520 }, history: [], @@ -343,6 +419,12 @@ return initialState(); } saved.capabilities = Array.isArray(saved.capabilities) ? saved.capabilities : []; + const removedDefaultDevice = saved.devices.some((item) => item.id === DEFAULT_DEVICE.id); + saved.devices = saved.devices.filter((item) => item.id !== DEFAULT_DEVICE.id); + if (removedDefaultDevice) { + saved.capabilities = saved.capabilities.filter((item) => item.deviceId !== DEFAULT_DEVICE.id); + delete saved.selectedDeviceByType?.light; + } saved.history = Array.isArray(saved.history) ? saved.history : []; saved.vehicleExecutions = saved.vehicleExecutions && typeof saved.vehicleExecutions === "object" ? saved.vehicleExecutions @@ -520,12 +602,14 @@ `; moduleSwitcher.insertAdjacentElement("afterend", root); @@ -1628,8 +1712,340 @@ const pet = $("#extensionDesktopPet"); const body = $("#extensionPetBody"); const bubble = $("#extensionPetBubble"); - const host = $("#v2SelfExtension"); - if (!pet || !body || !bubble || !host) return; + const image = $(".v2-extension-pet-image", body); + const entranceCanvas = $(".v2-extension-pet-entrance-canvas", body); + const tailCanvas = $(".v2-extension-pet-tail-canvas", body); + const mouth = $(".v2-extension-pet-mouth-closed", body); + const entranceContext = entranceCanvas?.getContext("2d"); + const tailContext = tailCanvas?.getContext("2d"); + if (!pet || !body || !bubble || !image || !entranceCanvas || !entranceContext + || !tailCanvas || !tailContext || !mouth) return; + const sourceImage = new Image(); + const entranceSourceImage = new Image(); + const themedEntranceImage = new Image(); + const ENTRANCE_KEYFRAME_COUNT = 12; + const ENTRANCE_CELL_SIZE = 512; + const ENTRANCE_DURATION_MS = 2300; + const ENTRANCE_WALK_END = 0.6; + const ENTRANCE_WALK_STEPS = 5; + const ENTRANCE_SETTLE_START_FRAME = 5; + const ENTRANCE_WALK_POSES = [ + 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, + ]; + let tailWaveQueued = false; + let tailWaveSequenceActive = false; + let tailWaveReplaying = false; + let entranceAnimationFrame = null; + let entranceRequested = document.body.dataset.module === "self-extension"; + let entranceThemeReady = false; + let entranceThemeRevision = 0; + let extensionWasActive = document.body.dataset.module === "self-extension"; + const applyPetTheme = () => { + if (!sourceImage.complete || !sourceImage.naturalWidth) return; + const accent = getComputedStyle(document.body).getPropertyValue("--v2-accent").trim() + || "#0e7773"; + const themedSource = createThemedPetDataUrl(sourceImage, accent); + if (themedSource) image.src = themedSource; + image.dataset.themeRole = "user"; + if (!entranceSourceImage.complete || !entranceSourceImage.naturalWidth) return; + const revision = ++entranceThemeRevision; + entranceThemeReady = false; + const themedEntranceSource = createThemedPetDataUrl(entranceSourceImage, accent); + if (!themedEntranceSource) return; + themedEntranceImage.addEventListener("load", () => { + if (revision !== entranceThemeRevision) return; + entranceThemeReady = true; + if (entranceRequested) playEntrance(); + }, { once: true }); + themedEntranceImage.src = themedEntranceSource; + }; + sourceImage.addEventListener("load", () => applyPetTheme(), { once: true }); + sourceImage.src = image.getAttribute("src"); + entranceSourceImage.addEventListener("load", () => applyPetTheme(), { once: true }); + entranceSourceImage.src = "/assets/pets/self-extension-cat-entrance.png?v=3"; + const tailSourceCanvas = document.createElement("canvas"); + const tailSourceContext = tailSourceCanvas.getContext("2d"); + const tailPoints = [ + [350, 165], [400, 166], [416, 190], [414, 400], [399, 450], [342, 464], + [330, 442], [347, 419], [361, 380], [367, 228], [345, 198], + ]; + const tailMotionFrames = [ + [0, 0, 0, 0, 0, 0], + [0, -5, -11, -7, 7, 17], + [0, -9, -20, -13, 13, 30], + [0, -13, -27, -17, 19, 41], + [0, -16, -32, -19, 24, 48], + [0, -9, -19, -11, 13, 31], + [0, -4, -9, -5, 6, 14], + [0, 0, 0, 0, 0, 0], + [0, 2, 5, 3, -2, -6], + [0, 3, 7, 4, -3, -8], + [0, 1, 3, 2, -1, -3], + [0, 0, 0, 0, 0, 0], + ]; + const interpolateCubic = (before, start, end, after, amount, clampToSegment = false) => { + const amountSquared = amount * amount; + const amountCubed = amountSquared * amount; + const interpolated = 0.5 * ( + (2 * start) + + (-before + end) * amount + + (2 * before - 5 * start + 4 * end - after) * amountSquared + + (-before + 3 * start - 3 * end + after) * amountCubed + ); + if (!clampToSegment) return interpolated; + return Math.max(Math.min(start, end), Math.min(Math.max(start, end), interpolated)); + }; + const getTailPose = (progress) => { + const framePosition = Math.max(0, Math.min(1, progress)) * (tailMotionFrames.length - 1); + const frameIndex = Math.min(tailMotionFrames.length - 2, Math.floor(framePosition)); + const amount = framePosition - frameIndex; + const beforeFrame = tailMotionFrames[Math.max(0, frameIndex - 1)]; + const startFrame = tailMotionFrames[frameIndex]; + const endFrame = tailMotionFrames[frameIndex + 1]; + const afterFrame = tailMotionFrames[Math.min(tailMotionFrames.length - 1, frameIndex + 2)]; + return startFrame.map((offset, index) => interpolateCubic( + beforeFrame[index], offset, endFrame[index], afterFrame[index], amount, true, + )); + }; + const sampleTailOffset = (pose, distanceFromBase) => { + const position = Math.max(0, Math.min(1, distanceFromBase)) * (pose.length - 1); + const index = Math.min(pose.length - 2, Math.floor(position)); + const amount = position - index; + const before = pose[Math.max(0, index - 1)]; + const start = pose[index]; + const end = pose[index + 1]; + const after = pose[Math.min(pose.length - 1, index + 2)]; + return interpolateCubic(before, start, end, after, amount); + }; + const traceTail = (context, scaleX, scaleY) => { + context.beginPath(); + tailPoints.forEach(([x, y], index) => { + const method = index ? "lineTo" : "moveTo"; + context[method](x * scaleX, y * scaleY); + }); + context.closePath(); + }; + const stopTailWave = () => { + window.clearTimeout(petTailTimer); + petTailTimer = null; + if (petTailFrame !== null) window.cancelAnimationFrame(petTailFrame); + petTailFrame = null; + tailWaveQueued = false; + tailWaveSequenceActive = false; + tailWaveReplaying = false; + delete pet.dataset.tailWaving; + tailContext.clearRect(0, 0, tailCanvas.width, tailCanvas.height); + }; + const stopEntrance = () => { + if (entranceAnimationFrame !== null) { + window.cancelAnimationFrame(entranceAnimationFrame); + entranceAnimationFrame = null; + } + delete pet.dataset.entering; + entranceCanvas.style.removeProperty("transform"); + entranceContext.clearRect(0, 0, entranceCanvas.width, entranceCanvas.height); + }; + const drawEntranceKeyframe = (frameIndex) => { + entranceContext.drawImage( + themedEntranceImage, + frameIndex * ENTRANCE_CELL_SIZE, + 0, + ENTRANCE_CELL_SIZE, + ENTRANCE_CELL_SIZE, + 0, + 0, + entranceCanvas.width, + entranceCanvas.height, + ); + }; + const drawEntrancePose = (progress) => { + let activeFrame; + let travelProgress = 1; + let stepBob = 0; + if (progress < ENTRANCE_WALK_END) { + const walkProgress = Math.max(0, progress / ENTRANCE_WALK_END); + const walkStepPosition = walkProgress * ENTRANCE_WALK_STEPS; + const completedSteps = Math.min( + ENTRANCE_WALK_STEPS - 1, + Math.floor(walkStepPosition), + ); + const stepProgress = walkStepPosition - completedSteps; + const easedStepProgress = 0.5 - (Math.cos(Math.PI * stepProgress) / 2); + travelProgress = (completedSteps + easedStepProgress) / ENTRANCE_WALK_STEPS; + stepBob = -Math.sin(Math.PI * stepProgress) * 2.8; + const walkPoseIndex = Math.min( + ENTRANCE_WALK_POSES.length - 1, + Math.round(walkProgress * (ENTRANCE_WALK_POSES.length - 1)), + ); + activeFrame = ENTRANCE_WALK_POSES[walkPoseIndex]; + } else { + const settleProgress = (progress - ENTRANCE_WALK_END) / (1 - ENTRANCE_WALK_END); + activeFrame = ENTRANCE_SETTLE_START_FRAME + Math.round( + settleProgress * (ENTRANCE_KEYFRAME_COUNT - ENTRANCE_SETTLE_START_FRAME - 1), + ); + } + entranceContext.clearRect(0, 0, entranceCanvas.width, entranceCanvas.height); + drawEntranceKeyframe(activeFrame); + return { travelProgress, stepBob }; + }; + function playEntrance() { + if (!entranceRequested || !entranceThemeReady + || document.visibilityState !== "visible" + || document.body.dataset.module !== "self-extension") return; + entranceRequested = false; + stopEntrance(); + stopTailWave(); + delete pet.dataset.blinking; + pet.dataset.mood = "idle"; + pet.dataset.entering = "true"; + const startedAt = performance.now(); + const renderEntrance = (now) => { + if (document.visibilityState !== "visible" + || document.body.dataset.module !== "self-extension") { + stopEntrance(); + return; + } + const progress = Math.min(1, (now - startedAt) / ENTRANCE_DURATION_MS); + const entrancePose = drawEntrancePose(progress); + const horizontalOffset = (1 - entrancePose.travelProgress) * (pet.offsetWidth + 34); + entranceCanvas.style.transform = `translate3d(${horizontalOffset}px, ${entrancePose.stepBob}px, 0)`; + if (progress < 1) { + entranceAnimationFrame = window.requestAnimationFrame(renderEntrance); + return; + } + entranceAnimationFrame = null; + delete pet.dataset.entering; + entranceCanvas.style.removeProperty("transform"); + entranceContext.clearRect(0, 0, entranceCanvas.width, entranceCanvas.height); + if (document.body.dataset.module === "self-extension") { + say("自扩展工作台已就绪", "happy"); + } + }; + entranceAnimationFrame = window.requestAnimationFrame(renderEntrance); + } + const requestEntrance = () => { + entranceRequested = true; + if (entranceThemeReady) playEntrance(); + }; + const drawTailWaveFrame = (progress) => { + if (!image.complete || !image.naturalWidth || !tailSourceContext) return false; + const width = image.naturalWidth; + const height = image.naturalHeight; + if (tailCanvas.width !== width || tailCanvas.height !== height) { + tailCanvas.width = width; + tailCanvas.height = height; + } + if (tailSourceCanvas.width !== width || tailSourceCanvas.height !== height) { + tailSourceCanvas.width = width; + tailSourceCanvas.height = height; + } + const scaleX = width / 512; + const scaleY = height / 512; + const tailTop = 171 * scaleY; + const tailBottom = 459 * scaleY; + const sliceHeight = Math.max(2, Math.round(2 * scaleY)); + tailContext.clearRect(0, 0, width, height); + tailContext.drawImage(image, 0, 0, width, height); + tailContext.save(); + tailContext.globalCompositeOperation = "destination-out"; + traceTail(tailContext, scaleX, scaleY); + tailContext.fill(); + tailContext.lineWidth = 10 * Math.max(scaleX, scaleY); + tailContext.lineJoin = "round"; + tailContext.stroke(); + tailContext.restore(); + tailSourceContext.clearRect(0, 0, width, height); + tailSourceContext.save(); + traceTail(tailSourceContext, scaleX, scaleY); + tailSourceContext.clip(); + tailSourceContext.drawImage(image, 0, 0, width, height); + tailSourceContext.restore(); + const tailPose = getTailPose(progress); + for (let y = tailTop; y < tailBottom; y += sliceHeight) { + const distanceFromBase = (tailBottom - y) / (tailBottom - tailTop); + const offset = sampleTailOffset(tailPose, distanceFromBase) * scaleX; + tailContext.drawImage( + tailSourceCanvas, + 0, y, width, sliceHeight + 1, + offset, y, width, sliceHeight + 1, + ); + } + return true; + }; + const runTailWave = (isReplay = false) => { + petTailTimer = null; + if (document.visibilityState !== "visible" + || document.body.dataset.module !== "self-extension" + || !image.complete + || !drawTailWaveFrame(0)) { + stopTailWave(); + return; + } + const startedAt = performance.now(); + tailWaveSequenceActive = true; + tailWaveReplaying = isReplay; + pet.dataset.tailWaving = "true"; + const renderTailWave = (now) => { + const progress = Math.min(1, (now - startedAt) / 1900); + if (!drawTailWaveFrame(progress)) { + stopTailWave(); + return; + } + if (progress < 1) { + petTailFrame = window.requestAnimationFrame(renderTailWave); + return; + } + petTailFrame = null; + delete pet.dataset.tailWaving; + tailContext.clearRect(0, 0, tailCanvas.width, tailCanvas.height); + if (!tailWaveReplaying && tailWaveQueued) { + tailWaveQueued = false; + tailWaveReplaying = true; + petTailTimer = window.setTimeout(() => runTailWave(true), 180); + return; + } + tailWaveSequenceActive = false; + tailWaveReplaying = false; + tailWaveQueued = false; + }; + petTailFrame = window.requestAnimationFrame(renderTailWave); + }; + const requestTailWave = () => { + if (pet.dataset.entering === "true") return; + if (tailWaveSequenceActive) { + if (!tailWaveReplaying) tailWaveQueued = true; + return; + } + runTailWave(); + }; + const scheduleBlink = (delay = 2800 + Math.random() * 4200) => { + window.clearTimeout(petBlinkTimer); + petBlinkTimer = window.setTimeout(() => { + if (document.visibilityState !== "visible" + || document.body.dataset.module !== "self-extension" + || pet.dataset.entering === "true") { + scheduleBlink(); + return; + } + pet.dataset.blinking = "true"; + window.clearTimeout(petBlinkResetTimer); + petBlinkResetTimer = window.setTimeout(() => { + delete pet.dataset.blinking; + if (Math.random() < 0.22) { + petBlinkTimer = window.setTimeout(() => { + pet.dataset.blinking = "true"; + petBlinkResetTimer = window.setTimeout(() => { + delete pet.dataset.blinking; + scheduleBlink(); + }, 135); + }, 145); + } else { + scheduleBlink(); + } + }, 135); + }, delay); + }; + scheduleBlink(1200 + Math.random() * 1600); const phrases = [ "嗨,我会陪你学习新能力", "拖动我可以换个位置", @@ -1639,26 +2055,58 @@ ]; const pointer = { active: false, moved: false, x: 0, y: 0, startX: 0, startY: 0 }; + const animateMouth = () => { + if (pet.dataset.entering === "true") return; + mouth.getAnimations?.().forEach((animation) => animation.cancel()); + mouth.animate?.( + [ + { opacity: 1, offset: 0 }, + { opacity: 1, offset: 0.06 }, + { opacity: 0, offset: 0.09 }, + { opacity: 0, offset: 0.23 }, + { opacity: 1, offset: 0.26 }, + { opacity: 1, offset: 0.38 }, + { opacity: 0, offset: 0.41 }, + { opacity: 0, offset: 0.55 }, + { opacity: 1, offset: 0.58 }, + { opacity: 1, offset: 0.7 }, + { opacity: 0, offset: 0.73 }, + { opacity: 0, offset: 0.87 }, + { opacity: 1, offset: 0.9 }, + { opacity: 1, offset: 1 }, + ], + { duration: 1260, easing: "linear" }, + ); + }; + const say = (message, mood = "talking") => { bubble.textContent = message; pet.dataset.mood = mood; + animateMouth(); window.clearTimeout(Number(pet.dataset.moodTimer || 0)); pet.dataset.moodTimer = String(window.setTimeout(() => { pet.dataset.mood = "idle"; }, 2600)); }; + pet.addEventListener("pointerenter", () => { + if (pet.dataset.entering === "true") return; + requestTailWave(); + if (pet.dataset.mood === "idle") animateMouth(); + }); + const clampPosition = (x, y) => { - const hostRect = host.getBoundingClientRect(); - const petRect = pet.getBoundingClientRect(); + const edgeMargin = 18; + const maxLeftShift = Math.max(0, window.innerWidth - pet.offsetWidth - edgeMargin * 2); + const maxUpShift = Math.max(0, window.innerHeight - pet.offsetHeight - edgeMargin * 2); return { - x: Math.max(-hostRect.width + petRect.width + 10, Math.min(0, x)), - y: Math.max(-hostRect.height + petRect.height + 10, Math.min(0, y)), + x: Math.max(-maxLeftShift, Math.min(0, x)), + y: Math.max(-maxUpShift, Math.min(0, y)), }; }; body.addEventListener("pointerdown", (event) => { - if (event.button !== 0) return; + if (event.button !== 0 || pet.dataset.entering === "true") return; pointer.active = true; pointer.moved = false; pointer.startX = event.clientX; @@ -1686,7 +2134,8 @@ body.addEventListener("pointerup", endDrag); body.addEventListener("pointercancel", endDrag); body.addEventListener("click", () => { - if (pointer.moved) return; + if (pointer.moved || pet.dataset.entering === "true") return; + requestTailWave(); petPhraseIndex = (petPhraseIndex + 1) % phrases.length; say(phrases[petPhraseIndex], petPhraseIndex % 2 ? "happy" : "talking"); }); @@ -1698,15 +2147,30 @@ pet.style.setProperty("--pet-y", `${position.y}px`); }); window.addEventListener("cognitive-agent:module-change", (event) => { - if (event.detail?.module === "self-extension") say("自扩展工作台已就绪", "happy"); + const extensionIsActive = event.detail?.module === "self-extension"; + const enteredExtension = extensionIsActive && !extensionWasActive; + extensionWasActive = extensionIsActive; + if (enteredExtension) { + requestEntrance(); + } else if (!extensionIsActive) { + entranceRequested = false; + stopEntrance(); + } }); petTimer = window.setInterval(() => { if (document.visibilityState !== "visible" - || document.body.dataset.module !== "self-extension") return; + || document.body.dataset.module !== "self-extension" + || pet.dataset.entering === "true") return; petPhraseIndex = (petPhraseIndex + 1) % phrases.length; say(phrases[petPhraseIndex]); }, 14000); - window.addEventListener("pagehide", () => window.clearInterval(petTimer)); + window.addEventListener("pagehide", () => { + window.clearInterval(petTimer); + window.clearTimeout(petBlinkTimer); + window.clearTimeout(petBlinkResetTimer); + stopEntrance(); + stopTailWave(); + }); } function bindEvents() { @@ -1827,7 +2291,94 @@ }); } + function buildUnifiedExtensionSync() { + const mount = $("#vehicleExtensionSync"); + if (!mount) return false; + let snapshot = null; + + const render = () => { + const health = snapshot?.extension_health || {}; + const physicalConnected = health.transport !== "simulation" + && Boolean(health.connected || health.peer_connected); + const listening = Boolean(health.listening); + const sharedCatalog = Array.isArray(snapshot?.extension?.catalog) + ? snapshot.extension.catalog + : []; + const mergedCatalog = [...sharedCatalog, ...peripheralCatalog()] + .filter((item, index, catalog) => { + const identity = item.id || `${item.device_id}:${item.action}`; + return catalog.findIndex((candidate) => ( + candidate.id || `${candidate.device_id}:${candidate.action}` + ) === identity) === index; + }); + const grouped = new Map(); + mergedCatalog.forEach((item) => { + const deviceId = item.device_id || "external-device"; + if (!grouped.has(deviceId)) grouped.set(deviceId, { + id: deviceId, + name: item.device_name || item.type_label || "USB 扩展设备", + type: item.type_label || item.device_type || "扩展硬件", + actions: [], + }); + grouped.get(deviceId).actions.push(item.action || item.name || "已学习能力"); + }); + const devices = [...grouped.values()]; + const lastAction = snapshot?.extension?.last_action; + const lastResult = snapshot?.extension?.result; + const panelCollapsed = mount.closest("#v2ExtensionPanel")?.classList.contains("is-collapsed") === true; + const statusLabel = physicalConnected + ? "USB 外设已接入" + : devices.length + ? "外设目录已同步" + : health.transport === "simulation" + ? "扩展仿真链路" + : listening + ? "等待 USB 外设接入" + : "扩展链路检查中"; + const statusNote = physicalConnected + ? `${health.peer || "GSCU1B"} · 已同步 ${mergedCatalog.length} 项扩展能力` + : devices.length + ? `车机已同步 ${devices.length} 个外设、${mergedCatalog.length} 项扩展能力` + : health.message || "插入外设后,车机将自动识别并同步到此处"; + mount.dataset.hasDevices = String(devices.length > 0); + mount.innerHTML = ` +
        +
        USB EXTENSION · LIVE

        外设与扩展能力

        + ${statusLabel} + +
        +
        + +
        ${statusLabel}${escapeHtml(statusNote)}
        + ${String(health.transport || "GSCU").toUpperCase()} +
        +
        + ${devices.length ? devices.map((device) => ` +
        +
        ${escapeHtml(device.name)}${escapeHtml(device.type)}
        ${device.actions.length} 项能力
        +
        ${device.actions.slice(0, 8).map((action) => `${escapeHtml(action)}`).join("")}
        +
        `).join("") : ` +
        +
        暂无已识别外设外设名称、类型和已学习能力将由车机同步显示
        +
        `} +
        +
        +
        最近联动${escapeHtml(lastAction?.command || lastAction?.type || "等待外设与车端设备联动")}
        + ${escapeHtml(lastResult?.status || lastResult?.message || "STANDBY")} +
        `; + window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); + }; + + window.addEventListener("cognitive-agent:display-sync", (event) => { + snapshot = event.detail || null; + render(); + }); + render(); + return true; + } + function init() { + if (buildUnifiedExtensionSync()) return; if (!buildShell()) return; initializeDesktopPet(); bindEvents(); diff --git a/apps/web-console/self-repair-seat3d.js b/apps/web-console/self-repair-seat3d.js deleted file mode 100644 index a2897c8..0000000 --- a/apps/web-console/self-repair-seat3d.js +++ /dev/null @@ -1,930 +0,0 @@ -(function () { - "use strict"; - - function viewerHasLayout(viewer) { - const bounds = viewer.getBoundingClientRect(); - return viewer.isConnected && bounds.width >= 2 && bounds.height >= 2; - } - - function deferSeat3dUntilVisible(viewer, options) { - if (viewer.dataset.seat3dPending === "true") return; - viewer.dataset.seat3dPending = "true"; - let observer = null; - const retry = () => { - if (!viewerHasLayout(viewer)) return; - observer?.disconnect(); - window.removeEventListener("resize", scheduleRetry); - window.removeEventListener("cognitive-agent:module-change", scheduleRetry); - delete viewer.dataset.seat3dPending; - initSeat3d(options); - }; - const scheduleRetry = () => window.requestAnimationFrame(retry); - if (window.ResizeObserver) { - observer = new ResizeObserver(retry); - observer.observe(viewer); - } - window.addEventListener("resize", scheduleRetry); - window.addEventListener("cognitive-agent:module-change", scheduleRetry); - scheduleRetry(); - } - - function initSeat3d(options) { - const { - canvasId, - viewerId, - stateEvent, - resetEvent, - initialAxes = [35, 42, 48, 20], - readyClass = "ready", - axisMode = "repair", - enableAxisDrag = false, - labelBindings = null, - } = options; - const THREE = window.THREE; - const canvas = document.getElementById(canvasId); - const viewer = document.getElementById(viewerId); - if (!canvas || !viewer || viewer.dataset.seat3dInitialized === "true") return; - if (!viewerHasLayout(viewer)) { - deferSeat3dUntilVisible(viewer, options); - return; - } - viewer.dataset.seat3dInitialized = "true"; - - const markReady = (fallback = false) => { - viewer.classList.add(readyClass); - if (fallback) viewer.classList.add("fallback"); - }; - - const buildFallback = () => { - const fallback = document.createElement("div"); - fallback.className = "v2-repair-seat-fallback"; - fallback.setAttribute("aria-hidden", "true"); - fallback.innerHTML = ` -
        -
        -
        -
        -
        -
        -
        -
        - `; - viewer.insertBefore(fallback, canvas.nextSibling); - window.addEventListener(stateEvent, (event) => { - const detail = event.detail || {}; - const axes = new Map((detail.axes || []).map((axis) => [Number(axis.motor), Number(axis.position_pct || 0)])); - fallback.style.setProperty("--repair-slide", `${(50 - (axes.get(0) ?? initialAxes[0])) * 0.18}px`); - fallback.style.setProperty("--repair-lift", `${((axes.get(1) ?? initialAxes[1]) - 50) * 0.1}px`); - fallback.style.setProperty("--repair-back", `${-8 - (axes.get(2) ?? initialAxes[2]) * 0.24}deg`); - fallback.style.setProperty("--repair-leg", `${-5 + (axes.get(3) ?? initialAxes[3]) * 0.58}deg`); - fallback.classList.toggle("heating", Number(detail.heatingLevel || 0) > 0); - fallback.classList.toggle("ventilating", Boolean(detail.ventilation)); - fallback.classList.toggle("active", !["IDLE", "PASSED"].includes(detail.state)); - fallback.classList.toggle("failed", detail.state === "FAILED"); - }); - markReady(true); - }; - - if (!THREE) { - buildFallback(); - return; - } - - const themeProbe = document.createElement("div"); - themeProbe.className = "console-v2"; - themeProbe.dataset.demoRole = "admin"; - themeProbe.style.display = "none"; - document.body.append(themeProbe); - const consoleStyles = window.getComputedStyle(themeProbe); - const cssThemeColor = (name, fallback) => { - const value = consoleStyles?.getPropertyValue(name).trim() || fallback; - try { - return new THREE.Color(value); - } catch (_error) { - return new THREE.Color(fallback); - } - }; - const white = new THREE.Color(0xffffff); - const black = new THREE.Color(0x000000); - const themeAccent = cssThemeColor("--v2-accent", "#315eaa"); - const themeStrong = cssThemeColor("--v2-accent-strong", "#234785"); - const themeSoft = cssThemeColor("--v2-accent-soft", "#e1e9fa"); - themeProbe.remove(); - const mixHex = (from, to, amount) => from.clone().lerp(to, amount).getHex(); - - const scene = new THREE.Scene(); - scene.fog = new THREE.Fog(mixHex(themeSoft, white, 0.12), 8, 15); - - let renderer; - try { - renderer = new THREE.WebGLRenderer({ - canvas, - antialias: true, - alpha: true, - powerPreference: "high-performance", - }); - } catch (_error) { - buildFallback(); - return; - } - renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); - renderer.outputEncoding = THREE.sRGBEncoding; - renderer.toneMapping = THREE.ACESFilmicToneMapping; - renderer.toneMappingExposure = 0.92; - renderer.shadowMap.enabled = true; - renderer.shadowMap.type = THREE.PCFSoftShadowMap; - - const camera = new THREE.PerspectiveCamera(33, 1, 0.05, 40); - const target = new THREE.Vector3(0, 1.15, 0); - const orbit = { yaw: 0.67, pitch: 0.21, distance: 6.8 }; - const pointer = { - active: false, - x: 0, - y: 0, - startX: 0, - startY: 0, - startValue: 0, - axis: null, - mode: "orbit", - moved: false, - dragVector: { x: 1, y: 0 }, - dragSource: "model", - }; - - scene.add(new THREE.HemisphereLight(0xffffff, mixHex(themeStrong, white, 0.46), 1.35)); - const keyLight = new THREE.DirectionalLight(0xffffff, 1.8); - keyLight.position.set(-4, 7, 6); - keyLight.castShadow = true; - keyLight.shadow.mapSize.set(1024, 1024); - scene.add(keyLight); - - const fillLight = new THREE.DirectionalLight(mixHex(themeAccent, white, 0.42), 0.72); - fillLight.position.set(5, 3, -4); - scene.add(fillLight); - - const floor = new THREE.Mesh( - new THREE.CircleGeometry(4.8, 80), - new THREE.MeshStandardMaterial({ color: mixHex(themeSoft, white, 0.18), roughness: 0.94 }), - ); - floor.rotation.x = -Math.PI / 2; - floor.position.y = -0.16; - floor.receiveShadow = true; - scene.add(floor); - - const grid = new THREE.GridHelper(8, 20, themeAccent.getHex(), mixHex(themeAccent, white, 0.7)); - grid.position.y = -0.153; - grid.material.transparent = true; - grid.material.opacity = 0.14; - scene.add(grid); - - const seatShell = new THREE.MeshPhysicalMaterial({ - color: mixHex(themeStrong, black, 0.06), - roughness: 0.54, - metalness: 0.02, - clearcoat: 0.16, - clearcoatRoughness: 0.7, - emissive: mixHex(themeStrong, black, 0.64), - emissiveIntensity: 0.08, - }); - const seatInsert = new THREE.MeshPhysicalMaterial({ - color: mixHex(themeAccent, white, 0.48), - roughness: 0.72, - metalness: 0, - clearcoat: 0.06, - emissive: 0x000000, - emissiveIntensity: 0, - }); - const thermalInsert = seatInsert.clone(); - const bolsterMaterial = new THREE.MeshStandardMaterial({ - color: themeAccent.getHex(), - roughness: 0.76, - emissive: 0x000000, - emissiveIntensity: 0, - }); - const structureMaterial = new THREE.MeshStandardMaterial({ - color: mixHex(themeStrong, black, 0.34), - roughness: 0.62, - metalness: 0.35, - }); - const railMaterial = new THREE.MeshStandardMaterial({ color: 0x7b8798, roughness: 0.42, metalness: 0.72 }); - const edgeMaterial = new THREE.LineBasicMaterial({ - color: mixHex(themeStrong, black, 0.38), - transparent: true, - opacity: 0.3, - }); - const seamMaterial = new THREE.LineBasicMaterial({ - color: mixHex(themeAccent, white, 0.42), - transparent: true, - opacity: 0.72, - }); - const axisHitTargets = []; - - function markAxisTarget(object, axis) { - if (!object || !Number.isInteger(axis)) return object; - object.traverse((child) => { - if (!child.isMesh) return; - child.userData.calibrationAxis = axis; - axisHitTargets.push(child); - }); - return object; - } - - function addEdges(mesh, geometry, opacity = 0.3) { - const material = edgeMaterial.clone(); - material.opacity = opacity; - mesh.add(new THREE.LineSegments(new THREE.EdgesGeometry(geometry, 38), material)); - } - - function makeBox(parent, size, position, material) { - const geometry = new THREE.BoxGeometry(...size); - const mesh = new THREE.Mesh(geometry, material); - mesh.position.set(...position); - mesh.castShadow = true; - mesh.receiveShadow = true; - addEdges(mesh, geometry, 0.26); - parent.add(mesh); - return mesh; - } - - function makePanel(parent, shape, depth, position, rotation, material) { - const geometry = new THREE.ExtrudeGeometry(shape, { - depth, - steps: 1, - curveSegments: 20, - bevelEnabled: true, - bevelSegments: 4, - bevelSize: 0.045, - bevelThickness: 0.04, - }); - geometry.translate(0, 0, -depth / 2); - geometry.computeVertexNormals(); - const mesh = new THREE.Mesh(geometry, material); - mesh.position.set(...position); - mesh.rotation.set(...rotation); - mesh.castShadow = true; - mesh.receiveShadow = true; - addEdges(mesh, geometry); - parent.add(mesh); - return mesh; - } - - function cushionShape(inset = 0) { - const shape = new THREE.Shape(); - const half = 0.69 - inset; - shape.moveTo(-0.52 + inset, 0.61 - inset); - shape.quadraticCurveTo(-half, 0.55 - inset, -half, 0.34); - shape.lineTo(-half + 0.025, -0.39 + inset); - shape.quadraticCurveTo(-half + 0.02, -0.61 + inset, -0.48 + inset, -0.68 + inset); - shape.quadraticCurveTo(0, -0.77 + inset, 0.48 - inset, -0.68 + inset); - shape.quadraticCurveTo(half - 0.02, -0.61 + inset, half - 0.025, -0.39 + inset); - shape.lineTo(half, 0.34); - shape.quadraticCurveTo(half, 0.55 - inset, 0.52 - inset, 0.61 - inset); - shape.quadraticCurveTo(0, 0.68 - inset, -0.52 + inset, 0.61 - inset); - return shape; - } - - function backrestShape(inset = 0) { - const shape = new THREE.Shape(); - const half = 0.7 - inset; - shape.moveTo(-0.52 + inset, 0); - shape.quadraticCurveTo(-half, 0.08, -half, 0.34); - shape.lineTo(-half + 0.035, 1.28 - inset); - shape.quadraticCurveTo(-half + 0.06, 1.52 - inset, -0.46 + inset, 1.65 - inset); - shape.quadraticCurveTo(0, 1.82 - inset, 0.46 - inset, 1.65 - inset); - shape.quadraticCurveTo(half - 0.06, 1.52 - inset, half - 0.035, 1.28 - inset); - shape.lineTo(half, 0.34); - shape.quadraticCurveTo(half, 0.08, 0.52 - inset, 0); - shape.quadraticCurveTo(0, -0.08 + inset, -0.52 + inset, 0); - return shape; - } - - function makeSeam(parent, points) { - const geometry = new THREE.BufferGeometry().setFromPoints(points.map((point) => new THREE.Vector3(...point))); - parent.add(new THREE.Line(geometry, seamMaterial)); - } - - const seatRoot = new THREE.Group(); - seatRoot.rotation.y = -0.38; - seatRoot.position.set(0, 0.02, 0); - scene.add(seatRoot); - - const leftRail = makeBox(seatRoot, [0.11, 0.08, 2.65], [-0.48, 0.12, 0], railMaterial); - const rightRail = makeBox(seatRoot, [0.11, 0.08, 2.65], [0.48, 0.12, 0], railMaterial); - markAxisTarget(leftRail, 0); - markAxisTarget(rightRail, 0); - makeBox(seatRoot, [1.15, 0.07, 0.13], [0, 0.15, -0.92], structureMaterial); - makeBox(seatRoot, [1.15, 0.07, 0.13], [0, 0.15, 0.92], structureMaterial); - - const slideRoot = new THREE.Group(); - seatRoot.add(slideRoot); - const base = new THREE.Mesh(new THREE.CapsuleGeometry(0.47, 0.5, 6, 18), structureMaterial); - base.rotation.x = Math.PI / 2; - base.scale.set(1.42, 1, 0.55); - base.position.set(0, 0.34, -0.02); - base.castShadow = true; - slideRoot.add(base); - markAxisTarget(base, 3); - - const cushionPivot = new THREE.Group(); - cushionPivot.position.set(0, 0.57, 0.06); - slideRoot.add(cushionPivot); - makePanel(cushionPivot, cushionShape(), 0.22, [0, 0, 0.08], [-Math.PI / 2, 0, 0], seatShell); - makePanel(cushionPivot, cushionShape(0.16), 0.055, [0, 0.145, 0.03], [-Math.PI / 2, 0, 0], thermalInsert); - [-1, 1].forEach((side) => { - const wing = new THREE.Mesh(new THREE.CapsuleGeometry(0.105, 0.86, 5, 12), bolsterMaterial); - wing.rotation.x = Math.PI / 2; - wing.position.set(side * 0.61, 0.17, 0.08); - wing.castShadow = true; - cushionPivot.add(wing); - }); - makeSeam(cushionPivot, [[-0.28, 0.181, 0.5], [-0.22, 0.181, 0.08], [-0.28, 0.181, -0.42]]); - makeSeam(cushionPivot, [[0.28, 0.181, 0.5], [0.22, 0.181, 0.08], [0.28, 0.181, -0.42]]); - markAxisTarget(cushionPivot, 3); - - const backrestPivot = new THREE.Group(); - backrestPivot.position.set(0, 0.62, -0.5); - backrestPivot.rotation.x = -0.09; - slideRoot.add(backrestPivot); - makePanel(backrestPivot, backrestShape(), 0.3, [0, 0, 0], [0, 0, 0], seatShell); - makePanel(backrestPivot, backrestShape(0.16), 0.07, [0, 0.04, 0.19], [0, 0, 0], thermalInsert); - [-1, 1].forEach((side) => { - const wing = new THREE.Mesh(new THREE.CapsuleGeometry(0.115, 1.2, 6, 14), bolsterMaterial); - wing.position.set(side * 0.61, 0.78, 0.18); - wing.scale.set(1, 1, 0.72); - wing.castShadow = true; - backrestPivot.add(wing); - }); - makeSeam(backrestPivot, [[-0.28, 0.2, 0.232], [-0.22, 0.83, 0.232], [-0.32, 1.46, 0.232]]); - makeSeam(backrestPivot, [[0.28, 0.2, 0.232], [0.22, 0.83, 0.232], [0.32, 1.46, 0.232]]); - makeSeam(backrestPivot, [[-0.32, 0.86, 0.234], [0, 0.78, 0.234], [0.32, 0.86, 0.234]]); - makeBox(backrestPivot, [0.045, 0.42, 0.045], [-0.24, 1.74, 0], railMaterial); - makeBox(backrestPivot, [0.045, 0.42, 0.045], [0.24, 1.74, 0], railMaterial); - const headrest = new THREE.Mesh(new THREE.CapsuleGeometry(0.31, 0.3, 8, 18), seatShell); - headrest.scale.set(1.35, 1, 0.5); - headrest.position.set(0, 1.98, 0.01); - headrest.castShadow = true; - backrestPivot.add(headrest); - const headrestInsert = new THREE.Mesh(new THREE.CapsuleGeometry(0.245, 0.23, 8, 18), seatInsert); - headrestInsert.scale.set(1.32, 1, 0.28); - headrestInsert.position.set(0, 1.98, 0.18); - backrestPivot.add(headrestInsert); - markAxisTarget(backrestPivot, 2); - - const legrestPivot = new THREE.Group(); - legrestPivot.position.set(0, 0.64, 0.7); - legrestPivot.rotation.x = 0.1; - slideRoot.add(legrestPivot); - const legShell = makePanel(legrestPivot, cushionShape(0.08), 0.18, [0, 0, 0.36], [-Math.PI / 2, 0, 0], seatShell); - legShell.scale.set(0.9, 0.72, 0.54); - const legInsert = makePanel(legrestPivot, cushionShape(0.2), 0.045, [0, 0.12, 0.4], [-Math.PI / 2, 0, 0], seatInsert); - legInsert.scale.set(0.92, 0.74, 0.56); - markAxisTarget(legrestPivot, 1); - - const labelAnchors = { - longitudinal: new THREE.Object3D(), - height: new THREE.Object3D(), - backrest: new THREE.Object3D(), - legrest: new THREE.Object3D(), - }; - labelAnchors.longitudinal.position.set(0.62, 0.16, 0.78); - slideRoot.add(labelAnchors.longitudinal); - labelAnchors.height.position.set(-0.72, 0.34, -0.08); - slideRoot.add(labelAnchors.height); - labelAnchors.backrest.position.set(0.62, 1.16, 0.2); - backrestPivot.add(labelAnchors.backrest); - labelAnchors.legrest.position.set(-0.48, 0.14, 0.42); - legrestPivot.add(labelAnchors.legrest); - - const statusHalo = new THREE.Mesh( - new THREE.RingGeometry(1.12, 1.18, 72), - new THREE.MeshBasicMaterial({ - color: themeAccent.getHex(), - transparent: true, - opacity: 0.12, - side: THREE.DoubleSide, - depthWrite: false, - }), - ); - statusHalo.position.set(0, 1.35, -0.35); - statusHalo.renderOrder = 2; - seatRoot.add(statusHalo); - - const palettes = { - normal: { - shell: mixHex(themeStrong, black, 0.06), - insert: mixHex(themeAccent, white, 0.48), - bolster: themeAccent.getHex(), - emissive: mixHex(themeStrong, black, 0.7), - }, - working: { - shell: themeAccent.getHex(), - insert: mixHex(themeAccent, white, 0.58), - bolster: mixHex(themeAccent, themeStrong, 0.38), - emissive: mixHex(themeAccent, black, 0.54), - }, - passed: { - shell: themeStrong.getHex(), - insert: mixHex(themeAccent, white, 0.52), - bolster: themeAccent.getHex(), - emissive: mixHex(themeStrong, black, 0.62), - }, - failed: { shell: 0x7a3f43, insert: 0xc97a78, bolster: 0x85494c, emissive: 0x4a100d }, - }; - - const current = { axes: [...initialAxes], ventilation: false, heating: 0, active: false, state: "IDLE" }; - const desired = { axes: [...initialAxes], ventilation: false, heating: 0, active: false, state: "IDLE" }; - const labelLines = labelBindings?.lineRoot - ? document.querySelector(labelBindings.lineRoot) - : null; - const labelAxisByName = { longitudinal: 0, legrest: 1, backrest: 2, height: 3 }; - const labelLayout = labelBindings - ? Object.entries(labelBindings.items || {}).map(([name, binding]) => ({ - name, - axis: labelAxisByName[name], - side: binding.side === "left" ? "left" : "right", - yOffset: Number(binding.yOffset || 0), - anchor: labelAnchors[name], - tag: document.querySelector(binding.selector), - line: labelLines?.querySelector(`[data-seat-label-line="${name}"]`) || null, - })).filter((item) => item.anchor && item.tag) - : []; - const projected = new THREE.Vector3(); - const worldPoint = new THREE.Vector3(); - - function setLabelHidden(item, hidden) { - item.tag.dataset.hidden = String(hidden); - if (item.line) item.line.dataset.hidden = String(hidden); - } - - function layoutSeatLabels() { - if (!labelLayout.length || !viewerHasLayout(viewer)) return; - const width = viewer.clientWidth; - const height = viewer.clientHeight; - const margin = 10; - const gap = 8; - const lanes = { left: [], right: [] }; - - labelLayout.forEach((item) => { - item.anchor.getWorldPosition(worldPoint); - projected.copy(worldPoint).project(camera); - const visible = projected.z >= -1 && projected.z <= 1; - if (!visible) { - setLabelHidden(item, true); - return; - } - const anchorX = (projected.x * 0.5 + 0.5) * width; - const anchorY = (-projected.y * 0.5 + 0.5) * height; - const tagWidth = Math.max(54, item.tag.offsetWidth); - const tagHeight = Math.max(20, item.tag.offsetHeight); - const desiredLeft = item.side === "left" - ? anchorX - tagWidth - 44 - : anchorX + 44; - lanes[item.side].push({ - ...item, - anchorX, - anchorY, - tagWidth, - tagHeight, - left: Math.max(margin, Math.min(width - tagWidth - margin, desiredLeft)), - desiredTop: Math.max( - margin, - Math.min(height - tagHeight - margin, anchorY - tagHeight / 2 + item.yOffset), - ), - }); - setLabelHidden(item, false); - }); - - Object.values(lanes).forEach((lane) => { - lane.sort((a, b) => a.desiredTop - b.desiredTop); - let cursor = margin; - lane.forEach((item) => { - item.top = Math.max(item.desiredTop, cursor); - cursor = item.top + item.tagHeight + gap; - }); - const overflow = cursor - gap + margin - height; - if (overflow > 0) lane.forEach((item) => { item.top -= overflow; }); - cursor = margin; - lane.forEach((item) => { - item.top = Math.max(cursor, Math.min(height - item.tagHeight - margin, item.top)); - cursor = item.top + item.tagHeight + gap; - }); - - lane.forEach((item) => { - item.tag.style.transform = `translate3d(${item.left.toFixed(1)}px, ${item.top.toFixed(1)}px, 0)`; - if (!item.line) return; - const endX = item.side === "left" ? item.left + item.tagWidth : item.left; - const endY = item.top + item.tagHeight / 2; - item.line.setAttribute("x1", item.anchorX.toFixed(1)); - item.line.setAttribute("y1", item.anchorY.toFixed(1)); - item.line.setAttribute("x2", endX.toFixed(1)); - item.line.setAttribute("y2", endY.toFixed(1)); - }); - }); - } - - function setActiveAxis(axis) { - labelLayout.forEach((item) => { - item.tag.classList.toggle("active", item.axis === axis); - }); - } - - function updateCamera() { - const cosPitch = Math.cos(orbit.pitch); - camera.position.set( - target.x + Math.sin(orbit.yaw) * cosPitch * orbit.distance, - target.y + Math.sin(orbit.pitch) * orbit.distance, - target.z + Math.cos(orbit.yaw) * cosPitch * orbit.distance, - ); - camera.lookAt(target); - viewer.dataset.orbitYaw = orbit.yaw.toFixed(3); - viewer.dataset.orbitPitch = orbit.pitch.toFixed(3); - } - - function resetOrbit() { - const aspect = Math.max(0.55, viewer.clientWidth / Math.max(1, viewer.clientHeight)); - orbit.yaw = 0.67; - orbit.pitch = 0.21; - orbit.distance = 6.8 * Math.max(1, Math.min(1.3, 0.78 / aspect)); - updateCamera(); - } - - function resize() { - const width = Math.max(1, viewer.clientWidth); - const height = Math.max(1, viewer.clientHeight); - const pixelRatio = Math.min(window.devicePixelRatio || 1, 2); - renderer.setPixelRatio(pixelRatio); - renderer.setSize(width, height, false); - camera.aspect = width / height; - camera.updateProjectionMatrix(); - } - - let viewerWasVisible = false; - function synchronizeViewport({ reset = false } = {}) { - if (!viewerHasLayout(viewer)) { - viewerWasVisible = false; - return false; - } - resize(); - if (reset || !viewerWasVisible) resetOrbit(); - viewerWasVisible = true; - return true; - } - - const scheduleViewportSync = () => { - window.requestAnimationFrame(() => window.requestAnimationFrame(() => { - synchronizeViewport(); - })); - }; - - function onHealingState(event) { - const detail = event.detail || {}; - (detail.axes || []).forEach((axis) => { - const motor = Number(axis.motor); - if (pointer.active && pointer.mode === "axis" - && axisToModelIndex[pointer.axis] === motor) return; - if (motor >= 0 && motor < desired.axes.length) { - desired.axes[motor] = Math.max(0, Math.min(100, Number(axis.position_pct || 0))); - } - }); - desired.ventilation = Boolean(detail.ventilation); - desired.heating = Math.max(0, Math.min(3, Number(detail.heatingLevel || 0))); - desired.active = !["IDLE", "PASSED"].includes(detail.state); - desired.state = String(detail.state || "IDLE"); - statusHalo.material.color.setHex(detail.state === "FAILED" ? 0xc94d51 : themeAccent.getHex()); - } - - function animate() { - window.requestAnimationFrame(animate); - if (!viewerHasLayout(viewer) || canvas.dataset.contextLost === "true") { - viewerWasVisible = false; - return; - } - if (!viewerWasVisible) synchronizeViewport({ reset: true }); - for (let index = 0; index < current.axes.length; index += 1) { - current.axes[index] += (desired.axes[index] - current.axes[index]) * 0.055; - } - current.heating += (desired.heating - current.heating) * 0.05; - current.ventilation = desired.ventilation; - current.active = desired.active; - current.state = desired.state; - - slideRoot.position.z = THREE.MathUtils.mapLinear(current.axes[0], 0, 100, -0.46, 0.46); - if (axisMode === "calibration") { - slideRoot.position.y = THREE.MathUtils.mapLinear(current.axes[1], 0, 100, -0.12, 0.16); - cushionPivot.rotation.x = 0; - } else { - slideRoot.position.y = 0; - cushionPivot.rotation.x = THREE.MathUtils.mapLinear(current.axes[1], 0, 100, -0.08, 0.16); - } - backrestPivot.rotation.x = THREE.MathUtils.mapLinear(current.axes[2], 0, 100, 0.16, -0.44); - legrestPivot.rotation.x = THREE.MathUtils.mapLinear(current.axes[3], 0, 100, 0.08, -0.68); - - const paletteName = current.state === "FAILED" - ? "failed" - : current.state === "PASSED" - ? "passed" - : current.active - ? "working" - : "normal"; - const palette = palettes[paletteName]; - seatShell.color.lerp(new THREE.Color(palette.shell), 0.09); - seatInsert.color.lerp(new THREE.Color(palette.insert), 0.09); - thermalInsert.color.lerp(new THREE.Color(palette.insert), 0.09); - bolsterMaterial.color.lerp(new THREE.Color(palette.bolster), 0.09); - - const heatRatio = current.heating / 3; - seatShell.emissive.lerp(new THREE.Color(heatRatio > 0 ? 0x8e2f18 : palette.emissive), 0.08); - seatShell.emissiveIntensity = 0.08 + heatRatio * 0.42; - thermalInsert.emissive.lerp(new THREE.Color(current.ventilation ? themeAccent.getHex() : palette.emissive), 0.08); - thermalInsert.emissiveIntensity = current.ventilation ? 0.32 : 0.06; - bolsterMaterial.emissive.lerp(new THREE.Color(palette.emissive), 0.08); - bolsterMaterial.emissiveIntensity = current.active ? 0.12 : 0.04; - statusHalo.rotation.z += current.active ? 0.006 : 0.0015; - statusHalo.material.opacity = current.state === "FAILED" - ? 0.2 + Math.sin(performance.now() * 0.005) * 0.06 - : current.active - ? 0.12 + Math.sin(performance.now() * 0.005) * 0.04 - : 0.06; - - scene.updateMatrixWorld(true); - layoutSeatLabels(); - renderer.render(scene, camera); - } - - const raycaster = new THREE.Raycaster(); - const rayPointer = new THREE.Vector2(); - const axisToModelIndex = { 0: 0, 1: 3, 2: 2, 3: 1 }; - const labelNameByAxis = { 0: "longitudinal", 1: "legrest", 2: "backrest", 3: "height" }; - const fallbackDragVectors = { - 0: { x: 1, y: 0 }, - 1: { x: -0.7, y: -0.7 }, - 2: { x: 0.8, y: 0.6 }, - 3: { x: 0, y: -1 }, - }; - - function applyAxisModelPose(axis, value) { - if (axis === 0) { - slideRoot.position.z = THREE.MathUtils.mapLinear(value, 0, 100, -0.46, 0.46); - } else if (axis === 1) { - legrestPivot.rotation.x = THREE.MathUtils.mapLinear(value, 0, 100, 0.08, -0.68); - } else if (axis === 2) { - backrestPivot.rotation.x = THREE.MathUtils.mapLinear(value, 0, 100, 0.16, -0.44); - } else if (axis === 3 && axisMode === "calibration") { - slideRoot.position.y = THREE.MathUtils.mapLinear(value, 0, 100, -0.12, 0.16); - } - } - - function projectAxisAnchor(anchor) { - anchor.getWorldPosition(worldPoint); - projected.copy(worldPoint).project(camera); - return { - x: (projected.x * 0.5 + 0.5) * viewer.clientWidth, - y: (-projected.y * 0.5 + 0.5) * viewer.clientHeight, - }; - } - - function calculateAxisDragVector(axis, value) { - const anchor = labelAnchors[labelNameByAxis[axis]]; - if (!anchor) return fallbackDragVectors[axis]; - const low = Math.max(0, value - 8); - const high = Math.min(100, value + 8); - if (high - low < 1) return fallbackDragVectors[axis]; - const saved = { - slideY: slideRoot.position.y, - slideZ: slideRoot.position.z, - backrestX: backrestPivot.rotation.x, - legrestX: legrestPivot.rotation.x, - }; - applyAxisModelPose(axis, low); - scene.updateMatrixWorld(true); - const start = projectAxisAnchor(anchor); - applyAxisModelPose(axis, high); - scene.updateMatrixWorld(true); - const end = projectAxisAnchor(anchor); - slideRoot.position.y = saved.slideY; - slideRoot.position.z = saved.slideZ; - backrestPivot.rotation.x = saved.backrestX; - legrestPivot.rotation.x = saved.legrestX; - scene.updateMatrixWorld(true); - const dx = end.x - start.x; - const dy = end.y - start.y; - const length = Math.hypot(dx, dy); - return length > 0.5 - ? { x: dx / length, y: dy / length } - : fallbackDragVectors[axis]; - } - - function startAxisDrag(axis, event, source = "model") { - if (!enableAxisDrag || viewer.dataset.axisControlEnabled !== "true" - || !Number.isInteger(axis)) return false; - event.preventDefault(); - event.stopPropagation(); - pointer.active = true; - pointer.x = event.clientX; - pointer.y = event.clientY; - pointer.startX = event.clientX; - pointer.startY = event.clientY; - pointer.moved = false; - pointer.axis = axis; - pointer.mode = "axis"; - pointer.dragSource = source; - const modelIndex = axisToModelIndex[axis]; - pointer.startValue = desired.axes[modelIndex]; - pointer.dragVector = calculateAxisDragVector(axis, pointer.startValue); - viewer.dataset.dragAxis = String(axis); - viewer.dataset.axisDragSource = source; - viewer.classList.add("axis-dragging"); - viewer.classList.remove("axis-hover"); - labelLayout.forEach((item) => { - item.tag.classList.toggle("dragging", source === "label" && item.axis === axis); - }); - setActiveAxis(axis); - return true; - } - - function axisAtPoint(clientX, clientY) { - if (!enableAxisDrag || viewer.dataset.axisControlEnabled !== "true") return null; - const bounds = viewer.getBoundingClientRect(); - if (clientX < bounds.left || clientX > bounds.right - || clientY < bounds.top || clientY > bounds.bottom) return null; - rayPointer.set( - ((clientX - bounds.left) / Math.max(1, bounds.width)) * 2 - 1, - -((clientY - bounds.top) / Math.max(1, bounds.height)) * 2 + 1, - ); - raycaster.setFromCamera(rayPointer, camera); - const hit = raycaster.intersectObjects(axisHitTargets, false)[0]; - return Number.isInteger(hit?.object?.userData?.calibrationAxis) - ? hit.object.userData.calibrationAxis - : null; - } - - function updateAxisHover(event) { - if (pointer.active) return; - const axis = axisAtPoint(event.clientX, event.clientY); - viewer.classList.toggle("axis-hover", axis !== null); - if (axis === null) delete viewer.dataset.hoverAxis; - else viewer.dataset.hoverAxis = String(axis); - setActiveAxis(axis); - } - - viewer.addEventListener("pointermove", updateAxisHover); - viewer.addEventListener("pointerleave", () => { - if (pointer.active) return; - viewer.classList.remove("axis-hover"); - delete viewer.dataset.hoverAxis; - setActiveAxis(null); - }); - viewer.addEventListener("pointerdown", (event) => { - if (event.button !== 0) return; - const axis = axisAtPoint(event.clientX, event.clientY); - if (axis !== null && startAxisDrag(axis, event)) return; - event.preventDefault(); - pointer.active = true; - pointer.x = event.clientX; - pointer.y = event.clientY; - pointer.startX = event.clientX; - pointer.startY = event.clientY; - pointer.moved = false; - pointer.axis = null; - pointer.mode = "orbit"; - pointer.dragSource = "model"; - viewer.classList.add("dragging"); - }); - labelLayout.forEach((item) => { - item.tag.dataset.axis = String(item.axis); - item.tag.addEventListener("pointerdown", (event) => { - if (event.button !== 0) return; - startAxisDrag(item.axis, event, "label"); - }); - item.tag.addEventListener("pointerenter", () => { - if (!pointer.active && viewer.dataset.axisControlEnabled === "true") { - setActiveAxis(item.axis); - } - }); - item.tag.addEventListener("pointerleave", () => { - if (!pointer.active) setActiveAxis(null); - }); - item.tag.addEventListener("keydown", (event) => { - if (viewer.dataset.axisControlEnabled !== "true") return; - const direction = ["ArrowRight", "ArrowUp"].includes(event.key) - ? 1 - : ["ArrowLeft", "ArrowDown"].includes(event.key) ? -1 : 0; - if (!direction) return; - event.preventDefault(); - const modelIndex = axisToModelIndex[item.axis]; - const value = Math.max(0, Math.min(100, desired.axes[modelIndex] + direction * 2.5)); - desired.axes[modelIndex] = value; - const detail = { axis: item.axis, permille: Math.round(value * 10) }; - window.dispatchEvent(new CustomEvent("calibration-seat-axis-preview", { detail })); - window.dispatchEvent(new CustomEvent("calibration-seat-axis-commit", { detail })); - }); - }); - window.addEventListener("pointermove", (event) => { - if (!pointer.active) return; - event.preventDefault(); - const totalX = event.clientX - pointer.startX; - const totalY = event.clientY - pointer.startY; - pointer.moved ||= Math.hypot(totalX, totalY) > 3; - if (pointer.mode === "axis") { - const delta = ( - totalX * pointer.dragVector.x + totalY * pointer.dragVector.y - ) * 0.55; - const value = Math.max(0, Math.min(100, pointer.startValue + delta)); - desired.axes[axisToModelIndex[pointer.axis]] = value; - window.dispatchEvent(new CustomEvent("calibration-seat-axis-preview", { - detail: { axis: pointer.axis, permille: Math.round(value * 10) }, - })); - return; - } - orbit.yaw -= (event.clientX - pointer.x) * 0.008; - orbit.pitch = Math.max(-0.08, Math.min(0.72, orbit.pitch + (event.clientY - pointer.y) * 0.006)); - pointer.x = event.clientX; - pointer.y = event.clientY; - updateCamera(); - }, { passive: false }); - const endOrbit = () => { - if (pointer.active && pointer.mode === "axis" && pointer.moved) { - const value = desired.axes[axisToModelIndex[pointer.axis]]; - window.dispatchEvent(new CustomEvent("calibration-seat-axis-commit", { - detail: { axis: pointer.axis, permille: Math.round(value * 10) }, - })); - } - pointer.active = false; - pointer.axis = null; - pointer.mode = "orbit"; - pointer.dragSource = "model"; - delete viewer.dataset.dragAxis; - delete viewer.dataset.axisDragSource; - viewer.classList.remove("dragging"); - viewer.classList.remove("axis-dragging"); - labelLayout.forEach((item) => item.tag.classList.remove("dragging")); - setActiveAxis(null); - }; - window.addEventListener("pointerup", endOrbit); - window.addEventListener("pointercancel", endOrbit); - window.addEventListener("blur", endOrbit); - viewer.addEventListener("wheel", (event) => { - event.preventDefault(); - orbit.distance = Math.max(5.1, Math.min(10, orbit.distance + event.deltaY * 0.003)); - updateCamera(); - }, { passive: false }); - viewer.addEventListener("dblclick", resetOrbit); - window.addEventListener(stateEvent, onHealingState); - window.addEventListener(resetEvent, resetOrbit); - - if (window.ResizeObserver) { - const resizeObserver = new ResizeObserver(() => synchronizeViewport()); - resizeObserver.observe(viewer); - } - window.addEventListener("resize", scheduleViewportSync); - window.addEventListener("cognitive-agent:module-change", scheduleViewportSync); - canvas.addEventListener("webglcontextlost", (event) => { - event.preventDefault(); - canvas.dataset.contextLost = "true"; - viewer.classList.add("context-lost"); - }); - canvas.addEventListener("webglcontextrestored", () => { - delete canvas.dataset.contextLost; - viewer.classList.remove("context-lost"); - synchronizeViewport({ reset: true }); - }); - synchronizeViewport({ reset: true }); - animate(); - window.requestAnimationFrame(() => markReady()); - - } - - function init() { - initSeat3d({ - canvasId: "repairSeatCanvas", - viewerId: "repairSeatViewer", - stateEvent: "seat-healing-state", - resetEvent: "self-repair-seat-reset", - }); - initSeat3d({ - canvasId: "calibrationSeatCanvas", - viewerId: "calibrationSeatViewer", - stateEvent: "calibration-seat-state", - resetEvent: "self-calibration-seat-reset", - initialAxes: [50, 50, 20, 0], - readyClass: "is-ready", - axisMode: "calibration", - enableAxisDrag: true, - labelBindings: { - lineRoot: "#calibrationSeatLabelLines", - items: { - backrest: { selector: '[data-seat-axis-label="backrest"]', side: "right", yOffset: -28 }, - longitudinal: { selector: '[data-seat-axis-label="longitudinal"]', side: "right", yOffset: 24 }, - legrest: { selector: '[data-seat-axis-label="legrest"]', side: "left", yOffset: 24 }, - height: { selector: '[data-seat-axis-label="height"]', side: "left", yOffset: -18 }, - }, - }, - }); - } - - if (document.readyState === "complete") { - init(); - } else { - document.addEventListener("DOMContentLoaded", init, { once: true }); - } -}()); diff --git a/apps/web-console/self-repair.css b/apps/web-console/self-repair.css deleted file mode 100644 index 8688001..0000000 --- a/apps/web-console/self-repair.css +++ /dev/null @@ -1,1390 +0,0 @@ -/* Seat self-repair workspace --------------------------------------------- */ - -.console-v2[data-module="self-repair"] { - --repair-deep-blue: var(--v2-accent-strong); - --repair-active-blue: color-mix(in srgb, var(--v2-accent) 58%, white); - --repair-pending: #a7b0b4; - --repair-warn: #d69738; - --repair-danger: #c45656; - --repair-heading: color-mix(in srgb, var(--v2-accent-strong) 78%, #1f2c33); - --repair-ink: color-mix(in srgb, var(--v2-accent-strong) 24%, #34434b); - --repair-muted: color-mix(in srgb, var(--v2-accent) 18%, #748185); - --repair-soft: color-mix(in srgb, var(--v2-accent-soft) 42%, white); - --repair-soft-strong: color-mix(in srgb, var(--v2-accent-soft) 72%, white); - --repair-surface: rgba(255, 255, 255, 0.9); - --repair-line: color-mix(in srgb, var(--v2-accent) 15%, transparent); -} - -.console-v2[data-module="self-repair"] .section-kicker { - color: var(--v2-accent); -} - -.console-v2 .v2-repair-sidebar, -.console-v2 .v2-repair-footer, -.console-v2 .v2-self-repair { - display: none; -} - -.console-v2[data-module="self-repair"] .v2-control-section, -.console-v2[data-module="self-repair"] .v2-config-section, -.console-v2[data-module="self-repair"] .v2-sidebar > .v2-sidebar-footer:not(.v2-repair-footer), -.console-v2[data-module="self-repair"] .v2-operation-shell, -.console-v2[data-module="self-repair"] .v2-output-shell { - display: none; -} - -.console-v2[data-module="self-repair"] .v2-role-select .v2-dropdown-trigger { - pointer-events: none; -} - -.console-v2[data-module="self-repair"] .v2-role-select .v2-dropdown-caret { - display: none; -} - -.console-v2[data-module="self-repair"] .v2-repair-sidebar { - min-height: 0; - display: flex; - flex: 1; - flex-direction: column; - margin-top: clamp(22px, 3.5vh, 42px); - overflow: hidden; -} - -.console-v2[data-module="self-repair"] .v2-repair-footer { - display: grid; -} - -.console-v2.v2-sidebar-collapsed[data-module="self-repair"] .v2-repair-sidebar, -.console-v2.v2-sidebar-collapsed[data-module="self-repair"] .v2-repair-footer { - display: none; -} - -.console-v2[data-module="self-repair"] .main-panel { - grid-template-rows: 36px minmax(0, 1fr); -} - -.console-v2[data-module="self-repair"] .v2-self-repair { - min-width: 0; - min-height: 0; - display: grid; - grid-row: 2; - grid-template-rows: auto minmax(0, 1fr); - gap: 11px; - padding: var(--v2-module-title-block) 0 0; - overflow: hidden; -} - -.v2-repair-sidebar > .v2-field-caption { - display: block; - margin: 0 0 8px; - color: var(--repair-muted); - font-size: 13px; - font-weight: 750; -} - -.v2-repair-view-switch { - display: grid; - gap: 7px; -} - -.v2-repair-view-switch button { - min-height: var(--v2-sidebar-item-height); - display: grid; - grid-template-columns: 30px minmax(0, 1fr); - align-items: center; - gap: 10px; - padding: 6px 15px; - color: color-mix(in srgb, var(--v2-accent-strong) 56%, #65787a); - background: transparent; - border: 1px solid transparent; - border-radius: 13px; - text-align: left; - cursor: pointer; - transition: 160ms ease; -} - -.v2-repair-view-switch button:hover { - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 34%, white); - border-color: color-mix(in srgb, var(--v2-accent) 10%, white); -} - -.v2-repair-view-switch button.active { - color: #111f20; - background: rgba(255, 255, 255, 0.94); - border-color: color-mix(in srgb, var(--v2-accent) 18%, white); - box-shadow: 0 10px 28px color-mix(in srgb, var(--v2-accent) 10%, transparent); -} - -.v2-repair-view-switch button > svg { - width: 19px; - height: 19px; - justify-self: center; - color: color-mix(in srgb, var(--v2-accent) 76%, #718486); -} - -.v2-repair-view-switch button.active > svg { - color: var(--v2-accent); -} - -.v2-repair-view-switch button > span { - min-width: 0; - display: grid; - gap: 2px; -} - -.v2-repair-view-switch strong, -.v2-repair-view-switch small { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-view-switch strong { - font-size: 15px; - line-height: 1.2; -} - -.v2-repair-view-switch small { - color: color-mix(in srgb, var(--v2-accent) 34%, #829092); - font-size: 9px; - font-weight: 600; -} - -.v2-repair-view-switch button.active small { - color: color-mix(in srgb, var(--v2-accent-strong) 62%, #829092); -} - -.v2-repair-config-stack { - display: grid; - gap: 8px; - padding-left: 9px; - border-left: 1px solid color-mix(in srgb, var(--v2-accent) 14%, transparent); -} - -.v2-repair-config-card { - min-width: 0; - min-height: var(--v2-sidebar-card-height); - display: grid; - grid-template-columns: 28px minmax(0, 1fr) auto; - align-items: center; - gap: 8px; - padding: 6px 8px; - color: var(--repair-ink); - background: rgba(255, 255, 255, 0.72); - border: 1px solid rgba(255, 255, 255, 0.78); - border-radius: var(--v2-sidebar-card-radius); -} - -.v2-repair-config-card > svg { - width: 17px; - height: 17px; - color: var(--v2-accent); -} - -.v2-repair-config-card > div { - min-width: 0; - display: grid; - gap: 1px; -} - -.v2-repair-config-card small { - color: var(--repair-muted); - font-size: 8px; - font-weight: 650; -} - -.v2-repair-config-card strong { - overflow: hidden; - color: var(--repair-heading); - margin-top: 2px; - font-size: 11px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-config-card > span { - padding: 3px 5px; - color: var(--v2-accent-strong); - background: color-mix(in srgb, var(--v2-accent-soft) 68%, white); - border-radius: 5px; - font: 800 7px/1.1 "IBM Plex Mono", Consolas, monospace; -} - -.repair-execution-card .v2-config-card-select, -.repair-execution-card .v2-custom-select { - min-width: 0; -} - -.repair-execution-card .v2-dropdown-trigger { - min-height: 18px; - padding: 0; - color: var(--repair-heading); - background: transparent; - border: 0; - font-size: 11px; - font-weight: 800; - box-shadow: none; -} - -.v2-repair-config-note { - margin: 8px 2px 0; - color: var(--repair-muted); - font-size: 10px; - line-height: 1.45; -} - -.v2-repair-heading { - min-width: 0; - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: start; - gap: 16px; - margin-inline: var(--v2-module-title-inline); - padding: 0; -} - -.v2-repair-heading h1 { - margin: 2px 0 2px; - color: var(--v2-accent-strong); - font-size: clamp(21px, 2vw, 30px); - line-height: 1; - letter-spacing: -0.045em; -} - -.v2-repair-heading p { - margin: 0; - color: var(--repair-muted); - font-size: 11px; -} - -.v2-repair-status-grid { - display: grid; - grid-template-columns: repeat(3, minmax(105px, 1fr)); - gap: 7px; -} - -.v2-repair-status-grid > div { - min-width: 0; - min-height: 43px; - display: grid; - grid-template-columns: 8px minmax(0, 1fr); - align-items: center; - gap: 7px; - padding: 7px 10px; - background: rgba(255, 255, 255, 0.7); - border: 1px solid var(--repair-line); - border-radius: 12px; -} - -.v2-repair-status-grid i { - width: 7px; - height: 7px; - border-radius: 50%; - background: #a8b3b3; - box-shadow: 0 0 0 3px rgba(132, 150, 150, 0.09); -} - -.v2-repair-status-grid i[data-state="online"] { - background: #2aa694; - box-shadow: 0 0 0 3px rgba(42, 166, 148, 0.12); -} - -.v2-repair-status-grid i[data-state="working"] { - background: var(--repair-active-blue); - box-shadow: 0 0 0 3px rgba(115, 166, 232, 0.15); -} - -.v2-repair-status-grid span { - min-width: 0; - display: grid; -} - -.v2-repair-status-grid small { - color: var(--repair-muted); - font-size: 8px; -} - -.v2-repair-status-grid strong { - overflow: hidden; - color: var(--repair-ink); - font-size: 11px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-view { - min-width: 0; - min-height: 0; - display: grid; - grid-template-rows: auto minmax(0, 1fr); - gap: 9px; - overflow: hidden; -} - -.v2-repair-view[hidden] { - display: none; -} - -.v2-repair-toolbar { - min-width: 0; - min-height: 52px; - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; - padding: 8px 11px; - background: rgba(255, 255, 255, 0.66); - border: 1px solid var(--repair-line); - border-radius: 14px; -} - -.v2-repair-toolbar > div:first-child { - min-width: 0; - display: flex; - align-items: center; - gap: 10px; -} - -.v2-repair-toolbar > div:first-child > span { - color: var(--v2-accent); - font: 800 11px "IBM Plex Mono", Consolas, monospace; -} - -.v2-repair-toolbar h2, -.v2-repair-toolbar p { - margin: 0; -} - -.v2-repair-toolbar h2 { - color: var(--repair-heading); - font-size: 16px; -} - -.v2-repair-toolbar p { - overflow: hidden; - color: var(--repair-muted); - font-size: 9px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-toolbar > div:last-child { - display: flex; - align-items: center; - justify-content: flex-end; - gap: 6px; -} - -.v2-repair-toolbar button { - min-height: 32px; - display: inline-flex; - align-items: center; - gap: 5px; - padding: 0 10px; - color: var(--repair-ink); - background: rgba(255, 255, 255, 0.86); - border: 1px solid var(--repair-line); - border-radius: 10px; - font-size: 10px; - font-weight: 750; - cursor: pointer; - transition: color 160ms ease, background 160ms ease, border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease; -} - -.v2-repair-toolbar button svg { - width: 13px; - height: 13px; -} - -.v2-repair-toolbar button:hover:not(:disabled) { - color: var(--v2-accent-strong); - border-color: color-mix(in srgb, var(--v2-accent) 30%, white); - transform: translateY(-1px); -} - -.v2-repair-toolbar button.primary { - color: #fff; - background: linear-gradient(145deg, var(--v2-accent), var(--v2-accent-strong)); - border-color: color-mix(in srgb, var(--v2-accent-strong) 74%, transparent); - box-shadow: 0 7px 16px color-mix(in srgb, var(--v2-accent) 21%, transparent); -} - -.v2-repair-toolbar button.primary:hover:not(:disabled) { - color: #fff; - background: linear-gradient(145deg, color-mix(in srgb, var(--v2-accent) 86%, white), var(--v2-accent-strong)); - border-color: var(--v2-accent-strong); - box-shadow: 0 10px 22px color-mix(in srgb, var(--v2-accent) 30%, transparent); -} - -.v2-repair-toolbar button.primary:active:not(:disabled) { - color: #fff; - background: var(--v2-accent-strong); - box-shadow: 0 3px 9px color-mix(in srgb, var(--v2-accent) 24%, transparent); - transform: translateY(0); -} - -.v2-repair-toolbar button.danger { - color: #a63f47; - background: #fff0f1; - border-color: #efc4c7; - box-shadow: none; -} - -.v2-repair-toolbar button:focus-visible { - outline: 2px solid color-mix(in srgb, var(--v2-accent) 42%, white); - outline-offset: 2px; -} - -.v2-repair-toolbar button:disabled { - cursor: not-allowed; - opacity: 0.48; -} - -.v2-repair-toolbar button.primary:disabled { - color: color-mix(in srgb, var(--v2-accent-strong) 42%, white); - background: var(--v2-accent-soft); - border-color: color-mix(in srgb, var(--v2-accent) 16%, white); - box-shadow: none; - opacity: 1; -} - -.v2-repair-software-grid { - min-width: 0; - min-height: 0; - display: grid; - grid-template-areas: "twin cases logs"; - grid-template-columns: minmax(280px, 1.18fr) minmax(210px, 0.72fr) minmax(360px, 1.4fr); - gap: 9px; - overflow: hidden; -} - -.v2-repair-panel { - min-width: 0; - min-height: 0; - overflow: hidden; - background: var(--repair-surface); - border: 1px solid var(--repair-line); - border-radius: 16px; - box-shadow: 0 12px 32px color-mix(in srgb, var(--v2-accent) 7%, transparent); -} - -.v2-repair-panel > header { - min-height: 49px; - display: flex; - align-items: center; - justify-content: space-between; - gap: 10px; - padding: 9px 12px; - border-bottom: 1px solid var(--repair-line); -} - -.v2-repair-panel > header h2, -.v2-repair-panel > header p { - margin: 0; -} - -.v2-repair-panel > header h2 { - color: var(--repair-heading); - font-size: 14px; -} - -.v2-repair-panel > header b { - color: var(--v2-accent-strong); - font: 800 10px "IBM Plex Mono", Consolas, monospace; -} - -.v2-repair-cases-panel { - grid-area: cases; - display: grid; - grid-template-rows: auto auto minmax(0, 1fr) auto; -} - -.v2-repair-injection-note { - margin: 9px 10px 6px; - padding: 8px 9px; - color: var(--repair-muted); - background: color-mix(in srgb, var(--v2-accent-soft) 66%, white); - border-radius: 9px; - font-size: 8px; - line-height: 1.5; -} - -.v2-repair-case-list { - min-height: 0; - display: grid; - align-content: start; - gap: 6px; - padding: 0 10px 8px; - overflow: auto; -} - -.v2-repair-case-list button { - min-width: 0; - min-height: 51px; - display: grid; - grid-template-columns: 29px minmax(0, 1fr) 7px; - align-items: center; - gap: 8px; - padding: 7px 9px; - color: var(--repair-ink); - background: var(--repair-soft); - border: 1px solid transparent; - border-radius: 12px; - text-align: left; - cursor: pointer; -} - -.v2-repair-case-list button.selected { - background: color-mix(in srgb, var(--v2-accent-soft) 76%, white); - border-color: color-mix(in srgb, var(--v2-accent) 72%, white); - box-shadow: none; -} - -.v2-repair-case-list button > span { - color: var(--v2-accent-strong); - font: 800 12px "IBM Plex Mono", Consolas, monospace; -} - -.v2-repair-case-list button > div { - min-width: 0; - display: grid; - gap: 2px; -} - -.v2-repair-case-list strong, -.v2-repair-case-list small { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-case-list strong { - font-size: 11px; -} - -.v2-repair-case-list small { - color: var(--repair-muted); - font-size: 8px; -} - -.v2-repair-case-list button > i { - width: 7px; - height: 7px; - border-radius: 50%; - background: var(--repair-pending); -} - -.v2-repair-case-list button[data-state="active"] > i { background: var(--repair-active-blue); } -.v2-repair-case-list button[data-state="complete"] > i { background: var(--repair-deep-blue); } -.v2-repair-case-list button[data-state="failed"] > i { background: var(--repair-danger); } - -.v2-repair-injection-footer { - display: grid; - gap: 6px; - padding: 9px 10px 10px; - border-top: 1px solid var(--repair-line); -} - -.v2-repair-injection-footer small, -.v2-repair-injection-footer > span { - overflow: hidden; - color: var(--repair-muted); - font-size: 8px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-injection-footer > span { - padding: 6px 7px; - color: #9a6428; - background: #fff4e7; - border-radius: 7px; - text-align: center; -} - -.v2-repair-injection-footer button { - min-height: 34px; - display: inline-flex; - align-items: center; - justify-content: center; - gap: 6px; - color: #fff; - background: linear-gradient(145deg, var(--v2-accent), var(--v2-accent-strong)); - border: 1px solid var(--v2-accent-strong); - border-radius: 9px; - font-size: 10px; - font-weight: 750; - cursor: pointer; -} - -.v2-repair-injection-footer button svg { width: 13px; height: 13px; } -.v2-repair-injection-footer button:disabled { color: var(--repair-muted); background: var(--repair-soft); border-color: var(--repair-line); cursor: not-allowed; } - -.v2-repair-twin-panel, -.v2-repair-log-panel { - display: grid; - grid-template-rows: auto minmax(0, 1fr); -} - -.v2-repair-twin-panel { grid-area: twin; } -.v2-repair-log-panel { - grid-area: logs; - grid-template-rows: auto auto auto minmax(0, 1fr); -} - -.v2-repair-seat-viewer { - min-height: 0; - position: relative; - overflow: hidden; - cursor: grab; - touch-action: none; - user-select: none; - background: - radial-gradient(circle at 52% 38%, rgba(255, 255, 255, 0.95), transparent 34%), - linear-gradient(150deg, color-mix(in srgb, var(--v2-accent-soft) 42%, white), color-mix(in srgb, var(--v2-accent-soft) 76%, #dfe7ef)); -} - -.v2-repair-seat-viewer.dragging { - cursor: grabbing; -} - -#repairSeatCanvas { - width: 100%; - height: 100%; - display: block; - pointer-events: none; -} - -.v2-repair-orbit-hint, -.v2-repair-twin-live { - pointer-events: none; -} - -.v2-repair-seat-viewer.fallback #repairSeatCanvas { visibility: hidden; } - -.v2-repair-seat-fallback { - --repair-slide: 2px; - --repair-lift: -1px; - --repair-back: -20deg; - --repair-leg: 7deg; - position: absolute; - inset: 5px 8px 72px; - display: grid; - place-items: center; - perspective: 680px; -} - -.repair-css-seat { - width: 164px; - height: 250px; - position: relative; - filter: drop-shadow(20px 24px 18px color-mix(in srgb, var(--v2-accent-strong) 22%, transparent)); - transform: translate3d(0, var(--repair-lift), 0) rotateX(4deg) rotateY(-23deg); - transform-style: preserve-3d; - transition: transform 360ms ease; -} - -.repair-css-seat > div { - position: absolute; - border: 1px solid color-mix(in srgb, var(--v2-accent-strong) 22%, transparent); - box-shadow: inset -9px -8px 14px color-mix(in srgb, var(--v2-accent-strong) 16%, transparent), inset 8px 6px 15px rgba(255, 255, 255, 0.55); - transform-style: preserve-3d; -} - -.repair-css-back { - width: 104px; - height: 128px; - top: 38px; - left: 31px; - z-index: 3; - overflow: hidden; - background: linear-gradient(145deg, color-mix(in srgb, var(--v2-accent-soft) 76%, white), color-mix(in srgb, var(--v2-accent) 58%, white)); - border-radius: 34px 34px 23px 23px; - transform: rotateX(var(--repair-back)); - transform-origin: 50% 100%; - transition: transform 360ms ease; -} - -.repair-css-back::before, -.repair-css-cushion::before { - position: absolute; - inset: 13px 19px; - content: ""; - background: repeating-linear-gradient(105deg, color-mix(in srgb, var(--v2-accent) 22%, transparent) 0 2px, transparent 2px 10px); - border: 1px solid rgba(255, 255, 255, 0.25); - border-radius: 24px; -} - -.repair-css-back i, -.repair-css-cushion i { - position: absolute; - inset: 0; - background: radial-gradient(circle at 48% 44%, color-mix(in srgb, var(--v2-accent) 34%, transparent), transparent 43%); - opacity: 0; - transition: opacity 260ms ease; -} - -.repair-css-headrest { - width: 68px; - height: 45px; - top: 0; - left: 49px; - z-index: 4; - background: linear-gradient(145deg, color-mix(in srgb, var(--v2-accent-soft) 72%, white), color-mix(in srgb, var(--v2-accent) 54%, white)); - border-radius: 25px 25px 18px 18px; -} - -.repair-css-headrest::before, -.repair-css-headrest::after { - width: 4px; - height: 20px; - position: absolute; - bottom: -16px; - content: ""; - background: color-mix(in srgb, var(--v2-accent-strong) 64%, #83909b); -} - -.repair-css-headrest::before { left: 20px; } -.repair-css-headrest::after { right: 20px; } - -.repair-css-cushion { - width: 126px; - height: 75px; - top: 152px; - left: 20px; - z-index: 4; - overflow: hidden; - background: linear-gradient(150deg, color-mix(in srgb, var(--v2-accent-soft) 74%, white), color-mix(in srgb, var(--v2-accent) 56%, white)); - border-radius: 25px 25px 31px 31px; - transform: translateZ(23px) translateY(var(--repair-lift)) rotateX(65deg) translateZ(10px); - transition: transform 360ms ease; -} - -.repair-css-cushion::before { inset: 10px 20px; } - -.repair-css-legrest { - width: 85px; - height: 63px; - top: 202px; - left: 40px; - z-index: 2; - background: linear-gradient(160deg, color-mix(in srgb, var(--v2-accent-soft) 68%, white), color-mix(in srgb, var(--v2-accent-strong) 58%, white)); - border-radius: 17px 17px 25px 25px; - transform: rotateX(var(--repair-leg)) translateZ(8px); - transform-origin: 50% 0; - transition: transform 360ms ease; -} - -.repair-css-base { - width: 103px; - height: 30px; - top: 207px; - left: 31px; - z-index: 1; - background: var(--v2-accent-strong); - border-radius: 8px 8px 17px 17px; - transform: translate3d(0, 17px, -28px); -} - -.repair-css-rails { - width: 130px; - height: 38px; - top: 233px; - left: 17px; - border: 0 !important; - box-shadow: none !important; - transform: translateX(var(--repair-slide)); - transition: transform 360ms ease; -} - -.repair-css-rails i { - width: 9px; - height: 78px; - position: absolute; - top: -25px; - background: linear-gradient(color-mix(in srgb, var(--v2-accent) 36%, #a6afb7), var(--v2-accent-strong)); - border-radius: 5px; - transform: rotateX(70deg); -} - -.repair-css-rails i:first-child { left: 26px; } -.repair-css-rails i:last-child { right: 26px; } - -.repair-css-halo { - width: 225px; - height: 75px; - position: absolute; - bottom: 2px; - border: 2px solid color-mix(in srgb, var(--v2-accent) 30%, transparent); - border-radius: 50%; - box-shadow: 0 0 25px color-mix(in srgb, var(--v2-accent) 16%, transparent); -} - -.v2-repair-seat-fallback.active .repair-css-halo { animation: repair-halo 1.4s ease-in-out infinite; } -.v2-repair-seat-fallback.failed .repair-css-halo { border-color: rgba(201, 77, 81, 0.7); } -.v2-repair-seat-fallback.heating .repair-css-back i, -.v2-repair-seat-fallback.heating .repair-css-cushion i { background: radial-gradient(circle, rgba(241, 131, 69, 0.52), transparent 55%); opacity: 1; } -.v2-repair-seat-fallback.ventilating .repair-css-back i, -.v2-repair-seat-fallback.ventilating .repair-css-cushion i { opacity: 1; } - -@keyframes repair-halo { - 50% { opacity: 0.46; transform: scale(1.08); } -} - -.v2-repair-model-loading { - position: absolute; - inset: 0; - z-index: 2; - display: grid; - place-content: center; - place-items: center; - gap: 5px; - color: var(--repair-heading); - background: color-mix(in srgb, var(--v2-accent-soft) 76%, rgba(255, 255, 255, 0.9)); - transition: opacity 240ms ease, visibility 240ms ease; -} - -.v2-repair-seat-viewer.ready .v2-repair-model-loading { - visibility: hidden; - opacity: 0; -} - -.v2-repair-model-loading > span { - width: 24px; - height: 24px; - border: 2px solid color-mix(in srgb, var(--v2-accent) 20%, transparent); - border-top-color: var(--v2-accent); - border-radius: 50%; - animation: repair-spin 800ms linear infinite; -} - -.v2-repair-model-loading strong { font-size: 12px; } -.v2-repair-model-loading small { color: var(--repair-muted); font-size: 8px; } - -@keyframes repair-spin { to { transform: rotate(360deg); } } - -.v2-repair-orbit-hint { - position: absolute; - top: 9px; - left: 50%; - padding: 5px 8px; - color: #fff; - background: color-mix(in srgb, var(--v2-accent-strong) 76%, transparent); - border-radius: 7px; - font-size: 8px; - transform: translateX(-50%); - white-space: nowrap; -} - -.v2-repair-twin-live { - position: absolute; - right: 8px; - bottom: 8px; - left: 8px; - padding: 8px; - color: #f2f6ff; - background: color-mix(in srgb, var(--v2-accent-strong) 88%, rgba(13, 28, 49, 0.9)); - border: 1px solid rgba(255, 255, 255, 0.14); - border-radius: 12px; - backdrop-filter: blur(8px); -} - -.v2-repair-twin-live > div:first-child { - min-width: 0; - display: grid; - grid-template-columns: auto minmax(0, 1fr) auto; - align-items: center; - gap: 7px; -} - -.v2-repair-twin-live small, -.v2-repair-twin-live b { - padding: 3px 5px; - border-radius: 6px; - font-size: 7px; - white-space: nowrap; -} - -.v2-repair-twin-live small { background: color-mix(in srgb, var(--v2-accent) 32%, transparent); } -.v2-repair-twin-live strong { overflow: hidden; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; } -.v2-repair-twin-live b { color: #ffe4a9; background: rgba(196, 137, 45, 0.22); } - -#repairAxisStrip { - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 5px; - margin-top: 7px; -} - -#repairAxisStrip > span { - min-width: 0; - display: grid; - grid-template-columns: auto minmax(10px, 1fr) auto; - align-items: center; - gap: 3px; - font-size: 7px; -} - -#repairAxisStrip i { - height: 3px; - position: relative; - overflow: hidden; - background: rgba(255, 255, 255, 0.18); - border-radius: 999px; -} - -#repairAxisStrip i::after { - width: var(--position); - height: 100%; - display: block; - content: ""; - background: var(--repair-active-blue); -} - -#repairAxisStrip > span.active i::after { background: #a9c8ff; } -#repairAxisStrip em { font-style: normal; } - -#repairTwinReaction { - margin: 6px 0 0; - overflow: hidden; - color: #c9d8ef; - font-size: 7px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-log-panel > header > b { - padding: 6px 10px; - border-radius: 999px; - font-size: 11px; -} - -.v2-repair-log-panel > header h2 { font-size: 16px; } - -.v2-repair-log-panel > header > b[data-state="healthy"] { color: #19805e; background: #e6f6ef; } -.v2-repair-log-panel > header > b[data-state="repairing"] { color: #a86a1f; background: #fff2de; } -.v2-repair-log-panel > header > b[data-state="fault"] { color: #ad4248; background: #fdebed; } -.v2-repair-log-panel > header > b[data-state="idle"] { color: var(--repair-muted); background: var(--repair-soft); } - -.v2-repair-log-summary { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 6px; - padding: 9px 10px; - border-bottom: 1px solid var(--repair-line); -} - -.v2-repair-log-summary > div { - min-width: 0; - padding: 9px 10px; - background: var(--repair-soft); - border-radius: 9px; -} - -.v2-repair-log-summary small { display: block; overflow: hidden; color: var(--repair-muted); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; } -.v2-repair-log-summary strong { display: block; margin-top: 5px; color: var(--repair-heading); font: 800 15px "IBM Plex Mono", Consolas, monospace; } - -.v2-repair-log-toolbar { - min-height: 44px; - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - padding: 5px 10px; - border-bottom: 1px solid var(--repair-line); -} - -.v2-repair-log-toolbar > div { display: flex; gap: 3px; } -.v2-repair-log-toolbar button { padding: 6px 9px; color: var(--repair-muted); background: transparent; border: 0; border-radius: 7px; font-size: 10px; font-weight: 750; cursor: pointer; } -.v2-repair-log-toolbar button.active { color: var(--v2-accent-strong); background: var(--v2-accent-soft); } -.v2-repair-log-toolbar > span { display: inline-flex; align-items: center; gap: 6px; color: var(--repair-muted); font-size: 9px; white-space: nowrap; } -.v2-repair-log-toolbar > span i { width: 7px; height: 7px; background: #26916d; border-radius: 50%; } - -.v2-repair-event-stream { - min-height: 0; - padding: 4px 10px 10px; - overflow: auto; -} - -.v2-repair-event-stream article { - min-height: 88px; - position: relative; - display: grid; - grid-template-columns: 78px 14px minmax(0, 1fr); - gap: 8px; - padding: 11px 0; - border-bottom: 1px solid var(--repair-line); -} - -.v2-repair-event-stream article > time { padding-top: 3px; color: var(--repair-muted); font: 9px "IBM Plex Mono", Consolas, monospace; } -.v2-repair-event-stream article > i { width: 11px; height: 11px; z-index: 1; margin-top: 3px; background: var(--v2-accent); border: 2px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px var(--repair-line); } -.v2-repair-event-stream article:not(:last-child)::after { width: 1px; position: absolute; top: 27px; bottom: -2px; left: 91px; content: ""; background: var(--repair-line); } -.v2-repair-event-stream article[data-kind="fault"] > i { background: var(--repair-danger); } -.v2-repair-event-stream article[data-kind="diagnosis"] > i, -.v2-repair-event-stream article[data-kind="repair"] > i { background: var(--repair-warn); } -.v2-repair-event-stream article[data-kind="success"] > i, -.v2-repair-event-stream article[data-kind="heartbeat"] > i { background: #248b67; } -.v2-repair-event-stream article > div { min-width: 0; } -.v2-repair-event-stream article header { min-height: 21px; display: flex; align-items: center; gap: 8px; padding: 0; border: 0; } -.v2-repair-event-stream article header span { padding: 3px 5px; color: var(--repair-muted); background: var(--repair-soft); border-radius: 5px; font-size: 9px; font-weight: 750; } -.v2-repair-event-stream article header strong { overflow: hidden; color: var(--repair-ink); font-size: 13px; text-overflow: ellipsis; white-space: nowrap; } -.v2-repair-event-stream article[data-kind="fault"] header strong { color: var(--repair-danger); } -.v2-repair-event-stream article[data-kind="diagnosis"] header strong, -.v2-repair-event-stream article[data-kind="repair"] header strong { color: #a7681d; } -.v2-repair-event-stream article[data-kind="success"] header strong, -.v2-repair-event-stream article[data-kind="heartbeat"] header strong { color: #197c5c; } -.v2-repair-event-stream article p { margin: 5px 0 0; color: var(--repair-muted); font-size: 10px; line-height: 1.55; } -.v2-repair-event-stream article footer { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 6px; } -.v2-repair-event-stream article footer span { padding: 3px 6px; color: var(--repair-muted); background: var(--repair-soft); border-radius: 5px; font-size: 9px; } - -.v2-repair-log-empty { height: 100%; display: grid; place-content: center; justify-items: center; gap: 6px; padding: 24px; color: var(--repair-muted); text-align: center; } -.v2-repair-log-empty svg { width: 24px; height: 24px; color: var(--v2-accent); } -.v2-repair-log-empty strong { color: var(--repair-ink); font-size: 14px; } -.v2-repair-log-empty span { max-width: 280px; font-size: 10px; line-height: 1.6; } - -.v2-repair-view[data-repair-page="hardware"] { - overflow: auto; - grid-template-rows: auto minmax(120px, auto) minmax(360px, 1fr); -} - -.v2-repair-link-panel > header p { - max-width: 45%; - overflow: hidden; - color: var(--repair-muted); - font-size: 9px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-link-layers { - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 1px; - padding: 8px 10px 4px; -} - -.v2-repair-link-layers > div { - min-width: 0; - position: relative; - display: grid; - gap: 3px; - padding: 7px 10px; - background: var(--repair-soft); -} - -.v2-repair-link-layers > div:not(:last-child)::after { - position: absolute; - top: 50%; - right: -4px; - z-index: 1; - content: "→"; - color: #879495; - transform: translateY(-50%); -} - -.v2-repair-link-layers small { color: var(--repair-muted); font-size: 8px; } -.v2-repair-link-layers strong { overflow: hidden; color: var(--repair-ink); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; } -.v2-repair-link-layers [data-state="OK"] strong { color: #238879; } -.v2-repair-link-layers [data-state="WARN"] strong { color: #b1782d; } - -#repairLinkDetail { - margin: 1px 11px 8px; - color: var(--repair-muted); - font-size: 8px; -} - -.v2-repair-hardware-grid { - min-width: 0; - min-height: 0; - display: grid; - grid-template-columns: minmax(190px, 0.66fr) minmax(500px, 1.58fr) minmax(210px, 0.72fr); - gap: 9px; -} - -.v2-repair-groups-panel, -.v2-repair-connectors-panel, -.v2-repair-pin-panel { - display: grid; - grid-template-rows: auto minmax(0, 1fr); -} - -#repairHardwareGroups { - min-height: 0; - display: grid; - align-content: start; - gap: 6px; - padding: 9px; - overflow: auto; -} - -#repairHardwareGroups button { - min-width: 0; - display: grid; - grid-template-columns: 3px minmax(0, 1fr) auto; - align-items: center; - gap: 8px; - padding: 8px; - color: var(--repair-ink); - background: var(--repair-soft); - border: 0; - border-radius: 10px; - text-align: left; -} - -#repairHardwareGroups button > i { - width: 3px; - height: 100%; - min-height: 28px; - background: #a7b2b2; - border-radius: 999px; -} - -#repairHardwareGroups button[data-state="OK"] > i { background: #2b9e8d; } -#repairHardwareGroups button[data-state="WARN"] > i { background: var(--repair-warn); } -#repairHardwareGroups button[data-state="FAULT"] > i { background: var(--repair-danger); } -#repairHardwareGroups button > div { min-width: 0; display: grid; gap: 2px; } -#repairHardwareGroups strong, -#repairHardwareGroups small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -#repairHardwareGroups strong { font-size: 9px; } -#repairHardwareGroups small { color: var(--repair-muted); font-size: 7px; } -#repairHardwareGroups span { color: var(--repair-muted); font-size: 7px; } - -.v2-repair-connectors-panel > header { - min-height: 58px; -} - -.v2-repair-pin-legend { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; - gap: 3px 5px; - color: var(--repair-muted); - font-size: 7px; -} - -.v2-repair-pin-legend span { - width: 7px; - height: 7px; - display: inline-block; - border-radius: 2px; - background: #aeb8b9; -} - -.v2-repair-pin-legend span[data-state="OK"] { background: #2b9e8d; } -.v2-repair-pin-legend span[data-state="IDLE"] { background: var(--repair-active-blue); } -.v2-repair-pin-legend span[data-state="WARN"] { background: var(--repair-warn); } -.v2-repair-pin-legend span[data-state="FAULT"] { background: var(--repair-danger); } - -#repairConnectors { - min-height: 0; - display: grid; - grid-template-columns: 0.82fr 0.88fr 1.15fr; - gap: 8px; - padding: 9px; - overflow: auto; -} - -.v2-repair-connector { - min-width: 0; - min-height: 0; - display: grid; - grid-template-rows: auto minmax(0, 1fr); - padding: 7px; - background: var(--repair-soft); - border: 1px solid var(--repair-line); - border-radius: 11px; -} - -.v2-repair-connector > header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 5px; - margin-bottom: 5px; -} - -.v2-repair-connector > header strong { color: var(--repair-heading); font-size: 10px; } -.v2-repair-connector > header span { color: var(--repair-muted); font-size: 6px; } - -.v2-repair-connector-body { - min-height: 0; - position: relative; - padding: 4px; - border: 1px solid color-mix(in srgb, var(--v2-accent) 18%, #aeb9ba); - border-radius: 3px; -} - -.v2-repair-connector-body > div { - height: 100%; - display: grid; - align-content: space-between; - gap: 2px; -} - -.v2-repair-connector-body > div > span { - min-width: 0; - display: grid; - grid-template-columns: 1fr 1fr; - gap: 3px; -} - -.v2-repair-connector-body button { - min-width: 0; - min-height: 18px; - display: grid; - grid-template-columns: 20px minmax(0, 1fr); - align-items: center; - gap: 2px; - padding: 1px 3px; - overflow: hidden; - color: var(--repair-ink); - background: var(--repair-soft-strong); - border: 1px solid transparent; - border-radius: 4px; - cursor: pointer; -} - -.v2-repair-connector-body button b { - font: 800 7px "IBM Plex Mono", Consolas, monospace; -} - -.v2-repair-connector-body button small { - overflow: hidden; - font-size: 5.5px; - text-overflow: ellipsis; - white-space: nowrap; -} - -.v2-repair-connector-body button[data-state="OK"] { color: #176f64; background: #ddf2ee; } -.v2-repair-connector-body button[data-state="IDLE"] { color: #315e94; background: #dfebfa; } -.v2-repair-connector-body button[data-state="WARN"] { color: #8d5d20; background: #fbedd6; } -.v2-repair-connector-body button[data-state="FAULT"] { color: #963f3f; background: #f8dddd; } -.v2-repair-connector-body button[data-state="NOT_USED"] { color: #abb3b4; background: #f2f4f4; } -.v2-repair-connector-body button.selected { border-color: var(--v2-accent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--v2-accent) 16%, transparent); } - -.v2-repair-connector-body .keying { - width: 5px; - height: 18px; - position: absolute; - left: -6px; - background: #f8faf9; - border: 1px solid #9da9aa; -} - -.v2-repair-connector-body .k1 { top: 9%; } -.v2-repair-connector-body .k2 { top: 27%; } -.v2-repair-connector-body .k3 { top: 50%; } -.v2-repair-connector-body .k4 { top: 72%; } - -#repairPinDetail { - min-height: 0; - padding: 9px 10px; - overflow: auto; -} - -#repairPinDetail dl { margin: 0; } -#repairPinDetail dl > div { padding: 7px 0; border-bottom: 1px solid var(--repair-line); } -#repairPinDetail dt { color: var(--repair-muted); font-size: 7px; } -#repairPinDetail dd { margin: 2px 0 0; color: var(--repair-ink); font-size: 9px; font-weight: 750; line-height: 1.35; } -#repairPinDetail section { margin-top: 11px; } -#repairPinDetail h3 { margin: 0 0 5px; color: var(--repair-heading); font-size: 10px; } -#repairPinDetail ul, -#repairPinDetail ol { display: grid; gap: 4px; margin: 0; padding-left: 15px; color: #6f8183; font-size: 8px; line-height: 1.4; } - -.v2-repair-pin-panel > header b[data-state="OK"] { color: #258a7b; } -.v2-repair-pin-panel > header b[data-state="WARN"] { color: var(--repair-warn); } -.v2-repair-pin-panel > header b[data-state="FAULT"] { color: var(--repair-danger); } - -.v2-repair-dialog { - width: min(820px, calc(100vw - 40px)); - max-height: min(680px, calc(100vh - 50px)); - padding: 0; - overflow: hidden; - color: var(--repair-ink); - background: color-mix(in srgb, var(--v2-accent-soft) 24%, white); - border: 1px solid var(--repair-line); - border-radius: 17px; - box-shadow: 0 28px 80px rgba(16, 45, 48, 0.24); -} - -.v2-repair-dialog::backdrop { background: rgba(15, 38, 41, 0.42); backdrop-filter: blur(4px); } -.v2-repair-dialog > header { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; border-bottom: 1px solid var(--repair-line); } -.v2-repair-dialog > header > div { display: grid; gap: 2px; } -.v2-repair-dialog > header strong { font-size: 15px; } -.v2-repair-dialog > header small { color: #819092; font-size: 9px; } -.v2-repair-dialog > header button { width: 29px; height: 29px; padding: 0; color: var(--repair-ink); background: var(--repair-soft-strong); border: 0; border-radius: 9px; font-size: 18px; cursor: pointer; } -.v2-repair-dialog > div { max-height: 570px; padding: 13px 16px 18px; overflow: auto; } -.v2-repair-dialog table { width: 100%; border-collapse: collapse; font-size: 9px; } -.v2-repair-dialog th, -.v2-repair-dialog td { padding: 7px; border-bottom: 1px solid var(--repair-line); text-align: left; } -.v2-repair-dialog th { color: var(--repair-muted); background: var(--repair-soft-strong); } -.v2-repair-confirm-dialog { width: min(460px, calc(100vw - 32px)); } -.v2-repair-confirm-dialog #repairConfirmMessage { margin: 0; color: var(--repair-ink); font-size: 13px; line-height: 1.7; } -.v2-repair-confirm-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; } -.v2-repair-confirm-actions button { min-width: 104px; } -.v2-repair-report-path { padding: 7px 9px; overflow-wrap: anywhere; color: var(--repair-muted); background: var(--repair-soft-strong); border-radius: 8px; font: 8px "IBM Plex Mono", Consolas, monospace; } -.v2-repair-event-list { display: grid; gap: 5px; margin-top: 10px; } -.v2-repair-event-list article { display: grid; gap: 2px; padding: 7px 9px; background: var(--repair-soft); border-radius: 8px; } -.v2-repair-event-list strong { font-size: 9px; } -.v2-repair-event-list span { color: #758587; font-size: 8px; } - -@media (max-height: 820px) { - .console-v2[data-module="self-repair"] .v2-repair-sidebar { - margin-top: 14px; - } - - .v2-repair-sidebar .v2-section-heading h2 { - margin-bottom: 10px; - } - - .v2-repair-sidebar > .v2-field-caption { - margin-bottom: 5px; - font-size: 11px; - } - - .v2-repair-view-switch button { - min-height: 48px; - grid-template-columns: 21px minmax(0, 1fr); - padding: 4px 9px; - } - - .v2-repair-view-switch button > svg { - width: 17px; - height: 17px; - } - - .v2-repair-view-switch strong { - font-size: 10px; - } - - .v2-repair-view-switch small { - font-size: 8px; - } - - .v2-repair-config-card { - min-height: 38px; - } -} - -@media (max-width: 1220px) { - .v2-repair-heading { grid-template-columns: minmax(0, 1fr); } - .v2-repair-status-grid { display: none; } - .v2-repair-software-grid { grid-template-columns: minmax(260px, 1fr) minmax(190px, 0.68fr) minmax(330px, 1.25fr); } - .v2-repair-toolbar button { padding-inline: 8px; } - .v2-repair-toolbar button svg { display: none; } - .v2-repair-hardware-grid { grid-template-columns: minmax(180px, 0.62fr) minmax(450px, 1.5fr) minmax(190px, 0.68fr); } -} - -@media (max-width: 960px) { - .console-v2[data-module="self-repair"] .v2-self-repair { overflow: auto; } - .v2-repair-view { min-height: 900px; overflow: visible; } - .v2-repair-software-grid { - grid-template-areas: "twin cases" "logs logs"; - grid-template-columns: minmax(330px, 1fr) 210px; - grid-template-rows: 410px 390px; - } - .v2-repair-hardware-grid { min-width: 920px; } - .v2-repair-toolbar { align-items: flex-start; flex-direction: column; } - .v2-repair-toolbar > div:last-child { width: 100%; justify-content: flex-start; flex-wrap: wrap; } -} diff --git a/apps/web-console/self-repair.js b/apps/web-console/self-repair.js deleted file mode 100644 index 44d9f20..0000000 --- a/apps/web-console/self-repair.js +++ /dev/null @@ -1,797 +0,0 @@ -(function () { - "use strict"; - - const API_ROOT = "/api/self-repair"; - const VIEW_KEY = "cognitive-agent.self-repair-view"; - const MODE_KEY = "cognitive-agent.self-repair-execution"; - const STATE_TEXT = { - OK: "正常", - WARN: "告警", - FAULT: "故障", - UNKNOWN: "未检测", - UNMONITORED: "关联待测", - NOT_USED: "未启用", - IDLE: "检测中", - }; - const EVENT_META = { - BASELINE: { kind: "system", label: "运行" }, - INJECTED: { kind: "fault", label: "注入" }, - DIAGNOSED: { kind: "diagnosis", label: "诊断" }, - REPAIRING: { kind: "repair", label: "修复" }, - VERIFYING: { kind: "repair", label: "复测" }, - PASSED: { kind: "success", label: "恢复" }, - FAILED: { kind: "fault", label: "失败" }, - }; - const FALLBACK_SCENARIOS = [ - ["FI-FIELD-01", "位置标定丢失", "座椅移动 / 位置记忆"], - ["FI-FIELD-02", "位置记录CRC回退", "四轴位置 / SMV8持久化"], - ["FI-FIELD-03", "瞬态过载误判", "电机移动 / 防夹保护"], - ["FI-FIELD-04", "热管理唤醒失败", "通风 / 加热"], - ["FI-FIELD-05", "风扇关闭异常", "座椅通风"], - ["FI-FIELD-06", "WDT复位后失能", "座椅控制器 / 多功能协同"], - ].map(([id, shortTitle, system]) => ({ - id, - short_title: shortTitle, - system, - normal_task: "等待连接后加载正常任务", - fault_reaction: "等待连接后加载故障停止状态", - diagnosis: "等待连接后加载 AI 诊断", - repair: "等待连接后加载恢复策略", - recovery_reaction: "等待连接后加载恢复结果", - field_basis: "自修复服务连接后显示实时用例说明", - })); - - function fallbackState(message = "正在连接自修复服务") { - return { - scenarios: FALLBACK_SCENARIOS, - healing: { - phase: "IDLE", - phase_text: "等待服务连接", - elapsed_s: 0, - case_id: null, - telemetry: {}, - events: [], - }, - batch: { active: false, completed: 0, total: 6, passed: 0, failed: 0, results: [] }, - runtime: { - active: false, - execution_mode: "shadow", - started_epoch: null, - stopped_epoch: null, - elapsed_s: 0, - healthy_elapsed_s: 0, - motion_profile: "四电机协同自由运动", - cycle_count: 0, - injected_count: 0, - repaired_count: 0, - events: [], - }, - bridge: { online: false, protocol_online: false, bus_traffic: false }, - bridge_manager: { state: "STARTING", message }, - integration: { can_runtime_configured: false, firmware_tools_configured: false }, - hardware: { groups: [], connectors: {} }, - hardware_session: { active: false, events: [] }, - bench_twin: {}, - }; - } - - const $ = (selector, root = document) => root.querySelector(selector); - const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]; - const esc = (value) => String(value == null ? "" : value) - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """); - - let latest = fallbackState(); - let selectedCaseId = null; - let selectedPinId = "JC1-1"; - let activeView = sessionStorage.getItem(VIEW_KEY) === "hardware" - ? "hardware" - : "software"; - sessionStorage.removeItem(MODE_KEY); - let executionMode = "shadow"; - let polling = false; - let bootstrapRuntimeReset = false; - let toastTimer = 0; - let confirmationResolve = null; - let eventFilter = "all"; - - function isAdmin() { - return window.CognitiveAgentConsoleV2?.getRole() === "admin" - || document.body.dataset.demoRole === "admin"; - } - - function isActive() { - return isAdmin() && document.body.dataset.module === "self-repair"; - } - - function toast(message, error = false) { - const node = $("#toast"); - if (!node) return; - node.textContent = message; - node.className = error ? "toast show error" : "toast show"; - window.clearTimeout(toastTimer); - toastTimer = window.setTimeout(() => { node.className = "toast"; }, 3600); - } - - function buildShell() { - const sidebar = $(".v2-sidebar"); - const mainPanel = $(".main-panel"); - const moduleSwitcher = $("#v2ModuleSwitcher"); - if (!sidebar || !mainPanel || !moduleSwitcher || $("#v2SelfRepair")) return false; - - const repairSidebar = document.createElement("section"); - repairSidebar.className = "v2-sidebar-section v2-repair-sidebar"; - repairSidebar.innerHTML = ` -
        SELF-REPAIR DESK

        控制台

        - 修复对象 -
        - - -
        -
        - 配置信息 -
        -
        当前车型腾势 N7
        N7
        -
        推理模型GPT-5.6-sol
        READY
        -
        座椅控制器T2G 4BF
        4BF
        -
        - -
        验证方式
        - -
        SAFE -
        -
        -

        影子仿真不会写入 ECU 或驱动实体设备

        `; - sidebar.insertBefore(repairSidebar, $(".v2-sidebar-footer")); - - const repairFooter = document.createElement("footer"); - repairFooter.className = "v2-sidebar-footer v2-repair-footer offline"; - repairFooter.innerHTML = ` - -
        自修复安全链路CAN 桥接离线
        - `; - sidebar.append(repairFooter); - - const root = document.createElement("section"); - root.className = "v2-self-repair"; - root.id = "v2SelfRepair"; - root.setAttribute("aria-label", "座椅 AI 自修复验证台"); - root.innerHTML = ` -
        -
        SELF-REPAIR

        座椅 AI 自修复验证

        座椅持续自由运行 · 故障独立注入 · 全过程事件留痕

        -
        -
        CAN桥接离线
        -
        座椅ECU未检测
        -
        AI状态等待验证
        -
        -
        - -
        -
        -
        01

        连续运行与自修复验证

        运行任务与故障注入相互独立;选择用例不会启动或重置座椅

        -
        - - - - -
        -
        -
        -
        -
        DIGITAL TWIN

        座椅3D孪生

        正常基线
        -
        - -
        正在构建座椅孪生坐垫 · 靠背 · 腿托 · 滑轨
        -
        拖动旋转 · 滚轮缩放 · 双击复位
        -
        影子动作仿真等待启动座椅任务待机

        实际动作将同步显示在座椅模型

        -
        -
        -
        -
        FAULT INJECTION

        量产故障注入

        6 个用例
        -

        先启动座椅持续运行,再按需选择故障。注入事件会明确标记为管理员操作。

        -
        -
        - 当前选择:— - - 本次尚未注入故障 -
        -
        -
        -
        EVENT STREAM

        运行与自修复日志

        等待启动
        -
        -
        本次连续运行00:00:00
        -
        累计健康运行00:00:00
        -
        故障 / 已修复0 / 0
        -
        -
        -
        - - -
        - 自动跟随最新日志 -
        -
        -
        -
        -
        - - - -
        软件自修复验证记录成功用例自动保存诊断快照
        -
        硬件自诊断记录支路状态变化与最终报告
        - -
        确认台架安全条件确认后才会向实物链路提交请求
        -

        -
        `; - moduleSwitcher.insertAdjacentElement("afterend", root); - - const select = $("#repairExecutionMode"); - select.value = executionMode; - window.CognitiveAgentConsoleV2?.enhanceSelect(select); - return true; - } - - async function apiPost(path, body = {}) { - const response = await fetch(`${API_ROOT}${path}`, { - method: "POST", - credentials: "same-origin", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - "X-Cognitive-Agent-Role": "admin", - }, - body: JSON.stringify(body), - }); - const value = await response.json().catch(() => ({ message: `HTTP ${response.status}` })); - if (!response.ok || value.ok === false) { - throw new Error(value.message || value.error || `HTTP ${response.status}`); - } - return value; - } - - function showView(view) { - activeView = view === "hardware" ? "hardware" : "software"; - sessionStorage.setItem(VIEW_KEY, activeView); - $$('[data-repair-view]').forEach((button) => { - const active = button.dataset.repairView === activeView; - button.classList.toggle("active", active); - button.setAttribute("aria-pressed", String(active)); - }); - $$(".v2-repair-view").forEach((page) => { - const active = page.dataset.repairPage === activeView; - page.hidden = !active; - page.classList.toggle("active", active); - }); - window.setTimeout(() => { - window.dispatchEvent(new Event("resize")); - if (activeView === "software") { - window.dispatchEvent(new Event("self-repair-seat-reset")); - } - }, 80); - } - - function scenarioForDisplay() { - if (!latest?.scenarios?.length) return null; - return latest.scenarios.find((item) => item.id === selectedCaseId) - || latest.scenarios[0]; - } - - function formatDuration(seconds) { - const whole = Math.max(0, Math.floor(Number(seconds || 0))); - const hours = Math.floor(whole / 3600); - const minutes = Math.floor((whole % 3600) / 60); - const remainder = whole % 60; - return [hours, minutes, remainder] - .map((value) => String(value).padStart(2, "0")) - .join(":"); - } - - function formatEventTime(epoch) { - if (!epoch) return "--:--:--.---"; - const value = new Date(Number(epoch) * 1000); - const base = [value.getHours(), value.getMinutes(), value.getSeconds()] - .map((item) => String(item).padStart(2, "0")) - .join(":"); - return `${base}.${String(value.getMilliseconds()).padStart(3, "0")}`; - } - - function runtimeState() { - return latest.runtime || fallbackState().runtime; - } - - function renderEventStream() { - const runtime = runtimeState(); - const healing = latest.healing || {}; - const scenario = (latest.scenarios || []).find((item) => item.id === healing.case_id) - || scenarioForDisplay(); - const runtimeEvents = (runtime.events || []).map((event) => ({ - ...event, - kind: event.kind || "system", - label: event.label || "运行", - })); - const healingEvents = (healing.events || []).map((event) => { - const meta = EVENT_META[event.phase] || EVENT_META.BASELINE; - const injected = event.phase === "INJECTED"; - return { - ...event, - kind: meta.kind, - label: meta.label, - title: injected - ? `管理员注入「${scenario?.short_title || "故障用例"}」` - : event.title, - tags: [ - injected ? "来源:admin" : null, - healing.run_id ? `事件:${healing.run_id}` : null, - healing.diagnosed_code && ["DIAGNOSED", "REPAIRING", "VERIFYING", "PASSED", "FAILED"].includes(event.phase) - ? `诊断码:${healing.diagnosed_code}` : null, - ].filter(Boolean), - }; - }); - const activeRepair = ["INJECTED", "DIAGNOSED", "REPAIRING", "VERIFYING"].includes(healing.phase); - const twin = latest.bench_twin || {}; - const naturalFault = runtime.active && !activeRepair && ["IDLE", "PASSED"].includes(healing.phase) - && Number(twin.system?.faulted_mask || 0) !== 0; - const liveEvents = runtime.active && !activeRepair ? [{ - epoch: latest.generated_epoch, - time: formatEventTime(latest.generated_epoch), - kind: naturalFault ? "fault" : "heartbeat", - label: naturalFault ? "自然故障" : "运行心跳", - title: naturalFault - ? "运行中检测到座椅异常" - : `座椅已正常运行 ${formatDuration(runtime.healthy_elapsed_s)}`, - detail: naturalFault - ? `ECU FaultedMask=0x${Number(twin.system.faulted_mask).toString(16).toUpperCase()},AI正在持续监测。` - : `${runtime.motion_profile} · 已完成 ${runtime.cycle_count || 0} 个动作周期。`, - tags: (twin.axes?.length ? twin.axes : [35, 42, 48, 20].map((position_pct, motor) => ({ motor, position_pct }))) - .map((axis) => `M${axis.motor} ${Number(axis.position_pct || 0).toFixed(0)}%`), - }] : []; - const events = [...runtimeEvents, ...healingEvents, ...liveEvents] - .filter((event) => eventFilter === "all" || ["fault", "diagnosis", "repair", "success"].includes(event.kind)) - .sort((left, right) => Number(left.epoch || 0) - Number(right.epoch || 0)); - - $("#repairEventStream").innerHTML = events.length - ? events.map((event) => `
        ${esc(event.label)}${esc(event.title)}

        ${esc(event.detail || "状态已更新")}

        ${event.tags?.length ? `
        ${event.tags.map((tag) => `${esc(tag)}`).join("")}
        ` : ""}
        `).join("") - : `
        ${runtime.active ? "座椅正在正常运行" : "等待启动座椅运行"}${runtime.active ? "运行心跳、故障、诊断和修复事件将在这里持续追加。" : "启动后将记录运行时长、四轴状态和后续故障注入。"}
        `; - $("#repairEventStream").scrollTop = $("#repairEventStream").scrollHeight; - - $("#repairRuntimeElapsed").textContent = formatDuration(runtime.elapsed_s); - $("#repairHealthyElapsed").textContent = formatDuration(runtime.healthy_elapsed_s); - $("#repairFaultSummary").textContent = `${Number(runtime.injected_count || 0)} / ${Number(runtime.repaired_count || 0)}`; - const failed = healing.phase === "FAILED"; - const repairing = activeRepair; - const logState = $("#repairLogState"); - logState.textContent = failed ? "需要处理" : repairing ? "自修复中" : healing.phase === "PASSED" && runtime.active ? "已恢复运行" : runtime.active ? "健康运行" : "等待启动"; - logState.dataset.state = failed ? "fault" : repairing ? "repairing" : runtime.active ? "healthy" : "idle"; - } - - function renderCases() { - if (!selectedCaseId && latest.scenarios?.length) selectedCaseId = latest.scenarios[0].id; - const results = new Map((latest.batch?.results || []).map((item) => [item.case_id, item])); - $("#repairCaseList").innerHTML = (latest.scenarios || []).map((scenario, index) => { - const result = results.get(scenario.id); - const running = latest.batch?.current_case_id === scenario.id - || (latest.healing?.case_id === scenario.id - && !["IDLE", "PASSED", "FAILED"].includes(latest.healing.phase)); - const state = result?.result === "PASS" ? "complete" - : result?.result === "FAIL" ? "failed" - : running ? "active" : "pending"; - return ``; - }).join(""); - $$('[data-repair-case]').forEach((button) => { - button.addEventListener("click", () => { - if (latest.batch?.active) return; - selectedCaseId = button.dataset.repairCase; - renderCases(); - renderTwin(); - }); - }); - const selected = scenarioForDisplay(); - const runtime = runtimeState(); - $("#repairCaseCount").textContent = `${(latest.scenarios || []).length} 个用例`; - $("#repairSelectedCase").textContent = selected - ? `当前选择:${selected.short_title}` : "当前选择:—"; - $("#repairInjectionCount").textContent = Number(runtime.injected_count || 0) - ? `本次已注入 ${runtime.injected_count} 次 · 已修复 ${runtime.repaired_count || 0} 次` - : "本次尚未注入故障"; - const activeRepair = !["IDLE", "PASSED", "FAILED"].includes(latest.healing?.phase); - $("#repairInject").disabled = !runtime.active || activeRepair || latest.batch?.active; - $("#repairInject").innerHTML = `${activeRepair ? "自修复处理中" : runtime.active ? "注入所选故障" : "请先启动座椅运行"}`; - } - - function renderTwin() { - const healing = latest.healing; - const scenario = scenarioForDisplay(); - if (!scenario) return; - const runtime = runtimeState(); - const telemetry = healing.telemetry || {}; - const live = latest.bench_twin || {}; - const bench = executionMode === "bench"; - const positions = Array.isArray(telemetry.axis_positions) - ? telemetry.axis_positions : [35, 42, 48, 20]; - const axes = bench && live.axes?.length === 4 - ? live.axes - : positions.map((position, motor) => ({ - motor, - label: ["水平滑轨", "坐盆升降", "靠背角度", "腿托角度"][motor], - position_pct: Number(position), - active: (telemetry.active_axes || []).includes(motor), - position_valid: telemetry.position_valid !== false, - })); - const stage = { - NORMAL_TASK: "正常任务", - FAULT_REACTION: "故障停止", - REPAIR: "执行修复", - VERIFYING: "安全复测", - RESUMING: "继续原任务", - COMPLETE: "任务已恢复", - SAFE_STOP: "安全停止", - }[telemetry.operation_stage] || healing.phase_text; - $("#repairTwinSource").textContent = bench - ? (live.online ? "实物 CAN 同步" : "实物 CAN 暂离线") - : "影子动作仿真"; - $("#repairTwinTask").textContent = healing.phase === "IDLE" - ? (runtime.active ? runtime.motion_profile : "等待启动座椅运行") - : scenario.normal_task; - $("#repairTwinStage").textContent = healing.phase === "IDLE" && runtime.active - ? "自由运动" : stage || "待机"; - $("#repairTwinState").textContent = healing.phase === "IDLE" - ? (runtime.active ? "持续运行中" : "等待启动") - : healing.phase === "PASSED" && runtime.active ? "已恢复运行" : healing.phase_text; - $("#repairTwinReaction").textContent = telemetry.bench_reaction - || (healing.phase === "IDLE" - ? (runtime.active - ? `四电机按设定轨迹协同运动 · 已完成 ${runtime.cycle_count || 0} 个周期` - : "实际动作将同步显示在座椅模型") - : scenario.fault_reaction); - $("#repairAxisStrip").innerHTML = axes.map((axis) => { - const position = Math.max(0, Math.min(100, Number(axis.position_pct || 0))); - return `M${axis.motor}${position.toFixed(0)}%`; - }).join(""); - window.dispatchEvent(new CustomEvent("seat-healing-state", { detail: { - state: healing.phase, - axes: axes.map((axis) => ({ - motor: axis.motor, - position_pct: Number(axis.position_pct || 0), - active: Boolean(axis.active), - valid: axis.position_valid !== false, - })), - ventilation: Boolean((bench ? live.thermal : telemetry).fan_running), - heatingLevel: Number((bench ? live.thermal : telemetry).heater_level || 0), - } })); - } - - function connectorRows(name, pins) { - if (name === "JA1") return Array.from({ length: 7 }, (_, index) => [index + 1, index + 8]); - if (name === "JB1") return Array.from({ length: 9 }, (_, index) => [(index + 1) * 2, index * 2 + 1]); - return Array.from({ length: 20 }, (_, index) => [index + 1, index + 21]); - } - - function pinButton(pin) { - if (!pin) return ""; - const state = pin.enabled === false ? "NOT_USED" : pin.state; - return ``; - } - - function renderConnectors(hardware) { - const connectors = hardware.connectors || {}; - const names = ["JA1", "JB1", "JC1"]; - $("#repairConnectors").innerHTML = names.map((name) => { - const pins = connectors[name] || []; - const byNumber = new Map(pins.map((pin) => [Number(pin.number), pin])); - const ok = pins.filter((pin) => pin.state === "OK").length; - const abnormal = pins.filter((pin) => ["WARN", "FAULT"].includes(pin.state)).length; - return `
        ${name}已验 ${ok} · 异常 ${abnormal}
        ${name === "JC1" ? "" : ""}
        ${connectorRows(name, pins).map((row) => `${pinButton(byNumber.get(row[0]))}${pinButton(byNumber.get(row[1]))}`).join("")}
        `; - }).join(""); - $$('[data-repair-pin]').forEach((button) => button.addEventListener("click", () => { - selectedPinId = button.dataset.repairPin; - renderHardware(); - })); - } - - function renderPinDetail(hardware) { - const allPins = Object.values(hardware.connectors || {}).flat(); - const pin = allPins.find((item) => item.id === selectedPinId) || allPins[0]; - if (!pin) return; - selectedPinId = pin.id; - const state = pin.enabled === false ? "NOT_USED" : pin.state; - $("#repairPinTitle").textContent = pin.id; - $("#repairPinState").textContent = STATE_TEXT[state] || state; - $("#repairPinState").dataset.state = state; - $("#repairPinDetail").innerHTML = ` -
        原理图网络
        ${esc(pin.net)}
        座椅侧功能
        ${esc(pin.function)}
        板内二级溯源
        ${esc(pin.mcu || "—")}
        本工程启用
        ${pin.enabled === false ? "否" : "是"}
        -

        判定依据

          ${(pin.evidence || ["等待诊断证据"]).map((item) => `
        • ${esc(item)}
        • `).join("")}
        -

        建议检查顺序

          ${(pin.actions || ["启动硬件诊断后生成建议"]).map((item) => `
        1. ${esc(item)}
        2. `).join("")}
        `; - } - - function renderHardware() { - const hardware = latest.hardware || {}; - const session = latest.hardware_session || {}; - const bridge = latest.bridge || {}; - const manager = latest.bridge_manager || {}; - const adapterOnline = hardware.link?.adapter === "OK" - || Boolean(bridge.bus?.opened) - || (bridge.online && bridge.bus_traffic); - const layers = [ - ["1", "CAN Runtime", bridge.online ? "正常" : "离线", bridge.online ? "OK" : "UNKNOWN"], - ["2", "CAN设备 / 通道", adapterOnline ? "设备与通道已打开" : "未连接", adapterOnline ? "OK" : "UNKNOWN"], - ["3", "总线实时流量", bridge.bus_traffic ? "正常" : "未检测", bridge.bus_traffic ? "OK" : "WARN"], - ["4", "座椅ECU协议", bridge.protocol_online ? "0x301~0x305在线" : "未检测", bridge.protocol_online ? "OK" : "UNKNOWN"], - ]; - $("#repairLinkLayers").innerHTML = layers.map((item) => `
        ${item[0]} · ${item[1]}${item[2]}
        `).join(""); - $("#repairBridgeMessage").textContent = manager.message || "等待桥接状态"; - $("#repairLinkDetail").textContent = bridge.protocol_online - ? `协议在线 · 最近帧 ${(bridge.recent_frame_ids || []).join(" / ")}` - : bridge.bus_traffic - ? "CAN 有实时流量,但尚未识别本工程 0x301~0x305 协议。" - : "尚未收到实时 CAN 帧,启用针脚保持未检测状态,不表示针脚故障。"; - $("#repairHardwareGroups").innerHTML = (hardware.groups || []).map((group) => ``).join(""); - $("#repairHardwareOverall").textContent = `已验证 ${hardware.connector_ok_count || 0}/21 · 异常 ${(hardware.connector_fault_count || 0) + (hardware.connector_warn_count || 0)}`; - const toggle = $("#repairHardwareToggle"); - toggle.innerHTML = session.active - ? '停止硬件诊断' - : '启动硬件诊断'; - renderConnectors(hardware); - renderPinDetail(hardware); - const events = session.events || []; - $("#repairHardwareRecordsBody").innerHTML = `

        ${esc(session.report_path || "停止诊断后自动保存硬件报告")}

        ${events.length ? `${[...events].reverse().map((event) => ``).join("")}
        时间支路状态摘要
        ${esc(event.time)}${esc(event.name)}${esc(STATE_TEXT[event.state] || event.state)}${esc(event.summary)}
        ` : "

        尚无硬件诊断事件。

        "}`; - } - - function renderGlobal() { - const bridge = latest.bridge || {}; - const manager = latest.bridge_manager || {}; - const healing = latest.healing || {}; - const hardwarePhase = latest.hardware_session?.progress?.phase; - const integration = latest.integration || {}; - const runtime = runtimeState(); - $("#repairCanStatus").textContent = bridge.online ? "在线" : "离线"; - $("#repairCanDot").dataset.state = bridge.online ? "online" : manager.state === "STARTING" ? "working" : "offline"; - $("#repairProtocolStatus").textContent = bridge.protocol_online ? "协议在线" : "未检测"; - $("#repairProtocolDot").dataset.state = bridge.protocol_online ? "online" : "offline"; - const hardwareState = { - BASELINE: ["硬件检测中", "working"], - RUNNING: ["硬件检测中", "working"], - PASSED: ["21针通过", "online"], - FAILED: ["硬件异常", "offline"], - }[hardwarePhase]; - const aiState = activeView === "hardware" && hardwareState - ? hardwareState - : runtime.active && healing.phase === "IDLE" - ? ["持续监控", "online"] - : runtime.active && healing.phase === "PASSED" - ? ["已恢复监控", "online"] - : [healing.phase_text || "等待验证", healing.phase === "PASSED" - ? "online" - : healing.phase === "IDLE" ? "offline" : "working"]; - $("#repairAiStatus").textContent = aiState[0]; - $("#repairAiDot").dataset.state = aiState[1]; - $("#repairConnectionText").textContent = bridge.online ? "CAN 桥接在线" : manager.message || "CAN 桥接离线"; - $(".v2-repair-footer").classList.toggle("offline", !bridge.online); - const benchOption = $('#repairExecutionMode option[value="bench"]'); - if (benchOption) benchOption.disabled = !integration.can_runtime_configured; - if (executionMode === "bench" && !integration.can_runtime_configured) { - executionMode = "shadow"; - $("#repairExecutionMode").value = "shadow"; - sessionStorage.setItem(MODE_KEY, executionMode); - } - $("#repairExecutionState").textContent = executionMode === "bench" ? "HIL" : "SAFE"; - $("#repairConfigNote").textContent = executionMode === "bench" - ? "真实台架动作受本机 admin、安全确认与桥接状态约束" - : "影子仿真不会写入 ECU 或驱动实体设备"; - $("#repairFirmwareFlash").disabled = !integration.firmware_tools_configured; - const runtimeToggle = $("#repairRuntimeToggle"); - const repairActive = ["INJECTED", "DIAGNOSED", "REPAIRING", "VERIFYING"].includes(healing.phase); - runtimeToggle.innerHTML = runtime.active - ? '停止座椅运行' - : '启动座椅运行'; - runtimeToggle.classList.toggle("danger", runtime.active); - runtimeToggle.classList.toggle("primary", !runtime.active); - runtimeToggle.disabled = repairActive; - window.CognitiveAgentConsoleV2?.enhanceSelect($("#repairExecutionMode")); - } - - function renderRecords() { - const results = latest.batch?.results || []; - const events = latest.healing?.events || []; - $("#repairSoftwareRecordsBody").innerHTML = `

        ${esc(latest.latest_report_path || "成功用例将自动保存诊断快照")}

        ${results.length ? `${results.map((item) => ``).join("")}
        用例结果耗时诊断码
        ${esc(item.title)}${esc(item.result)}${Number(item.duration_s || 0).toFixed(2)} s${esc(item.diagnosed_code || "—")}
        ` : "

        尚无批量验证记录。

        "}
        ${events.map((event) => `
        ${esc(event.title)}${esc(event.detail)}
        `).join("")}
        `; - } - - function renderAll() { - renderGlobal(); - renderCases(); - renderEventStream(); - renderTwin(); - renderHardware(); - renderRecords(); - // Polling refreshes data only. Reapplying the active view here would also - // reset the user's current 3D orbit every 600 ms. - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - } - - async function poll() { - if (!isActive() || polling) return; - polling = true; - try { - const response = await fetch(`${API_ROOT}/state`, { - cache: "no-store", - credentials: "same-origin", - headers: { Accept: "application/json", "X-Cognitive-Agent-Role": "admin" }, - }); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - latest = await response.json(); - if (!bootstrapRuntimeReset) { - bootstrapRuntimeReset = true; - const backendMode = latest.runtime?.execution_mode === "bench" ? "bench" : "shadow"; - if (backendMode === "bench") { - // A physical session is authoritative: retain it and render bench feedback. - executionMode = "bench"; - sessionStorage.setItem(MODE_KEY, executionMode); - if ($("#repairExecutionMode")) $("#repairExecutionMode").value = executionMode; - } else { - // Shadow state is one-run-only. A full web runtime restart always returns - // counters, injected faults, and the twin to the initial safe state. - if (latest.runtime?.active) { - await apiPost("/runtime", { active: false, execution_mode: "shadow" }); - } - await apiPost("/runtime/reset-statistics"); - const resetResponse = await fetch(`${API_ROOT}/state`, { - cache: "no-store", - credentials: "same-origin", - headers: { Accept: "application/json", "X-Cognitive-Agent-Role": "admin" }, - }); - if (resetResponse.ok) latest = await resetResponse.json(); - } - } - if (!["IDLE"].includes(latest.healing?.phase)) selectedCaseId = latest.healing.case_id; - renderAll(); - } catch (error) { - $("#repairConnectionText").textContent = `自修复服务连接失败:${error.message}`; - $(".v2-repair-footer").classList.add("offline"); - } finally { - polling = false; - } - } - - async function runAction(action, successMessage) { - try { - await action(); - toast(successMessage); - await poll(); - } catch (error) { - toast(error.message, true); - } - } - - function finishConfirmation(accepted) { - const dialog = $("#repairConfirmDialog"); - const resolve = confirmationResolve; - confirmationResolve = null; - if (dialog?.open) dialog.close(accepted ? "confirmed" : "cancelled"); - if (resolve) resolve(accepted); - } - - function confirmAction(message, confirmLabel = "确认执行") { - const dialog = $("#repairConfirmDialog"); - if (!dialog || confirmationResolve) return Promise.resolve(false); - $("#repairConfirmMessage").textContent = message; - $("#repairConfirmAccept").textContent = confirmLabel; - dialog.showModal(); - return new Promise((resolve) => { - confirmationResolve = resolve; - }); - } - - function bindEvents() { - $$('[data-repair-view]').forEach((button) => button.addEventListener("click", () => showView(button.dataset.repairView))); - $("#repairExecutionMode").addEventListener("change", (event) => { - executionMode = event.target.value === "bench" ? "bench" : "shadow"; - sessionStorage.setItem(MODE_KEY, executionMode); - if (latest) renderAll(); - }); - $("#repairRuntimeToggle").addEventListener("click", async () => { - const active = Boolean(runtimeState().active); - if (executionMode === "bench" && !(await confirmAction( - active - ? "即将停止实物座椅连续运行。请确认可安全停止。" - : "即将启动实物座椅四电机协同自由运动。请确认运动区域无人、无遮挡且急停可用。", - active ? "确认停止" : "确认启动", - ))) return; - runAction( - () => apiPost("/runtime", { active: !active, execution_mode: executionMode }), - active ? "座椅连续运行已停止" : "座椅连续运行已启动", - ); - }); - $("#repairInject").addEventListener("click", async () => { - const scenario = scenarioForDisplay(); - if (!runtimeState().active || !scenario) return; - if (executionMode === "bench" && !(await confirmAction( - `即将向实物 ECU 注入「${scenario.short_title}」并驱动座椅自修复。请确认运动区域无人、无遮挡且急停可用。`, - "确认注入", - ))) return; - runAction( - () => apiPost("/healing/start", { case_id: selectedCaseId, execution_mode: executionMode }), - executionMode === "bench" ? "实物故障已注入" : "影子故障已注入,开始自修复", - ); - }); - $("#repairReset").addEventListener("click", async () => { - runAction(() => apiPost("/runtime/reset-statistics"), "本次运行统计已重置"); - }); - $("#repairFirmwareFlash").addEventListener("click", async () => { - if (!(await confirmAction("即将构建并烧录台架测试固件。请确认座椅运动区域无人、急停可用且 CMSIS-DAP 已连接。", "确认构建/烧录"))) return; - runAction(() => apiPost("/firmware/build-flash", { confirmed_bench_clear: true }), "固件构建/烧录流程已完成"); - }); - $("#repairHardwareToggle").addEventListener("click", async () => { - if (!latest) return; - if (latest.hardware_session?.active) { - runAction(() => apiPost("/hardware/stop"), "硬件诊断已停止并保存报告"); - return; - } - if (!(await confirmAction("硬件诊断可能自动烧录测试固件,并短时驱动四路电机、风扇与低档加热。请确认台架区域安全且急停可用。", "确认启动诊断"))) return; - runAction(() => apiPost("/hardware/start", { confirmed_bench_clear: true }), "21 针主动硬件诊断已启动"); - }); - $("#repairHardwareSelfTest").addEventListener("click", () => runAction(() => apiPost("/hardware/self-test"), "72 针映射和诊断规则自检完成")); - $("#repairEmergencyStop").addEventListener("click", async () => { - if (!(await confirmAction("确认提交 STOP ALL 和热管理关闭请求?", "确认紧急停止"))) return; - runAction(() => apiPost("/emergency-stop"), "紧急停止请求已提交"); - }); - $("#repairConfirmCancel").addEventListener("click", () => finishConfirmation(false)); - $("#repairConfirmAccept").addEventListener("click", () => finishConfirmation(true)); - $("#repairConfirmDialog").addEventListener("cancel", (event) => { - event.preventDefault(); - finishConfirmation(false); - }); - $("#repairConfirmDialog").addEventListener("close", () => { - if (confirmationResolve) finishConfirmation(false); - }); - $("#repairSoftwareRecords").addEventListener("click", () => $("#repairSoftwareDialog").showModal()); - $("#repairHardwareRecords").addEventListener("click", () => $("#repairHardwareDialog").showModal()); - $$('[data-repair-log-filter]').forEach((button) => button.addEventListener("click", () => { - eventFilter = button.dataset.repairLogFilter === "fault" ? "fault" : "all"; - $$('[data-repair-log-filter]').forEach((item) => item.classList.toggle("active", item === button)); - renderEventStream(); - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - })); - $$('[data-repair-close]').forEach((button) => button.addEventListener("click", () => $(`#${button.dataset.repairClose}`).close())); - window.addEventListener("cognitive-agent:module-change", (event) => { - if (event.detail?.module === "self-repair") poll(); - }); - window.addEventListener("cognitive-agent:demo-role-change", () => { - if (isActive()) poll(); - }); - } - - function init() { - if (!buildShell()) return; - bindEvents(); - showView(activeView); - renderAll(); - window.lucide?.createIcons({ attrs: { "aria-hidden": "true" } }); - if (isActive()) poll(); - window.setInterval(poll, 600); - } - - document.addEventListener("DOMContentLoaded", init); -}()); diff --git a/apps/web-console/service-worker.js b/apps/web-console/service-worker.js index 383ad9c..7c63e0b 100644 --- a/apps/web-console/service-worker.js +++ b/apps/web-console/service-worker.js @@ -1,4 +1,4 @@ -const CACHE_VERSION = "cognitive-agent-pad-v120"; +const CACHE_VERSION = "cognitive-agent-pad-v163"; const SHELL_CACHE = `${CACHE_VERSION}-shell`; const RUNTIME_CACHE = `${CACHE_VERSION}-runtime`; const APP_SHELL = [ @@ -6,21 +6,15 @@ const APP_SHELL = [ "/index.html", "/styles.css?v=dual-seat-9", "/network.js?v=android-pad-1", - "/app.js?v=dual-seat-82", - "/gesture-control.js?v=android-pad-7", - "/pwa.js?v=android-pad-1", - "/console-v2.css?v=desktop-refactor-107", - "/console-v2.js?v=desktop-refactor-36", - "/self-evolution.css?v=seat-weighing-5", - "/self-evolution.js?v=seat-weighing-2", - "/self-extension.css?v=extension-19", - "/self-extension.js?v=extension-21", - "/self-calibration.css?v=calibration-12", - "/self-calibration.js?v=calibration-8", - "/self-repair.css?v=repair-21", - "/self-repair.js?v=repair-21", - "/self-repair-seat3d.js?v=repair-21", - "/assets/models/n7_seat.glb?v=e7f50f03", + "/app.js?v=dual-seat-85", + "/gesture-control.js?v=android-pad-8", + "/pwa.js?v=android-pad-2", + "/console-v2.css?v=sync-layout-11", + "/console-v2.js?v=sync-layout-11", + "/self-extension.css?v=sync-layout-11", + "/self-extension.js?v=sync-layout-11", + "/assets/pets/self-extension-cat.png?v=3", + "/assets/pets/self-extension-cat-entrance.png?v=3", "/manifest.webmanifest", "/icons/app-icon-192.png", "/icons/app-icon-512.png", @@ -39,6 +33,7 @@ self.addEventListener("install", (event) => { event.waitUntil( caches.open(SHELL_CACHE) .then((cache) => cache.addAll(APP_SHELL)) + .then(() => self.skipWaiting()) .then(() => self.clients.matchAll({ includeUncontrolled: true })) .then((clients) => clients.forEach((client) => client.postMessage({ type: "OFFLINE_READY" }))) ); @@ -57,12 +52,13 @@ self.addEventListener("activate", (event) => { }); async function cacheFirst(request) { - const cached = await caches.match(request); + const shellCache = await caches.open(SHELL_CACHE); + const runtimeCache = await caches.open(RUNTIME_CACHE); + const cached = (await shellCache.match(request)) || (await runtimeCache.match(request)); if (cached) return cached; const response = await fetch(request); if (response.ok) { - const cache = await caches.open(RUNTIME_CACHE); - await cache.put(request, response.clone()); + await runtimeCache.put(request, response.clone()); } return response; } @@ -76,7 +72,11 @@ async function navigationResponse(request) { } return response; } catch (_error) { - return (await caches.match("/index.html")) || Response.error(); + const shellCache = await caches.open(SHELL_CACHE); + const runtimeCache = await caches.open(RUNTIME_CACHE); + return (await runtimeCache.match("/index.html")) + || (await shellCache.match("/index.html")) + || Response.error(); } } diff --git a/src/cognitive_agent/application/calibration/service.py b/src/cognitive_agent/application/calibration/service.py index 2106400..3e3f337 100644 --- a/src/cognitive_agent/application/calibration/service.py +++ b/src/cognitive_agent/application/calibration/service.py @@ -12,7 +12,6 @@ from typing import Any from . import protocol from .mqtt_client import MqttSeatPoseClient from .transports import PythonCanTransport, SimulationTransport, ZlgBridgeTransport -from .video import VideoBridge AXES = ( {"id": 0, "name": "前后", "title": "前后电机", "unit": "cm", "physical_range": 21.5, "nominal": 480}, @@ -33,8 +32,14 @@ DEFAULT_SETTINGS: dict[str, Any] = { "dll_path": r"C:\Program Files (x86)\ZCANPRO\zlgcan.dll", "resistance": 1, }, - "mqtt": {"host": "172.20.10.12", "port": 1883, "topic": "zed/seatpose"}, - "video": {"host": "172.20.10.12", "port": 8554, "path": "zed"}, + "mqtt": {"host": "172.20.10.6", "port": 1883, "topic": "zed/seatpose"}, + "video": { + "scheme": "http", + "host": "172.20.10.6", + "port": 8889, + "path": "zed", + "transport": "webrtc", + }, } @@ -60,7 +65,6 @@ class CalibrationService: self._mqtt: MqttSeatPoseClient | None = None self._saved_job = -1 self.settings = self._load_settings() - self.video = VideoBridge(self._on_video_state) self.state: dict[str, Any] = self._initial_state() def start(self, *, auto_connect: bool = False) -> None: @@ -84,7 +88,6 @@ class CalibrationService: if self._mqtt: self._mqtt.close() self._mqtt = None - self.video.stop() if self._transport: self._transport.close() self._transport = None @@ -103,7 +106,6 @@ class CalibrationService: mode = str(self.state["transport"].get("mode", "hardware")) if mode != "simulation": raise ApiError("真实台架会话不能通过虚拟重启接口复位", 409) - self.video.stop() if self._mqtt: self._mqtt.close() self._mqtt = None @@ -285,12 +287,24 @@ class CalibrationService: mqtt = self.settings["mqtt"] video = self.settings["video"] self._validate_host_port(mqtt.get("host"), mqtt.get("port"), "MQTT") - self._validate_host_port(video.get("host"), video.get("port"), "RTSP") + self._validate_host_port(video.get("host"), video.get("port"), "WebRTC") + scheme = str(video.get("scheme", "http")).strip().lower() + if scheme not in {"http", "https"}: + raise ApiError("WebRTC 信令协议必须是 http 或 https") path = str(video.get("path", "")).strip().strip("/") if not path or any(char in path for char in " ?#\\"): - raise ApiError("RTSP 流路径无效") + raise ApiError("WebRTC 流路径无效") + video["scheme"] = scheme video["path"] = path + video["transport"] = "webrtc" self.state["settings"] = json.loads(json.dumps(self.settings)) + self.state["video"].update( + { + "transport": "webrtc", + "url": self._video_url(), + "detail": "WebRTC 由浏览器直接接收", + } + ) self._save_settings() self._touch() return self.snapshot() @@ -331,19 +345,19 @@ class CalibrationService: return self.snapshot() def start_video(self) -> dict[str, Any]: - config = self.settings["video"] - uri = f"rtsp://{config['host']}:{int(config['port'])}/{str(config['path']).strip('/')}" - try: - self.video.start(uri) - except Exception as error: - self._on_video_state("error", str(error)) - raise ApiError(str(error), 503) from error + self._on_video_state("ready", f"浏览器可直接连接 {self._video_url()}") return self.snapshot() def stop_video(self) -> dict[str, Any]: - self.video.stop() + self._on_video_state("idle", "浏览器 WebRTC 接收已停止") return self.snapshot() + def _video_url(self) -> str: + config = self.settings["video"] + scheme = str(config.get("scheme", "http")).strip().lower() + path = str(config["path"]).strip("/") + return f"{scheme}://{config['host']}:{int(config['port'])}/{path}/" + def _initial_state(self) -> dict[str, Any]: return { "version": 0, @@ -399,9 +413,10 @@ class CalibrationService: "areas": {}, }, "video": { - "state": "idle", - "detail": "视频接收尚未启动", - "ffmpeg_available": self.video.available, + "state": "ready", + "detail": "WebRTC 由浏览器直接接收", + "transport": "webrtc", + "url": self._video_url(), }, "settings": json.loads(json.dumps(self.settings)), "last_result": self._load_result(), @@ -704,6 +719,23 @@ class CalibrationService: for section in settings: if isinstance(stored.get(section), dict): settings[section].update(stored[section]) + stored_video = stored.get("video") + legacy_video_endpoint = ( + isinstance(stored_video, dict) + and str(stored_video.get("host", "")).strip() == "172.20.10.12" + and str(stored_video.get("port", "")).strip() == "8554" + ) + if isinstance(stored_video, dict) and ( + "scheme" not in stored_video or legacy_video_endpoint + ): + # Settings written by the retired RTSP/FFmpeg bridge are not + # valid WHEP endpoints. Migrate that schema to the known ZED + # MediaMTX endpoint instead of trying port 8554 as WebRTC. The + # explicit endpoint check also catches legacy settings that a + # newer UI already decorated with scheme/transport fields. + settings["video"] = json.loads(json.dumps(DEFAULT_SETTINGS["video"])) + if settings["mqtt"].get("host") == "172.20.10.12": + settings["mqtt"]["host"] = DEFAULT_SETTINGS["mqtt"]["host"] except (OSError, ValueError): pass return settings diff --git a/src/cognitive_agent/server.py b/src/cognitive_agent/server.py index 39869cb..03619b8 100755 --- a/src/cognitive_agent/server.py +++ b/src/cognitive_agent/server.py @@ -10,6 +10,8 @@ import mimetypes import os import re import socket +import threading +import time from http.cookies import CookieError, SimpleCookie from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -63,6 +65,82 @@ PUBLIC_AUTH_PATHS = { } +class VehicleDisplaySync: + """Process-local snapshot consumed by passive vehicle display clients.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._revision = 0 + self._snapshot: dict[str, object] = { + "revision": 0, + "updated_at": None, + "task": { + "status": "idle", + "utterance": "", + "source": "head_unit", + "result": None, + "error": None, + }, + "extension": { + "catalog": [], + "last_action": None, + "result": None, + }, + } + + @staticmethod + def _safe_copy(value: object) -> object: + return json.loads(json.dumps(value, ensure_ascii=False, default=str)) + + def update_task( + self, + *, + status: str, + utterance: str, + source: str = "head_unit", + result: object = None, + error: object = None, + ) -> None: + with self._lock: + self._revision += 1 + self._snapshot["revision"] = self._revision + self._snapshot["updated_at"] = time.time() + self._snapshot["task"] = { + "status": status, + "utterance": utterance, + "source": source or "head_unit", + "result": self._safe_copy(result), + "error": self._safe_copy(error), + } + + def update_extension( + self, + *, + catalog: object | None = None, + action: object | None = None, + result: object | None = None, + ) -> None: + with self._lock: + self._revision += 1 + current = dict(self._snapshot.get("extension", {})) + if catalog is not None: + current["catalog"] = self._safe_copy(catalog) + if action is not None: + current["last_action"] = self._safe_copy(action) + if result is not None: + current["result"] = self._safe_copy(result) + self._snapshot["revision"] = self._revision + self._snapshot["updated_at"] = time.time() + self._snapshot["extension"] = current + + def snapshot(self, health: dict[str, object]) -> dict[str, object]: + with self._lock: + payload = self._safe_copy(self._snapshot) + assert isinstance(payload, dict) + payload["extension_health"] = self._safe_copy(health) + return payload + + def _lan_ipv4_address() -> str | None: """Return the IPv4 address selected by the host's default route.""" probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -86,6 +164,7 @@ class SeatDemoHandler(BaseHTTPRequestHandler): ) repair = SelfRepairService() auth = AuthRuntime(AuthConfig.from_env()) + vehicle_display_sync = VehicleDisplaySync() server_version = "CognitiveAgentCabinDemo/2.0" def do_GET(self) -> None: # noqa: N802 - stdlib handler API @@ -151,6 +230,9 @@ class SeatDemoHandler(BaseHTTPRequestHandler): if path == "/api/runtime": self._json(self.service.runtime_info()) return + if path == "/api/vehicle-display-sync": + self._json(self.vehicle_display_sync.snapshot(self.extension.health())) + return if path in {"/api/hardware/seat-state", "/api/hardware/vehicle-state"}: query = parse_qs(parsed_url.query) conversation_id = str(query.get("conversation_id", [""])[0]) @@ -277,6 +359,19 @@ class SeatDemoHandler(BaseHTTPRequestHandler): self._json({"error": "not_found"}, HTTPStatus.NOT_FOUND) return + utterance = "" + source = "head_unit" + + def fail_display_sync(code: str, error: Exception) -> None: + if not utterance: + return + self.vehicle_display_sync.update_task( + status="failed", + utterance=utterance, + source=source, + error={"code": code, "message": str(error)}, + ) + try: username = self._session_username() or "local" retry_after = self.auth.api_requests.retry_after(username) @@ -293,8 +388,15 @@ class SeatDemoHandler(BaseHTTPRequestHandler): if self.auth.config.enabled: self.auth.api_requests.record(username) payload = self._read_json_body() + utterance = str(payload.get("utterance", "")) + source = str(payload.get("client_type", "head_unit")) + self.vehicle_display_sync.update_task( + status="running", + utterance=utterance, + source=source, + ) result = self.service.process( - str(payload.get("utterance", "")), + utterance, str(payload.get("provider", "auto")), str(payload["conversation_id"]) if payload.get("conversation_id") else None, str(payload.get("execution_mode", "dry_run")), @@ -319,8 +421,15 @@ class SeatDemoHandler(BaseHTTPRequestHandler): else None ), ) + self.vehicle_display_sync.update_task( + status=str(result.get("status", "succeeded")), + utterance=utterance, + source=source, + result=result, + ) self._json(result, HTTPStatus.CREATED) except HardwareAccessRequiredError as exc: + fail_display_sync("hardware_access_required", exc) self._json( { "error": "hardware_access_required", @@ -330,6 +439,7 @@ class SeatDemoHandler(BaseHTTPRequestHandler): HTTPStatus.FORBIDDEN, ) except HardwareBusyError as exc: + fail_display_sync("hardware_busy", exc) self._json( { "error": "hardware_busy", @@ -340,13 +450,16 @@ class SeatDemoHandler(BaseHTTPRequestHandler): {"Retry-After": str(exc.retry_after_seconds)}, ) except HardwareSafetyError as exc: + fail_display_sync("hardware_safety_gate", exc) self._json( {"error": "hardware_safety_gate", "message": str(exc)}, HTTPStatus.FORBIDDEN, ) except (ValueError, json.JSONDecodeError) as exc: + fail_display_sync("invalid_request", exc) self._json({"error": "invalid_request", "message": str(exc)}, HTTPStatus.BAD_REQUEST) except OpenAIIntentError as exc: + fail_display_sync("openai_request_failed", exc) self.log_error("OpenAI intent request failed: %s", exc) self._json( { @@ -356,6 +469,7 @@ class SeatDemoHandler(BaseHTTPRequestHandler): HTTPStatus.BAD_GATEWAY, ) except Exception as exc: # noqa: BLE001 - keep the demo API responsive + fail_display_sync("internal_error", exc) self.log_error("request failed: %s", exc) self._json( { @@ -412,8 +526,31 @@ class SeatDemoHandler(BaseHTTPRequestHandler): if action: self._handle_extension_gateway(action, payload) return + if path == "/api/extension/display-sync": + catalog = payload.get("peripherals", payload.get("catalog", [])) + if not isinstance(catalog, list) or len(catalog) > 248: + raise ValueError("外设能力目录必须是至多 248 项的数组。") + sync_result = {"status": "ready", "count": len(catalog)} + self.vehicle_display_sync.update_extension( + catalog=catalog, + action={ + "type": "hardware_detected", + "device": payload.get("device"), + }, + result=sync_result, + ) + self._json({"success": True, **sync_result}) + return if path == "/api/extension/assistant/plan": - self._json(self.extension.plan(payload)) + self.vehicle_display_sync.update_extension( + catalog=payload.get("peripherals", payload.get("catalog", [])), + action={"type": "plan", "command": payload.get("utterance", "")}, + ) + result = self.extension.plan(payload) + self.vehicle_display_sync.update_extension( + result=result, + ) + self._json(result) return if path == "/api/extension/vehicle/execute": result = self.extension.execute_vehicle( @@ -421,6 +558,17 @@ class SeatDemoHandler(BaseHTTPRequestHandler): self.service, hardware_access_bypass=self._is_unproxied_loopback_request(), ) + self.vehicle_display_sync.update_task( + status=str(result.get("status", "succeeded")), + utterance=str(payload.get("command", payload.get("utterance", ""))), + source=str(payload.get("client_type", "head_unit")), + result=result, + ) + self.vehicle_display_sync.update_extension( + catalog=payload.get("catalog") if "catalog" in payload else None, + action={"type": "vehicle_execute"}, + result=result, + ) self._json(result) return self._json({"error": "not_found"}, HTTPStatus.NOT_FOUND) @@ -694,31 +842,23 @@ class SeatDemoHandler(BaseHTTPRequestHandler): pass def _serve_calibration_video(self) -> None: - self.send_response(HTTPStatus.OK) - self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=n7frame") - self.send_header("Cache-Control", "no-store") - self.send_header("Connection", "close") - self._send_security_headers() - self.end_headers() - sequence = -1 - try: - while True: - sequence, frame = self.calibration.video.wait_frame(sequence) - if frame is None: - continue - header = ( - b"--n7frame\r\nContent-Type: image/jpeg\r\nContent-Length: " - + str(len(frame)).encode("ascii") - + b"\r\n\r\n" - ) - self.wfile.write(header + frame + b"\r\n") - self.wfile.flush() - except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): - pass + self._json( + { + "error": "legacy_video_transport_removed", + "message": "ZED 画面已改为浏览器直连 WebRTC/WHEP。", + }, + HTTPStatus.GONE, + ) def _handle_extension_gateway(self, action: str, payload: dict[str, object]) -> None: try: - self._json(self.extension.execute_gateway(action, dict(payload))) + result = self.extension.execute_gateway(action, dict(payload)) + if action != "info": + self.vehicle_display_sync.update_extension( + action={"type": action, **dict(payload)}, + result=result, + ) + self._json(result) except GatewayError as exc: self._json( {"success": False, "error": "gscu_unavailable", "message": str(exc)}, @@ -986,7 +1126,9 @@ class SeatDemoHandler(BaseHTTPRequestHandler): cache_control = "public, max-age=31536000, immutable" elif relative_path.startswith("assets/"): cache_control = "no-cache" - elif candidate.name in {"index.html", "login.html", "service-worker.js"}: + elif candidate.name == "service-worker.js": + cache_control = "no-store" + elif candidate.name in {"index.html", "login.html"}: cache_control = "no-cache" self.send_header("Cache-Control", cache_control) if candidate.name == "service-worker.js": @@ -1050,7 +1192,8 @@ class SeatDemoHandler(BaseHTTPRequestHandler): "script-src 'self' 'wasm-unsafe-eval'; " "style-src 'self'; " "img-src 'self' data: blob:; " - "connect-src 'self' blob:; " + "media-src 'self' blob:; " + "connect-src 'self' blob: http://172.20.10.6:8889; " "object-src 'none'; base-uri 'none'; frame-ancestors 'none'", ) if self._is_https(): diff --git a/tests/e2e/test_seat_web_api.py b/tests/e2e/test_seat_web_api.py index d0033b5..a9ea2fa 100755 --- a/tests/e2e/test_seat_web_api.py +++ b/tests/e2e/test_seat_web_api.py @@ -174,37 +174,81 @@ operations: finally: self.service.mode_profiles = original_registry + def test_head_unit_display_sync_tracks_tasks_and_usb_catalog(self) -> None: + task_request = urllib.request.Request( + f"{self.base_url}/api/requests", + method="POST", + headers={"Content-Type": "application/json"}, + data=json.dumps( + { + "utterance": "副驾有点热,有点闷", + "provider": "local", + "conversation_id": "conv-head-unit-display-sync", + "vehicle_id": "denza_n7", + "execution_mode": "dry_run", + "client_type": "head_unit", + }, + ensure_ascii=False, + ).encode("utf-8"), + ) + with self.opener.open(task_request, timeout=3) as response: + task_result = json.loads(response.read().decode("utf-8")) + + peripheral = { + "id": "cap-usb-light-on", + "device_id": "usb-light-1", + "device_name": "USB 氛围灯条", + "device_type": "light", + "type_label": "灯光外设", + "action": "开启灯带", + } + extension_request = urllib.request.Request( + f"{self.base_url}/api/extension/display-sync", + method="POST", + headers={"Content-Type": "application/json"}, + data=json.dumps( + {"device": {"id": "usb-light-1"}, "peripherals": [peripheral]}, + ensure_ascii=False, + ).encode("utf-8"), + ) + with self.opener.open(extension_request, timeout=3) as response: + extension_result = json.loads(response.read().decode("utf-8")) + with self.opener.open( + f"{self.base_url}/api/vehicle-display-sync", timeout=3 + ) as response: + snapshot = json.loads(response.read().decode("utf-8")) + + self.assertEqual(task_result["status"], "succeeded") + self.assertTrue(extension_result["success"]) + self.assertEqual(snapshot["task"]["utterance"], "副驾有点热,有点闷") + self.assertEqual(snapshot["task"]["result"]["request_id"], task_result["request_id"]) + self.assertEqual(snapshot["extension"]["catalog"], [peripheral]) + self.assertEqual(snapshot["extension"]["last_action"]["type"], "hardware_detected") + self.assertIn("extension_health", snapshot) + def test_static_console_and_runtime_endpoint(self) -> None: with self.opener.open(f"{self.base_url}/", timeout=3) as response: html = response.read().decode("utf-8") - with self.opener.open(f"{self.base_url}/app.js?v=dual-seat-82", timeout=3) as response: + with self.opener.open(f"{self.base_url}/app.js?v=dual-seat-85", timeout=3) as response: app_script = response.read().decode("utf-8") with self.opener.open( - f"{self.base_url}/gesture-control.js?v=android-pad-7", timeout=3 + f"{self.base_url}/gesture-control.js?v=android-pad-8", timeout=3 ) as response: gesture_script = response.read().decode("utf-8") with self.opener.open( - f"{self.base_url}/console-v2.js?v=desktop-refactor-36", timeout=3 + f"{self.base_url}/console-v2.js?v=sync-layout-11", timeout=3 ) as response: console_script = response.read().decode("utf-8") with self.opener.open( - f"{self.base_url}/console-v2.css?v=desktop-refactor-107", timeout=3 + f"{self.base_url}/console-v2.css?v=sync-layout-11", timeout=3 ) as response: console_styles = response.read().decode("utf-8") with self.opener.open( - f"{self.base_url}/self-evolution.js?v=seat-weighing-2", timeout=3 - ) as response: - evolution_script = response.read().decode("utf-8") - with self.opener.open( - f"{self.base_url}/self-evolution.css?v=seat-weighing-5", timeout=3 - ) as response: - evolution_styles = response.read().decode("utf-8") - with self.opener.open( - f"{self.base_url}/self-extension.js?v=extension-21", timeout=3 + f"{self.base_url}/self-extension.js?v=sync-layout-11", timeout=3 ) as response: extension_script = response.read().decode("utf-8") with self.opener.open( - f"{self.base_url}/self-extension.css?v=extension-19", timeout=3 + f"{self.base_url}/self-extension.css?v=sync-layout-11", timeout=3 ) as response: extension_styles = response.read().decode("utf-8").replace("\r\n", "\n") with self.opener.open( @@ -231,75 +275,48 @@ operations: self.assertIn("CMD 0x431 · FB 0x41A · CH1", html) self.assertIn("CMD 0x431 · FB 0x388 · CH1", html) self.assertNotIn("透明车体 · 实体设备", html) - self.assertIn('src="/app.js?v=dual-seat-82"', html) + self.assertIn('src="/app.js?v=dual-seat-85"', html) self.assertIn('href="/styles.css?v=dual-seat-9"', html) - self.assertIn('src="/gesture-control.js?v=android-pad-7"', html) + self.assertIn('src="/gesture-control.js?v=android-pad-8"', html) self.assertNotIn('class="vehicle-system-hud"', html) - self.assertIn('src="/console-v2.js?v=desktop-refactor-36"', html) - self.assertIn('href="/console-v2.css?v=desktop-refactor-107"', html) - self.assertIn('src="/self-evolution.js?v=seat-weighing-2"', html) - self.assertIn('href="/self-evolution.css?v=seat-weighing-5"', html) - self.assertIn('src="/self-extension.js?v=extension-21"', html) - self.assertIn('href="/self-extension.css?v=extension-19"', html) + self.assertIn('src="/console-v2.js?v=sync-layout-11"', html) + self.assertIn('href="/console-v2.css?v=sync-layout-11"', html) + self.assertIn('src="/self-extension.js?v=sync-layout-11"', html) + self.assertIn('href="/self-extension.css?v=sync-layout-11"', html) + self.assertNotIn("self-calibration", html) + self.assertNotIn("self-repair", html) + self.assertNotIn("self-evolution", html) self.assertNotIn("滚动查看更多", html) self.assertIn('aria-label="执行车舱控制指令"', html) - self.assertIn('sessionStorage.getItem("cognitive-agent.demo-role")', console_script) + self.assertNotIn('"admin"', console_script) + self.assertNotIn("v2RoleSelect", console_script) self.assertIn('id="v2SidebarToggle"', console_script) self.assertIn('id = "v2ModuleSwitcher"', console_script) self.assertIn( 'panelHeading.classList.add("v2-operation-heading", "v2-module-heading")', console_script, ) - self.assertIn('kicker.textContent = "SELF-ORCHESTRATION"', console_script) - self.assertIn( + self.assertIn('kicker.textContent = "REMOTE ORCHESTRATION · LIVE SYNC"', console_script) + self.assertIn('fetch("/api/vehicle-display-sync"', console_script) + self.assertIn('document.body.classList.add("v2-passive-display", "v2-interactive-sync")', console_script) + self.assertIn('input.readOnly = false', console_script) + self.assertIn('function buildTwinDeviceInteractions()', console_script) + self.assertIn('id="v2SyncLogList"', console_script) + self.assertIn('data-panel-toggle="devices"', console_script) + self.assertIn('data-panel-toggle="extensions"', console_script) + self.assertIn('id="vehicleExtensionSync"', console_script) + self.assertNotIn( 'if (ui.activeModule === "self-extension" && ui.role !== "user")', console_script, ) - self.assertIn( - 'if (ui.activeModule === "self-extension" && role !== "user" && !allowModuleTransition)', + self.assertNotIn( + 'if (ui.activeModule === "self-extension" && role !== "user"', console_script, ) - self.assertIn('label: "自编排", available: true', console_script) - self.assertIn('id: "self-calibration"', console_script) - self.assertIn('label: "自标定"', console_script) - self.assertLess( - console_script.index('label: "自标定"'), - console_script.index('label: "自编排"'), - ) - self.assertIn("adminOnly: true", console_script) - self.assertIn( - "$('.v2-module-tab[data-module=\"self-calibration\"]')", - console_script, - ) - self.assertIn('label: "自扩展", available: true', console_script) - self.assertIn('aria-label="自扩展面向所有登录用户"', console_script) + self.assertIn('511工程-智能座舱', console_script) + self.assertIn('网页控制链路', console_script) self.assertIn('Hi,user', console_script) - self.assertIn('id: "self-repair"', console_script) - self.assertIn('label: "自修复"', console_script) - self.assertIn('id: "self-evolution", label: "自进化", available: true', console_script) - self.assertIn( - 'window.CognitiveAgentSelfEvolution?.mount(mainPanel)', - console_script, - ) - self.assertIn('caption.textContent = evolutionMode ? "进化视图" : "控制方式"', console_script) - self.assertIn('{ label: "座椅称重进化", icon: "scale"', console_script) - self.assertIn('{ label: "系统能力日志", icon: "scroll-text"', console_script) - self.assertIn('aria-label", "自进化 · 座椅称重个性化模型进化"', evolution_script) - self.assertIn('SELF-EVOLUTION · SEAT WEIGHING', evolution_script) - self.assertIn('座椅称重模型进化', evolution_script) - self.assertIn('系统能力日志', evolution_script) - self.assertIn('data-family-model="${model.id}"', evolution_script) - self.assertIn('用户 A', evolution_script) - self.assertIn('用户 B', evolution_script) - self.assertIn('用户 C', evolution_script) - self.assertIn('访客', evolution_script) - self.assertIn('退化保护已触发', evolution_script) - self.assertIn('本次未参与发布', evolution_script) - self.assertIn('演示进化过程', evolution_script) - self.assertIn('家庭体脂秤', evolution_script) - self.assertIn('目标误差', evolution_script) - self.assertIn('["self-orchestration", "self-extension", "self-evolution"]', console_script) - self.assertIn('roleSelect.disabled = ui.activeModule === "self-repair"', console_script) + self.assertIn('["self-orchestration", "self-extension"]', console_script) self.assertNotIn('label: "自诊断"', console_script) self.assertIn('手势模型', console_script) self.assertIn('id="v2GestureModelValue">MediaPipe GR', console_script) @@ -316,13 +333,12 @@ operations: self.assertIn('const dryRunButton = $(\'[data-execution-mode="dry_run"]\')', console_script) self.assertIn('if (!dryRunButton.classList.contains("active")) dryRunButton.click()', console_script) self.assertIn('userTargetText.textContent = "执行目标:虚拟 CAN"', console_script) - self.assertIn("真实台架仅由管理员显式启用", console_script) + self.assertIn("user 固定使用虚拟 CAN 安全执行环境", console_script) self.assertNotIn("user 演示固定使用真实台架", console_script) self.assertIn('grid-template-columns: clamp(245px, 18.5vw, 310px)', console_styles) self.assertIn('.v2-control-switch {', console_styles) self.assertIn('.v2-module-switcher {', console_styles) - self.assertIn('grid-template-columns: repeat(5, minmax(0, 1fr))', console_styles) - self.assertIn('[data-module="self-evolution"] .v2-self-evolution', evolution_styles) + self.assertIn('grid-template-columns: repeat(2, minmax(0, 1fr))', console_styles) self.assertIn( '.console-v2 .v2-module-heading.v2-module-heading h1', console_styles, @@ -334,22 +350,6 @@ operations: 'grid-template-rows: 36px clamp(236px, 33dvh, 246px) minmax(0, 1fr)', console_styles, ) - self.assertIn( - '[data-module="self-calibration"] .v2-self-calibration', - console_styles, - ) - self.assertIn( - '[data-module="self-repair"] .v2-self-repair', - console_styles, - ) - self.assertIn('.v2-evolution-version.active', evolution_styles) - self.assertIn('[data-evolution-scope="admin"]', evolution_styles) - self.assertIn('.v2-weighing-workspace', evolution_styles) - self.assertIn('.v2-family-model.active', evolution_styles) - self.assertIn('.v2-personal-line', evolution_styles) - self.assertIn('.v2-linkage-guard', evolution_styles) - self.assertIn('.v2-parameter-grid', evolution_styles) - self.assertIn('[data-demo-role="admin"] [data-evolution-scope="admin"]', evolution_styles) self.assertIn( 'color-mix(in srgb, var(--v2-accent-soft) 86%, white)', console_styles, @@ -362,14 +362,13 @@ operations: self.assertIn('background: color-mix(in srgb, var(--v2-accent) 30%, var(--v2-accent-soft))', console_styles) self.assertIn('width: clamp(48px, 45%, 72px)', console_styles) self.assertIn('font-weight: 800', console_styles) - self.assertIn('width: clamp(300px, 28vw, 360px)', console_styles) self.assertIn('white-space: nowrap', console_styles) self.assertIn('.v2-gesture-model-field', console_styles) self.assertIn('.v2-inline-gesture .v2-camera-toggle', console_styles) self.assertIn('.v2-inline-gesture .v2-gesture-action-rail', console_styles) self.assertIn('grid-template-rows: 42px 10px 42px', console_styles) self.assertIn('background: var(--v2-accent);', console_styles) - self.assertIn('[data-demo-role="user"] .v2-inline-gesture #gestureArmButton svg', console_styles) + self.assertNotIn("gestureArmButton", console_styles) self.assertIn('.v2-inline-gesture #gestureStopButton', console_styles) self.assertIn('.v2-inline-gesture .v2-gesture-result-stack', console_styles) self.assertIn('.v2-inline-gesture .v2-gesture-execution-slot', console_styles) @@ -380,7 +379,7 @@ operations: self.assertIn('.v2-edge-fade-right', console_styles) self.assertIn('.mode-group-divider', console_styles) self.assertIn('.joint-twin-shell > .cabin-band', console_styles) - self.assertIn('[data-demo-role="user"] .v2-page-index', console_styles) + self.assertIn('.console-v2 .v2-page-index', console_styles) self.assertIn('.joint-twin-shell .twin-readout', console_styles) self.assertIn('.joint-seat-panel .thermal-states', console_styles) self.assertIn('.joint-twin-shell .domain-readouts', console_styles) @@ -421,7 +420,7 @@ operations: self.assertIn("function styleReferencePassiveGlass", app_script) self.assertIn("function styleReferencePassiveRearExterior", app_script) self.assertIn('twinRole: "reference_passive_rear_bumper"', app_script) - self.assertIn('"cognitive-agent:demo-role-change"', console_script) + self.assertNotIn('"cognitive-agent:demo-role-change"', console_script) self.assertIn('resultStack.id = "v2GestureResultStack"', console_script) self.assertIn('executionSlot.id = "v2GestureExecutionSlot"', console_script) self.assertIn('statusTarget.append(requestStatus)', console_script) @@ -450,9 +449,9 @@ operations: self.assertIn('healthState.message || "GSCU1B 尚未连接"', extension_script) self.assertIn('window.addEventListener("pageshow"', extension_script) self.assertIn('[data-module="self-extension"]', extension_styles) - self.assertIn('[data-module="self-extension"] .v2-role-select', extension_styles) + self.assertNotIn('[data-module="self-extension"] .v2-role-select', extension_styles) self.assertIn('.v2-extension-composer .primary-action {', extension_styles) - self.assertIn('--v2-accent: #0e7773', extension_styles) + self.assertNotIn('--v2-accent:', extension_styles) self.assertIn('.v2-sidebar-collapsed[data-module="self-extension"] .v2-extension-sidebar', extension_styles) self.assertIn('.v2-extension-capability span {', extension_styles) self.assertIn('.v2-extension-parameter-list > span {', extension_styles) @@ -482,14 +481,17 @@ operations: ) self.assertIn("const stageHasLayout = () =>", app_script) self.assertIn("window.requestAnimationFrame(initSeatTwin)", app_script) + self.assertIn('client_type: "web_console"', app_script) self.assertIn('canvas.addEventListener("webglcontextlost"', app_script) self.assertIn('"cognitive-agent:module-change"', app_script) - self.assertIn('const CACHE_VERSION = "cognitive-agent-pad-v120"', service_worker) - self.assertIn('"/self-evolution.js?v=seat-weighing-2"', service_worker) - self.assertIn('"/self-evolution.css?v=seat-weighing-5"', service_worker) - self.assertIn( - '"/assets/models/n7_seat.glb?v=e7f50f03"', service_worker - ) + self.assertIn('const CACHE_VERSION = "cognitive-agent-pad-v163"', service_worker) + self.assertIn('"/assets/pets/self-extension-cat.png?v=3"', service_worker) + self.assertIn(".then(() => self.skipWaiting())", service_worker) + self.assertNotIn("const cached = await caches.match(request)", service_worker) + self.assertNotIn("self-evolution", service_worker) + self.assertNotIn("self-calibration", service_worker) + self.assertNotIn("self-repair", service_worker) + self.assertNotIn("n7_seat.glb", service_worker) self.assertIn("hardware_access_required", app_script) self.assertIn('button.setAttribute("aria-label", "关闭摄像头")', gesture_script) self.assertIn("function refreshCameraAvailability", gesture_script) @@ -499,9 +501,8 @@ operations: self.assertIn('case "NotAllowedError":', gesture_script) self.assertIn('case "NotReadableError":', gesture_script) self.assertIn('case "OverconstrainedError":', gesture_script) - self.assertIn("function sendSimulatedGesture()", gesture_script) - self.assertIn('document.body.dataset.demoRole !== "admin"', gesture_script) - self.assertIn("function syncGestureDebugRole", gesture_script) + self.assertNotIn("sendSimulatedGesture", gesture_script) + self.assertNotIn("gestureDebug", gesture_script) self.assertIn("HARDWARE_REQUEST_TIMEOUT_MS = 15 * 60 * 1000", app_script) self.assertIn( "requestTimeoutForExecutionMode(state.executionMode)", app_script @@ -695,11 +696,11 @@ operations: def test_self_extension_vehicle_success_contract_is_strict(self) -> None: with self.opener.open( - f"{self.base_url}/self-extension.js?v=extension-21", timeout=3 + f"{self.base_url}/self-extension.js?v=extension-44", timeout=3 ) as response: extension_script = response.read().decode("utf-8") with self.opener.open( - f"{self.base_url}/app.js?v=dual-seat-82", timeout=3 + f"{self.base_url}/app.js?v=dual-seat-83", timeout=3 ) as response: app_script = response.read().decode("utf-8") diff --git a/tests/e2e/test_self_calibration_api.py b/tests/e2e/test_self_calibration_api.py index abe13b6..eb84a5a 100644 --- a/tests/e2e/test_self_calibration_api.py +++ b/tests/e2e/test_self_calibration_api.py @@ -130,73 +130,18 @@ class TestSelfCalibrationApi: assert reset["transport"]["state"] == "disconnected" assert [axis["permille"] for axis in reset["axes"]] == [0, 0, 0, 0] - def test_frontend_and_original_model_are_served_by_existing_service(self) -> None: + def test_frontend_and_original_model_are_removed(self) -> None: with urllib.request.urlopen(f"{self.base_url}/", timeout=3) as response: html = response.read().decode("utf-8") - with urllib.request.urlopen( - f"{self.base_url}/self-calibration.js?v=calibration-8", - timeout=3, - ) as response: - script = response.read().decode("utf-8") - with urllib.request.urlopen( - f"{self.base_url}/self-calibration.css?v=calibration-12", - timeout=3, - ) as response: - styles = response.read().decode("utf-8") - with urllib.request.urlopen( - f"{self.base_url}/console-v2.js?v=desktop-refactor-31", - timeout=3, - ) as response: - console_script = response.read().decode("utf-8") - with urllib.request.urlopen( - f"{self.base_url}/assets/models/n7_seat.glb", - timeout=3, - ) as response: - model = response.read() - content_type = response.headers["Content-Type"] - content_security_policy = response.headers["Content-Security-Policy"] - unversioned_cache_control = response.headers["Cache-Control"] - with urllib.request.urlopen( - f"{self.base_url}/assets/models/n7_seat.glb?v=e7f50f03", - timeout=3, - ) as response: - versioned_model_prefix = response.read(4) - versioned_cache_control = response.headers["Cache-Control"] - with pytest.raises(urllib.error.HTTPError) as missing_model: - urllib.request.urlopen( - f"{self.base_url}/assets/models/missing-seat.glb?v=missing", - timeout=3, - ) + assert "self-calibration" not in html + assert "vendor/mediamtx" not in html - assert 'href="/self-calibration.css?v=calibration-12"' in html - assert 'src="/self-calibration.js?v=calibration-8"' in html - assert 'data-calibration-page="live"' in script - assert 'data-calibration-view="live"' in script - assert 'data-calibration-page="hall"' not in script - assert 'data-calibration-page="stereo"' not in script - assert "座椅与双目联合标定" in script - assert 'class="v2-module-heading"' in script - assert 'SELF-CALIBRATION' in script - assert 'padding: var(--v2-module-title-block) 0 0' in styles - assert 'margin-inline: var(--v2-module-title-inline)' in styles - assert "实时座椅姿态" in script - assert "四轴实时控制" in script - assert "ZED 实时画面" in script - assert "双目位姿数据" not in script - assert 'class="v2-calibration-panel v2-calibration-mqtt-panel"' not in script - assert "grid-template-columns: minmax(420px, 1.06fr) minmax(380px, 0.94fr)" in styles - assert "标定仿真台架" in script - assert "X-Cognitive-Agent-Role" in script - assert "--v2-sidebar: #dae3f5" in styles - assert "--v2-sidebar-deep: #b6c7ea" in styles - assert "--v2-accent-strong: #1e386b" in styles - assert '["self-calibration", "self-repair"].includes(module)' in console_script - assert 'setRole("admin", { allowModuleTransition: true })' in console_script - assert len(model) == 845_992 - assert versioned_model_prefix == model[:4] - assert content_type.startswith("model/gltf-binary") - assert unversioned_cache_control == "no-cache" - assert versioned_cache_control == "public, max-age=31536000, immutable" - assert missing_model.value.code == 404 - assert "img-src 'self' data: blob:;" in content_security_policy - assert "connect-src 'self' blob:;" in content_security_policy + for path in ( + "/self-calibration.js", + "/self-calibration.css", + "/vendor/mediamtx/reader.js", + "/assets/models/n7_seat.glb", + ): + with pytest.raises(urllib.error.HTTPError) as missing_asset: + urllib.request.urlopen(f"{self.base_url}{path}", timeout=3) + assert missing_asset.value.code == 404 diff --git a/tests/e2e/test_self_repair_api.py b/tests/e2e/test_self_repair_api.py index dee4be3..cf41c85 100644 --- a/tests/e2e/test_self_repair_api.py +++ b/tests/e2e/test_self_repair_api.py @@ -142,74 +142,24 @@ class TestSelfRepairApi: assert result["ok"] is True assert result["self_test"]["result"] == "PASS" - def test_frontend_assets_and_role_transition_are_served(self) -> None: + def test_frontend_assets_and_role_transition_are_removed(self) -> None: with urllib.request.urlopen(f"{self.base_url}/", timeout=3) as response: html = response.read().decode("utf-8") - with urllib.request.urlopen( - f"{self.base_url}/self-repair.js?v=repair-21", timeout=3 - ) as response: - script = response.read().decode("utf-8").replace("\r\n", "\n") - with urllib.request.urlopen( - f"{self.base_url}/self-repair.css?v=repair-21", timeout=3 - ) as response: - styles = response.read().decode("utf-8") - with urllib.request.urlopen( - f"{self.base_url}/self-repair-seat3d.js?v=repair-21", timeout=3 - ) as response: - seat3d = response.read().decode("utf-8") with urllib.request.urlopen( f"{self.base_url}/console-v2.js?v=desktop-refactor-31", timeout=3 ) as response: console_script = response.read().decode("utf-8") - assert 'href="/self-repair.css?v=repair-21"' in html - assert 'src="/self-repair.js?v=repair-21"' in html - assert 'class="v2-module-heading"' in script - assert 'SELF-REPAIR' in script - assert 'padding: var(--v2-module-title-block) 0 0' in styles - assert 'margin-inline: var(--v2-module-title-inline)' in styles - assert 'src="/self-repair-seat3d.js?v=repair-21"' in html - assert "量产故障注入" in script - assert "运行与自修复日志" in script - assert "启动座椅运行" in script - assert "开始正常任务" not in script - assert 'id="repairSeatCanvas"' in script - assert 'id="repairSeatViewer"' in script - assert "self-repair-seat-reset" in script - assert "seat-healing-state" in script - assert 'id="repairConfirmDialog"' in script - assert "confirmAction(" in script - assert "window.confirm" not in script - assert 'hardware.link?.adapter === "OK"' in script - assert 'PASSED: ["21针通过", "online"]' in script - assert "connectorRows" in script - assert "Polling refreshes data only" in script - assert "renderRecords();\n showView(activeView);" not in script - assert 'let latest = fallbackState();' in script - assert 'renderAll();\n window.lucide?.createIcons' in script - assert '"WDT复位后失能"' in script - assert "--repair-deep-blue" in styles - assert '.console-v2[data-module="self-repair"] .section-kicker' in styles - assert 'grid-template-areas: "twin cases logs"' in styles - assert ".v2-repair-event-stream" in styles - assert "background: rgba(255, 255, 255, 0.94)" in styles - assert "border-color: color-mix(in srgb, var(--v2-accent) 18%, white)" in styles - assert ".v2-repair-toolbar button.primary:hover:not(:disabled)" in styles - assert "color: #fff;" in styles - assert "seat-healing-state" in seat3d - assert "function backrestShape" in seat3d - assert "new THREE.CapsuleGeometry" in seat3d - assert 'cssThemeColor("--v2-accent", "#315eaa")' in seat3d - assert 'viewer.addEventListener("pointerdown"' in seat3d - assert 'window.addEventListener("pointermove"' in seat3d - assert "window.addEventListener(resetEvent" in seat3d - assert "function viewerHasLayout(viewer)" in seat3d - assert "function deferSeat3dUntilVisible(viewer, options)" in seat3d - assert "if (!viewerHasLayout(viewer))" in seat3d - assert 'window.addEventListener("cognitive-agent:module-change"' in seat3d - assert 'canvas.addEventListener("webglcontextlost"' in seat3d - assert '["self-calibration", "self-repair"].includes(module)' in console_script - assert 'roleSelect.disabled = ui.activeModule === "self-repair"' in console_script + assert "self-repair" not in html + assert '"admin"' not in console_script + for path in ( + "/self-repair.js", + "/self-repair.css", + "/self-repair-seat3d.js", + ): + with pytest.raises(urllib.error.HTTPError) as missing_asset: + urllib.request.urlopen(f"{self.base_url}{path}", timeout=3) + assert missing_asset.value.code == 404 def test_self_repair_bridge_uses_the_backend_runtime_directory() -> None: diff --git a/tests/unit/test_frontend_vehicle_state_sync_contract.py b/tests/unit/test_frontend_vehicle_state_sync_contract.py index 62a108b..f685e0a 100644 --- a/tests/unit/test_frontend_vehicle_state_sync_contract.py +++ b/tests/unit/test_frontend_vehicle_state_sync_contract.py @@ -47,27 +47,16 @@ class FrontendVehicleStateSyncContractTests(unittest.TestCase): self.extension_source, ) - def test_shared_twin_theme_tracks_demo_role_and_extension_is_always_user(self) -> None: + def test_shared_twin_theme_is_fixed_to_user(self) -> None: self.assertIn("function applyTwinSceneTheme(", self.app_source) - self.assertIn('canvas.dataset.themeRole = themeRole', self.app_source) + self.assertIn('canvas.dataset.themeRole = "user"', self.app_source) self.assertIn( 'canvas.dataset.themeAccent = `#${palette.accent.toString(16).padStart(6, "0")}`', self.app_source, ) self.assertIn("accent: 0x0e7773", self.app_source) - self.assertIn("accent: 0x315eaa", self.app_source) - self.assertIn( - 'if (document.body.dataset.module === "self-extension") return "user"', - self.app_source, - ) - self.assertIn( - 'const themeRole = document.body.dataset.module === "self-extension"', - self.app_source, - ) - self.assertIn( - 'window.addEventListener("cognitive-agent:demo-role-change"', - self.app_source, - ) + self.assertNotIn("accent: 0x315eaa", self.app_source) + self.assertNotIn("cognitive-agent:demo-role-change", self.app_source) def test_shared_twin_ground_uses_theme_radial_alpha_texture(self) -> None: self.assertIn("function createTwinGroundTexture(", self.app_source) diff --git a/tests/unit/test_requested_frontend_enhancements.py b/tests/unit/test_requested_frontend_enhancements.py index f76bd05..76e3980 100644 --- a/tests/unit/test_requested_frontend_enhancements.py +++ b/tests/unit/test_requested_frontend_enhancements.py @@ -10,27 +10,29 @@ def source(name: str) -> str: return (ROOT / "apps" / "web-console" / name).read_text(encoding="utf-8") -def test_calibration_twin_tracks_labels_and_commits_direct_axis_drag() -> None: - calibration = source("self-calibration.js") - seat3d = source("self-repair-seat3d.js") - styles = source("self-calibration.css") +def test_frontend_only_exposes_user_orchestration_and_extension() -> None: + web_root = ROOT / "apps" / "web-console" + html = source("index.html") + console = source("console-v2.js") - assert 'data-seat-axis-label="backrest"' in calibration - assert 'data-seat-label-line="legrest"' in calibration - assert 'window.addEventListener("calibration-seat-axis-preview"' in calibration - assert 'window.addEventListener("calibration-seat-axis-commit"' in calibration - assert "function layoutSeatLabels()" in seat3d - assert "makePanel(legrestPivot, cushionShape(0.08)" in seat3d - assert "function legrestShape(" not in seat3d - assert 'enableAxisDrag: true' in seat3d - assert 'function startAxisDrag(axis, event, source = "model")' in seat3d - assert 'startAxisDrag(item.axis, event, "label")' in seat3d - assert "calculateAxisDragVector(axis, value)" in seat3d - assert "Math.max(0, Math.min(100," in seat3d - assert 'new CustomEvent("calibration-seat-axis-commit"' in seat3d - assert ".v2-calibration-label-lines line" in styles - assert '.v2-axis-tag[data-control-enabled="true"]' in styles - assert "pointer-events: auto;" in styles + for removed in ( + "self-calibration.js", + "self-calibration.css", + "self-repair.js", + "self-repair.css", + "self-repair-seat3d.js", + "self-evolution.js", + "self-evolution.css", + ): + assert not (web_root / removed).exists() + assert removed not in html + + assert "511工程-智能座舱" in console + assert '["self-orchestration", "self-extension"]' in console + assert 'id="vehicleExtensionSync"' in console + assert 'getRole: () => "user"' in console + assert '"admin"' not in console + assert "v2RoleSelect" not in console def test_extension_pet_and_transient_vehicle_state_restart_contract() -> None: @@ -41,17 +43,63 @@ def test_extension_pet_and_transient_vehicle_state_restart_contract() -> None: assert "function initializeDesktopPet()" in extension assert "saved.vehicleExecutions = {};" in extension assert "saved.lastProtocol = null;" in extension + assert 'src="/assets/pets/self-extension-cat.png?v=3"' in extension + assert 'class="v2-extension-pet-entrance-canvas"' in extension + assert '"/assets/pets/self-extension-cat-entrance.png?v=3"' in extension + assert "const ENTRANCE_KEYFRAME_COUNT = 12" in extension + assert "const ENTRANCE_DURATION_MS = 2300" in extension + assert "const ENTRANCE_WALK_STEPS = 5" in extension + assert "const ENTRANCE_SETTLE_START_FRAME = 5" in extension + assert "0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4" in extension + assert "const easedStepProgress = 0.5 - (Math.cos(Math.PI * stepProgress) / 2)" in extension + assert "function playEntrance()" in extension + assert 'pet.dataset.entering = "true"' in extension + assert "const drawEntrancePose =" in extension + assert "window.requestAnimationFrame(renderEntrance)" in extension + assert "function createThemedPetDataUrl(" in extension + assert "blueDominance < 24" in extension + assert 'window.addEventListener("cognitive-agent:demo-role-change"' not in extension + assert 'class="v2-extension-pet-blink"' in extension + assert "const scheduleBlink =" in extension + assert 'pet.dataset.blinking = "true"' in extension + assert 'class="v2-extension-pet-mouth-closed"' in extension + assert "const animateMouth = () =>" in extension + assert "mouth.animate?.(" in extension + assert "{ opacity: 0, offset: 0.09 }" in extension + assert "{ opacity: 0, offset: 0.41 }" in extension + assert "{ opacity: 0, offset: 0.73 }" in extension + assert "{ duration: 1260" in extension + assert 'class="v2-extension-pet-tail-canvas"' in extension + assert "const runTailWave =" in extension + assert "const requestTailWave =" in extension + assert 'prefers-reduced-motion: reduce' not in extension + assert "tailWaveQueued = true" in extension + assert "window.setTimeout(() => runTailWave(true), 180)" in extension + assert "scheduleTailWave" not in extension + assert 'pet.dataset.tailWaving = "true"' in extension + assert "const tailMotionFrames = [" in extension + assert "const sampleTailOffset =" in extension + assert "sampleTailOffset(tailPose, distanceFromBase)" in extension + assert "clampToSegment = false" in extension + assert "Math.max(Math.min(start, end)" in extension + assert "const sampleTravelingTailOffset =" not in extension + assert 'document.visibilityState !== "visible"' in extension assert ".v2-extension-pet-body" in styles - assert "@keyframes extension-pet-blink" in styles + assert ".v2-extension-pet-entrance-canvas" in styles + assert '.v2-extension-pet[data-entering="true"] .v2-extension-pet-image' in styles + assert '.v2-extension-pet[data-blinking="true"] .v2-extension-pet-blink' in styles + assert ".v2-extension-pet-mouth-closed" in styles + assert "width: 176px;" in styles + assert "font-size: 13px;" in styles + assert '.v2-extension-pet[data-tail-waving="true"] .v2-extension-pet-tail-canvas' in styles + assert '.v2-extension-pet[data-tail-waving="true"] .v2-extension-pet-image' in styles + assert "position: fixed;" in styles + assert "extension-pet-float" not in styles + assert '[data-module="self-extension"][data-demo-role="admin"] .v2-sidebar' not in styles + assert '[data-module="self-extension"][data-demo-role="admin"] .v2-avatar' not in styles -def test_virtual_modules_reset_but_physical_sessions_remain_authoritative() -> None: +def test_orchestration_session_reset_remains_available() -> None: orchestration = source("app.js") - calibration = source("self-calibration.js") - repair = source("self-repair.js") assert 'sessionStorage.removeItem("cognitive-agent.conversation-id")' in orchestration - assert 'api("/session/reset")' in calibration - assert 'if (state.transport?.mode === "simulation")' in calibration - assert 'if (backendMode === "bench")' in repair - assert 'await apiPost("/runtime/reset-statistics")' in repair diff --git a/tests/unit/test_self_calibration.py b/tests/unit/test_self_calibration.py index 6755754..5a43450 100644 --- a/tests/unit/test_self_calibration.py +++ b/tests/unit/test_self_calibration.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json import tempfile import time from pathlib import Path @@ -10,6 +11,41 @@ from cognitive_agent.application.calibration import protocol from cognitive_agent.application.calibration.service import ApiError, CalibrationService +def test_video_settings_use_webrtc_and_migrate_legacy_rtsp() -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + data_dir = root / "data" + data_dir.mkdir() + (data_dir / "settings.json").write_text( + json.dumps( + { + "mqtt": {"host": "172.20.10.12", "port": 1883, "topic": "zed/seatpose"}, + "video": { + "scheme": "http", + "host": "172.20.10.12", + "port": 8554, + "path": "zed", + "transport": "webrtc", + }, + } + ), + encoding="utf-8", + ) + + service = CalibrationService(root) + settings = service.snapshot()["settings"] + + assert settings["mqtt"]["host"] == "172.20.10.6" + assert settings["video"] == { + "scheme": "http", + "host": "172.20.10.6", + "port": 8889, + "path": "zed", + "transport": "webrtc", + } + assert service.start_video()["video"]["state"] == "ready" + + def test_protocol_matches_android_golden_vectors() -> None: assert protocol.crc8(b"123456789") == 0x4B vectors = ( diff --git a/座椅部分功能CAN矩阵表.xlsx b/座椅部分功能CAN矩阵表.xlsx deleted file mode 100755 index 7710a16..0000000 Binary files a/座椅部分功能CAN矩阵表.xlsx and /dev/null differ