File size: 170,991 Bytes
d813d66
1
var sceneScaffolder=pc.createScript("sceneScaffolder");sceneScaffolder.prototype.initialize=function(){var e=this.app,t=e.root.findByName("Camera");t&&t.destroy();var o=e.root.findByName("Light");o&&o.destroy();var a=new pc.Entity("SurgeonCamera");a.addComponent("camera",{clearColor:new pc.Color(.95,.98,1),nearClip:.1,farClip:100,fov:60}),a.setPosition(0,1.7,6.5),a.addComponent("script"),a.script.create("cameraController"),a.script.create("interactionController"),e.root.addChild(a),this.createCrosshairUI(e);var n=new pc.Entity("MainSurgicalLight");n.tags.add("room_entity"),n.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:3,range:15,innerConeAngle:15,outerConeAngle:35,castShadows:!0,shadowBias:.1,shadowDistance:20,shadowResolution:2048}),n.addComponent("render",{type:"box"}),n.setLocalScale(.5,.2,.5),n.addComponent("collision",{type:"box"}),n.addComponent("rigidbody",{type:"static"}),n.setPosition(0,4,0),n.setEulerAngles(90,0,0),e.root.addChild(n);var r=new pc.Entity("SecondarySurgicalLight");r.tags.add("room_entity"),r.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:2.5,range:12,innerConeAngle:20,outerConeAngle:40,castShadows:!0,shadowBias:.1}),r.setPosition(-1.5,3.8,-.5),r.setEulerAngles(75,15,0),e.root.addChild(r);var d=new pc.Entity("AmbientRoomLight");d.tags.add("room_entity"),d.addComponent("light",{type:"directional",color:new pc.Color(.9,.95,1),intensity:.4,castShadows:!1}),d.setEulerAngles(30,45,0),e.root.addChild(d);var s=new pc.Entity("SterileFloor");s.tags.add("room_entity");var i=new pc.StandardMaterial;i.diffuse=new pc.Color(.92,.95,.98),i.metalness=.1,i.gloss=.8,i.useMetalness=!0,i.update(),s.addComponent("render",{type:"plane",material:i,receiveShadows:!0,castShadows:!1}),s.setLocalScale(20,1,15),e.root.addChild(s),this.createWall(e,"BackWall",0,2.5,-7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"FrontWall",0,2.5,7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"LeftWall",-10,2.5,0,.2,5,15,new pc.Color(.95,.97,1)),this.createWall(e,"RightWall",10,2.5,0,.2,5,15,new pc.Color(.95,.97,1));var l=new pc.Entity("OperatingTableBase");l.tags.add("room_entity");var c=new pc.StandardMaterial;c.diffuse=new pc.Color(.8,.8,.85),c.metalness=.7,c.gloss=.6,c.useMetalness=!0,c.update(),l.addComponent("render",{type:"cylinder",material:c,castShadows:!0,receiveShadows:!0}),l.setLocalScale(.8,.7,.8),l.setPosition(0,.35,0),e.root.addChild(l);var p=new pc.Entity("OperatingTableSurface");p.tags.add("room_entity");var y=new pc.StandardMaterial;y.diffuse=new pc.Color(.9,.92,.95),y.metalness=.2,y.gloss=.9,y.useMetalness=!0,y.update(),p.addComponent("render",{type:"box",material:y,castShadows:!0,receiveShadows:!0}),p.setLocalScale(2.2,.1,.8),p.setPosition(0,.75,0),p.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(1.1,.05,.4)}),p.addComponent("rigidbody",{type:"static"}),e.root.addChild(p);var m=new pc.Entity("AnesthesiaMachine");m.tags.add("room_entity");var h=new pc.StandardMaterial;h.diffuse=new pc.Color(.7,.75,.8),h.metalness=.8,h.useMetalness=!0,h.update(),m.addComponent("render",{type:"box",material:h,castShadows:!0,receiveShadows:!0}),m.setLocalScale(1.2,1.8,.8),m.setPosition(-4,.9,2),e.root.addChild(m);var C=new pc.Entity("InstrumentTable");C.tags.add("room_entity");var w=new pc.StandardMaterial;w.diffuse=new pc.Color(.85,.87,.9),w.metalness=.6,w.gloss=.8,w.useMetalness=!0,w.update(),C.addComponent("render",{type:"box",material:w,castShadows:!0,receiveShadows:!0}),C.setLocalScale(1.5,1.2,.8),C.setPosition(3,.6,-1),e.root.addChild(C);var S=new pc.Entity("XRayViewer");S.tags.add("room_entity");var f=new pc.StandardMaterial;f.diffuse=new pc.Color(.1,.1,.12),f.metalness=.9,f.useMetalness=!0,f.update(),S.addComponent("render",{type:"box",material:f,castShadows:!0,receiveShadows:!0}),S.setLocalScale(1.8,1.2,.1),S.setPosition(-4,2.5,-6),e.root.addChild(S);var g=new pc.Entity("XRayScreen");g.tags.add("room_entity");var u=new pc.StandardMaterial;u.diffuse=new pc.Color(.9,.95,1),u.emissive=new pc.Color(.3,.35,.4),u.update(),g.addComponent("render",{type:"box",material:u,castShadows:!1,receiveShadows:!1}),g.addComponent("collision",{type:"box"}),g.addComponent("rigidbody",{type:"static"}),g.setLocalScale(1.6,1,.05),g.setPosition(-4,2.5,-5.9),e.root.addChild(g);var v=new pc.Entity("SurgicalLightArm1");v.tags.add("room_entity");var M=new pc.StandardMaterial;M.diffuse=new pc.Color(.9,.9,.92),M.metalness=.8,M.useMetalness=!0,M.update(),v.addComponent("render",{type:"cylinder",material:M,castShadows:!0,receiveShadows:!0}),v.setLocalScale(.15,2,.15),v.setPosition(0,3,0),e.root.addChild(v);var E=new pc.Entity("PatientBody");E.tags.add("room_entity");var b=new pc.StandardMaterial;b.diffuse=new pc.Color(.95,.85,.75),b.metalness=.1,b.gloss=.2,b.useMetalness=!0,b.update(),E.addComponent("render",{type:"box",material:b,castShadows:!0,receiveShadows:!0}),E.addComponent("collision",{type:"box"}),E.addComponent("rigidbody",{type:"static"}),E.setLocalScale(.6,.3,1.8),E.setPosition(0,.95,0),e.root.addChild(E);var _=new pc.Entity("SurgicalDrape");_.tags.add("room_entity");var L=new pc.StandardMaterial;L.diffuse=new pc.Color(.8,.9,.95),L.metalness=0,L.gloss=.1,L.update(),_.addComponent("render",{type:"box",material:L,castShadows:!0,receiveShadows:!0}),_.setLocalScale(.8,.05,2),_.setPosition(0,1.15,0),e.root.addChild(_);var P=new pc.Entity("CArmXRayMachine");P.tags.add("room_entity");var x=new pc.StandardMaterial;x.diffuse=new pc.Color(.75,.78,.82),x.metalness=.7,x.useMetalness=!0,x.update(),P.addComponent("render",{type:"box",material:x,castShadows:!0,receiveShadows:!0}),P.setLocalScale(1,2.2,1.5),P.setPosition(5,1.1,3),P.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(.5,1.1,.75)}),P.addComponent("rigidbody",{type:"static"}),e.root.addChild(P);var B=new pc.Entity("PowerToolsStation");B.tags.add("room_entity");var T=new pc.StandardMaterial;T.diffuse=new pc.Color(.6,.65,.7),T.metalness=.8,T.useMetalness=!0,T.update(),B.addComponent("render",{type:"box",material:T,castShadows:!0,receiveShadows:!0}),B.setLocalScale(.8,1.5,.6),B.setPosition(-3.5,.75,-2.5),e.root.addChild(B);var A=new pc.Entity("BoneCementMixer");A.tags.add("room_entity");var R=new pc.StandardMaterial;R.diffuse=new pc.Color(.85,.85,.88),R.metalness=.6,R.useMetalness=!0,R.update(),A.addComponent("render",{type:"cylinder",material:R,castShadows:!0,receiveShadows:!0}),A.setLocalScale(.4,.8,.4),A.setPosition(2.5,.4,2.5),e.root.addChild(A),this.createVitalSignsMonitor(e,new pc.Vec3(-2,0,3)),this.registerCleanupManager(),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),console.log("Orthopaedic Operating Theatre scaffolded successfully!"),console.log("\nPress SHIFT+C to clear the room (keeps camera and UI)")},sceneScaffolder.prototype.onKeyDown=function(e){e.key===pc.KEY_C&&e.event.shiftKey&&(console.log("[SceneScaffolder] Clearing room..."),this.clearRoom())},sceneScaffolder.prototype.clearRoom=function(){console.log("[SceneScaffolder] Removing room entities...");const e=this.app.root.findByTag("room_entity");console.log(`[SceneScaffolder] Found ${e.length} room entities to remove`);for(let t=e.length-1;t>=0;t--){const o=e[t];if(o&&!o._destroyed)try{o.destroy()}catch(e){console.warn(`[SceneScaffolder] Failed to destroy ${o.name}:`,e)}}console.log("[SceneScaffolder] Room cleared - camera and UI remain")},sceneScaffolder.prototype.registerCleanupManager=function(){console.log("[SceneScaffolder] Registering cleanup manager..."),this.app.cleanupMissionScene=function(){console.log("[Cleanup] Starting mission scene cleanup...");const e=this.root.findByTag("mission_entity");console.log(`[Cleanup] Found ${e.length} mission entities`);for(let t=e.length-1;t>=0;t--){const o=e[t];if(o&&!o._destroyed)try{o.destroy()}catch(e){console.warn(`[Cleanup] Failed to destroy ${o.name}:`,e)}}this.root.findByTag("npc").forEach((e=>{e&&!e._destroyed&&e.destroy()}));this.root.findByTag("item").forEach((e=>{e&&!e._destroyed&&e.destroy()}));["MissionUIScreen","MissionPanel","DialoguePanel","NPCUIScreen"].forEach((e=>{const t=this.root.findByName(e);t&&!t._destroyed&&t.destroy()})),console.log("[Cleanup] Mission scene cleanup complete")}.bind(this.app),this.app.clearRoom=this.clearRoom.bind(this),this.app.safeUpdateMaterial=function(e,t){if(!e||e._destroyed)return!1;if(!e.render||!e.render.material)return!1;try{const o=e.render.material;return t(o),o.update(),!0}catch(t){return console.warn(`[Material] Failed to update material for ${e.name}:`,t),!1}}},sceneScaffolder.prototype.createWall=function(e,t,o,a,n,r,d,s,i){var l=new pc.Entity(t);l.tags.add("room_entity");var c=new pc.StandardMaterial;c.diffuse=i,c.metalness=.1,c.gloss=.3,c.useMetalness=!0,c.update(),l.addComponent("render",{type:"box",material:c,castShadows:!1,receiveShadows:!0}),l.setPosition(o,a,n),l.setLocalScale(r,d,s),e.root.addChild(l)},sceneScaffolder.prototype.createVitalSignsMonitor=function(e,t){var o=new pc.Entity("VitalSignsMonitor");o.tags.add("room_entity"),o.setPosition(t);var a=new pc.Entity("MonitorCartBody");a.tags.add("room_entity");var n=new pc.StandardMaterial;n.diffuse=new pc.Color(.8,.82,.85),n.useMetalness=!0,n.metalness=.4,n.gloss=.5,n.update(),a.addComponent("render",{type:"box",material:n}),a.setLocalScale(.6,1,.5),a.setLocalPosition(0,.5,0),a.addComponent("collision",{type:"box"}),a.addComponent("rigidbody",{type:"static"}),o.addChild(a);var r=new pc.Entity("MonitorScreen");r.tags.add("room_entity");var d=new pc.StandardMaterial;d.diffuse.set(.05,.05,.1),d.emissive.set(.02,.02,.05),d.update(),r.addComponent("render",{type:"box",material:d}),r.setLocalScale(.58,.45,.03),r.setLocalPosition(0,.7,.27),r.addComponent("collision",{type:"box"}),r.addComponent("rigidbody",{type:"static"}),o.addChild(r);var s=new pc.Entity("MonitorBase");return s.tags.add("room_entity"),s.addComponent("render",{type:"box",material:n}),s.setLocalScale(.7,.05,.7),s.setLocalPosition(0,.025,0),o.addChild(s),e.root.addChild(o),o},sceneScaffolder.prototype.createCrosshairUI=function(e){var t=new pc.Entity("UIScreen");t.addComponent("screen",{referenceResolution:new pc.Vec2(1280,720),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),e.root.addChild(t);var o=new pc.Entity("CrosshairOutline");o.addComponent("image",{type:pc.ELEMENTTYPE_IMAGE,anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:6,height:6,color:new pc.Color(0,0,0,.5)}),t.addChild(o);var a=new pc.Entity("CrosshairDot");a.addComponent("image",{type:pc.ELEMENTTYPE_IMAGE,anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:2,height:2,color:new pc.Color(1,1,1,.8)}),t.addChild(a),console.log("Compound Crosshair UI created.")};var CameraController=pc.createScript("cameraController");CameraController.attributes.add("movementSpeed",{type:"number",default:5,title:"Movement Speed"}),CameraController.attributes.add("keyboardRotationSpeed",{type:"number",default:90,title:"Keyboard Rotation Speed"}),CameraController.attributes.add("pitchLimit",{type:"number",default:89,title:"Pitch Angle Limit"}),CameraController.attributes.add("useControlManager",{type:"boolean",default:!0,title:"Use Control Manager"}),CameraController.prototype.initialize=function(){console.log("CameraController: Initializing..."),this.eulers=new pc.Vec3;var e=this.entity.getEulerAngles();if(this.eulers.set(e.x,e.y,e.z),this.pitch=this.eulers.x,this.yaw=this.eulers.y,this.moveDirection=new pc.Vec3,this.controlManager=null,this.useControlManager){const e=this.app.root.findComponent("script",(e=>e.has("controlManager")));e?(this.controlManager=e.entity.script.controlManager,console.log("CameraController: Using Control Manager")):(console.warn("CameraController: Control Manager not found, using direct input"),this.useControlManager=!1)}console.log("CameraController initialized. Controls:"),console.log("- WASD: Move"),console.log("- Q/E: Rotate"),console.log("- Arrow Keys: Look up/down")},CameraController.prototype.update=function(e){this.shouldProcessInput()&&(this.processMovement(e),this.processRotation(e),this.entity.setLocalEulerAngles(this.pitch,this.yaw,0))},CameraController.prototype.shouldProcessInput=function(){return!this.useControlManager||!this.controlManager||!this.controlManager.blockedKeys.has("W")},CameraController.prototype.processMovement=function(e){var t=this.app,o=this.movementSpeed,r=0,i=0;if(this.useControlManager&&this.controlManager?(this.controlManager.isKeyActive("W")&&(i=1),this.controlManager.isKeyActive("S")&&(i=-1),this.controlManager.isKeyActive("A")&&(r=-1),this.controlManager.isKeyActive("D")&&(r=1)):(t.keyboard.isPressed(pc.KEY_W)&&(i=1),t.keyboard.isPressed(pc.KEY_S)&&(i=-1),t.keyboard.isPressed(pc.KEY_A)&&(r=-1),t.keyboard.isPressed(pc.KEY_D)&&(r=1)),0!==r||0!==i){var a=this.entity.forward.clone();a.y=0,a.normalize();var n=this.entity.right.clone();n.y=0,n.normalize(),this.moveDirection.set(0,0,0),this.moveDirection.add(a.mulScalar(i)),this.moveDirection.add(n.mulScalar(r)),this.moveDirection.lengthSq()>0&&(this.moveDirection.normalize().mulScalar(o*e),this.entity.translate(this.moveDirection))}},CameraController.prototype.processRotation=function(e){var t=this.app,o=0;this.useControlManager&&this.controlManager?(this.controlManager.isKeyActive("Q")&&(o=1),this.controlManager.isKeyActive("E")&&(o=-1)):(t.keyboard.isPressed(pc.KEY_Q)&&(o=1),t.keyboard.isPressed(pc.KEY_E)&&(o=-1)),this.yaw+=o*this.keyboardRotationSpeed*e;var r=0;this.useControlManager&&this.controlManager?(this.controlManager.isKeyActive("UP")&&(r=-1),this.controlManager.isKeyActive("DOWN")&&(r=1)):(t.keyboard.isPressed(pc.KEY_UP)&&(r=-1),t.keyboard.isPressed(pc.KEY_DOWN)&&(r=1)),this.pitch+=r*this.keyboardRotationSpeed*e,this.pitch=pc.math.clamp(this.pitch,-this.pitchLimit,this.pitchLimit)};var SceneScaffolder=pc.createScript("sceneScaffolder");SceneScaffolder.prototype.initialize=function(){var e=this.app,a=e.root.findByName("Camera");a&&a.destroy();var o=e.root.findByName("Light");o&&o.destroy();var t=new pc.Entity("MyControllableCamera");t.addComponent("camera",{clearColor:new pc.Color(.1,.1,.1),nearClip:.1,farClip:1e3,fov:45}),t.setPosition(0,1.6,5),t.addComponent("script"),t.script.create("cameraController"),e.root.addChild(t);var n=new pc.Entity("MyLight");n.addComponent("light",{type:"directional",color:new pc.Color(1,1,1),intensity:1,castShadows:!0,shadowBias:.2,shadowDistance:50,normalOffsetBias:.05,shadowResolution:2048}),n.setEulerAngles(45,30,0),e.root.addChild(n);var r=new pc.Entity("GroundPlane"),d=new pc.StandardMaterial;d.diffuse=new pc.Color(.5,.5,.5),d.update(),r.addComponent("render",{type:"plane",material:d,castShadows:!1,receiveShadows:!0}),r.setLocalScale(50,1,50),e.root.addChild(r);var i=new pc.Entity("MyCube"),s=new pc.StandardMaterial;s.diffuse=new pc.Color(1,0,0),s.shininess=50,s.update(),i.addComponent("render",{type:"box",material:s,castShadows:!0,receiveShadows:!0}),i.setPosition(0,1,0),e.root.addChild(i);var l=new pc.Entity("MySphere"),c=new pc.StandardMaterial;c.diffuse=new pc.Color(0,0,1),c.shininess=70,c.metalness=.3,c.useMetalness=!0,c.update(),l.addComponent("render",{type:"sphere",material:c,castShadows:!0,receiveShadows:!0}),l.setPosition(3,1.5,2),e.root.addChild(l),console.log("Controllable 3D environment scaffolded from code!")};var OrthopaedicTheatreScaffolder=pc.createScript("orthopaedicTheatreScaffolder");OrthopaedicTheatreScaffolder.prototype.initialize=function(){var e=this.app,a=e.root.findByName("Camera");a&&a.destroy();var t=e.root.findByName("Light");t&&t.destroy();var o=new pc.Entity("SurgeonCamera");o.addComponent("camera",{clearColor:new pc.Color(.95,.98,1),nearClip:.1,farClip:100,fov:60}),o.setPosition(0,1.7,8),o.addComponent("script"),o.script.create("cameraController"),e.root.addChild(o);var n=new pc.Entity("MainSurgicalLight");n.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:3,range:15,innerConeAngle:15,outerConeAngle:35,castShadows:!0,shadowBias:.1,shadowDistance:20,shadowResolution:2048}),n.setPosition(0,4,0),n.setEulerAngles(90,0,0),e.root.addChild(n);var s=new pc.Entity("SecondarySurgicalLight");s.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:2.5,range:12,innerConeAngle:20,outerConeAngle:40,castShadows:!0,shadowBias:.1}),s.setPosition(-1.5,3.8,-.5),s.setEulerAngles(75,15,0),e.root.addChild(s);var r=new pc.Entity("AmbientRoomLight");r.addComponent("light",{type:"directional",color:new pc.Color(.9,.95,1),intensity:.4,castShadows:!1}),r.setEulerAngles(30,45,0),e.root.addChild(r);var d=new pc.Entity("SterileFloor"),l=new pc.StandardMaterial;l.diffuse=new pc.Color(.92,.95,.98),l.metalness=.1,l.gloss=.8,l.useMetalness=!0,l.update(),d.addComponent("render",{type:"plane",material:l,receiveShadows:!0,castShadows:!1}),d.setLocalScale(20,1,15),e.root.addChild(d),this.createWall(e,"BackWall",0,2.5,-7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"FrontWall",0,2.5,7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"LeftWall",-10,2.5,0,.2,5,15,new pc.Color(.95,.97,1)),this.createWall(e,"RightWall",10,2.5,0,.2,5,15,new pc.Color(.95,.97,1));var i=new pc.Entity("OperatingTableBase"),c=new pc.StandardMaterial;c.diffuse=new pc.Color(.8,.8,.85),c.metalness=.7,c.gloss=.6,c.useMetalness=!0,c.update(),i.addComponent("render",{type:"cylinder",material:c,castShadows:!0,receiveShadows:!0}),i.setLocalScale(.8,.7,.8),i.setPosition(0,.35,0),e.root.addChild(i);var p=new pc.Entity("OperatingTableSurface"),w=new pc.StandardMaterial;w.diffuse=new pc.Color(.9,.92,.95),w.metalness=.2,w.gloss=.9,w.useMetalness=!0,w.update(),p.addComponent("render",{type:"box",material:w,castShadows:!0,receiveShadows:!0}),p.setLocalScale(2.2,.1,.8),p.setPosition(0,.75,0),e.root.addChild(p);var h=new pc.Entity("AnesthesiaMachine"),S=new pc.StandardMaterial;S.diffuse=new pc.Color(.7,.75,.8),S.metalness=.8,S.useMetalness=!0,S.update(),h.addComponent("render",{type:"box",material:S,castShadows:!0,receiveShadows:!0}),h.setLocalScale(1.2,1.8,.8),h.setPosition(-4,.9,2),e.root.addChild(h);var C=new pc.Entity("InstrumentTable"),m=new pc.StandardMaterial;m.diffuse=new pc.Color(.85,.87,.9),m.metalness=.6,m.gloss=.8,m.useMetalness=!0,m.update(),C.addComponent("render",{type:"box",material:m,castShadows:!0,receiveShadows:!0}),C.setLocalScale(1.5,1.2,.8),C.setPosition(3,.6,-1),e.root.addChild(C);var u=new pc.Entity("XRayViewer"),y=new pc.StandardMaterial;y.diffuse=new pc.Color(.1,.1,.12),y.metalness=.9,y.useMetalness=!0,y.update(),u.addComponent("render",{type:"box",material:y,castShadows:!0,receiveShadows:!0}),u.setLocalScale(1.8,1.2,.1),u.setPosition(-4,2.5,-6),e.root.addChild(u);var g=new pc.Entity("XRayScreen"),f=new pc.StandardMaterial;f.diffuse=new pc.Color(.9,.95,1),f.emissive=new pc.Color(.3,.35,.4),f.update(),g.addComponent("render",{type:"box",material:f,castShadows:!1,receiveShadows:!1}),g.setLocalScale(1.6,1,.05),g.setPosition(-4,2.5,-5.9),e.root.addChild(g);var v=new pc.Entity("SurgicalLightArm1"),M=new pc.StandardMaterial;M.diffuse=new pc.Color(.9,.9,.92),M.metalness=.8,M.useMetalness=!0,M.update(),v.addComponent("render",{type:"cylinder",material:M,castShadows:!0,receiveShadows:!0}),v.setLocalScale(.15,2,.15),v.setPosition(0,3,0),e.root.addChild(v);var E=new pc.Entity("PatientBody"),L=new pc.StandardMaterial;L.diffuse=new pc.Color(.95,.85,.75),L.metalness=.1,L.gloss=.2,L.useMetalness=!0,L.update(),E.addComponent("render",{type:"box",material:L,castShadows:!0,receiveShadows:!0}),E.setLocalScale(.6,.3,1.8),E.setPosition(0,.95,0),e.root.addChild(E);var P=new pc.Entity("SurgicalDrape"),b=new pc.StandardMaterial;b.diffuse=new pc.Color(.8,.9,.95),b.metalness=0,b.gloss=.1,b.update(),P.addComponent("render",{type:"box",material:b,castShadows:!0,receiveShadows:!0}),P.setLocalScale(.8,.05,2),P.setPosition(0,1.15,0),e.root.addChild(P);var x=new pc.Entity("CArmXRayMachine"),A=new pc.StandardMaterial;A.diffuse=new pc.Color(.75,.78,.82),A.metalness=.7,A.useMetalness=!0,A.update(),x.addComponent("render",{type:"box",material:A,castShadows:!0,receiveShadows:!0}),x.setLocalScale(1,2.2,1.5),x.setPosition(5,1.1,3),e.root.addChild(x);var T=new pc.Entity("PowerToolsStation"),W=new pc.StandardMaterial;W.diffuse=new pc.Color(.6,.65,.7),W.metalness=.8,W.useMetalness=!0,W.update(),T.addComponent("render",{type:"box",material:W,castShadows:!0,receiveShadows:!0}),T.setLocalScale(.8,1.5,.6),T.setPosition(-3.5,.75,-2.5),e.root.addChild(T);var B=new pc.Entity("BoneCementMixer"),O=new pc.StandardMaterial;O.diffuse=new pc.Color(.85,.85,.88),O.metalness=.6,O.useMetalness=!0,O.update(),B.addComponent("render",{type:"cylinder",material:O,castShadows:!0,receiveShadows:!0}),B.setLocalScale(.4,.8,.4),B.setPosition(2.5,.4,2.5),e.root.addChild(B),console.log("Orthopaedic Operating Theatre scaffolded successfully!"),console.log("Environment includes:"),console.log("- Sterile room with clinical lighting"),console.log("- Central operating table with patient"),console.log("- Anesthesia machine and monitoring equipment"),console.log("- X-ray viewer and C-arm machine"),console.log("- Surgical instrument tables"),console.log("- Orthopaedic-specific equipment (drills, cement mixer)"),console.log("- Proper surgical lighting setup")},OrthopaedicTheatreScaffolder.prototype.createWall=function(e,a,t,o,n,s,r,d,l){var i=new pc.Entity(a),c=new pc.StandardMaterial;c.diffuse=l,c.metalness=.1,c.gloss=.3,c.useMetalness=!0,c.update(),i.addComponent("render",{type:"box",material:c,castShadows:!1,receiveShadows:!0}),i.setPosition(t,o,n),i.setLocalScale(s,r,d),e.root.addChild(i)};var InteractionController=pc.createScript("interactionController");InteractionController.attributes.add("interactionDistance",{type:"number",default:5,title:"Interaction Distance"}),InteractionController.attributes.add("highlightColor",{type:"rgba",default:[.4,.4,0,1],title:"Highlight Color (Emissive)"}),InteractionController.prototype.initialize=function(){this.highlightedEntity=null,this.originalEmissive=new pc.Color;const t=this.app.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),i=this.entity.camera,e=i.layers;-1===e.indexOf(t.id)&&(i.layers=e.concat(t.id)),console.log("Interaction Controller is active. Look at an object to highlight it, press 'F' to interact.")},InteractionController.prototype.update=function(t){if("undefined"!=typeof Ammo){var i=this.entity.getPosition(),e=(new pc.Vec3).copy(this.entity.forward).mulScalar(this.interactionDistance).add(i),n=this.app.systems.rigidbody.raycastFirst(i,e),o=n?n.entity:null;o!==this.highlightedEntity&&(this.highlightedEntity&&this.setHighlight(this.highlightedEntity,!1),o&&this.setHighlight(o,!0),this.highlightedEntity=o),this.app.keyboard.wasPressed(pc.KEY_F)&&this.highlightedEntity&&this.interactWith(this.highlightedEntity)}},InteractionController.prototype.interactWith=function(t){if(console.log("Interacting with:",t.name),t.tags&&t.tags.has("npc")&&t.npcData)return console.log("[Interaction] NPC detected:",t.npcData.name),this.app.fire("npc:interact",t.npcData.id),void this.app.fire("interaction:triggered",t.name);var i=t;if(t.parent&&"VitalSignsMonitor"===t.parent.name&&(i=t.parent),"VitalSignsMonitor"===i.name){var e=i.findByName("MonitorScreen");if(e){void 0===e.isOn&&(e.isOn=!1),e.isOn=!e.isOn;var n=e.render.material;n.emissive.set(e.isOn?.5:0,e.isOn?.8:0,e.isOn?1:0),n.update(),console.log("Monitor screen state set to:",e.isOn?"ON":"OFF")}}else if("PatientBody"===t.name){var o=this.app.root.findByName("SurgicalDrape");o&&(o.enabled=!o.enabled,console.log("Surgical drape visibility set to:",o.enabled))}else if("MainSurgicalLight"===t.name)void 0===t.isAdjusted&&(t.isAdjusted=!1),t.isAdjusted=!t.isAdjusted,t.isAdjusted?(t.setEulerAngles(75,20,0),console.log("Surgical light adjusted.")):(t.setEulerAngles(90,0,0),console.log("Surgical light reset."));else if("XRayScreen"===t.name){void 0===t.colorIndex&&(t.colorIndex=0);var r=[new pc.Color(.9,.95,1),new pc.Color(.9,1,.9),new pc.Color(1,.9,.9)];t.colorIndex=(t.colorIndex+1)%r.length;var a=t.render.material;a.diffuse.copy(r[t.colorIndex]),a.update(),console.log("X-Ray screen color changed to index:",t.colorIndex)}t&&t.name&&this.app.fire("interaction:triggered",t.name),i&&i!==t&&i.name&&this.app.fire("interaction:triggered",i.name)},InteractionController.prototype.setHighlight=function(t,i){if((!t||"MonitorScreen"!==t.name)&&t&&t.render&&t.render.material){var e=t.render.material;i?(this.originalEmissive.copy(e.emissive),e.emissive.set(this.highlightColor.r,this.highlightColor.g,this.highlightColor.b)):e.emissive.copy(this.originalEmissive),e.update()}};var GameManager=pc.createScript("gameManager");GameManager.attributes.add("gameData",{type:"asset",assetType:"text",title:"Game Data JSON"}),GameManager.prototype.initialize=function(){this.storyData=null,this.currentLocation="tavern",this.currentRoom="start",this.isUiReady=!1,this.app.on("ui:choiceMade",this.onChoiceMade,this),this.app.on("ui:ready",this.onUiReady,this),this.gameData&&this.gameData.resource?(this.storyData=JSON.parse(this.gameData.resource),console.log("GameManager: Data loaded and parsed."),this.isUiReady&&this.displayCurrentState()):console.error("GameManager: Game Data JSON asset is not linked or has not loaded yet.")},GameManager.prototype.onUiReady=function(){console.log("GameManager: Received 'ui:ready' event."),this.isUiReady=!0,this.storyData&&this.displayCurrentState()},GameManager.prototype.displayCurrentState=function(){if(this.storyData&&this.isUiReady){var t=this.storyData[this.currentLocation][this.currentRoom];t?(console.log("GameManager: Firing 'story:display' event for room:",this.currentRoom),this.app.fire("story:display",{description:t.description,choices:t.choices})):console.error("GameManager: Could not find room data for:",this.currentLocation,this.currentRoom)}},GameManager.prototype.onChoiceMade=function(t){if(this.storyData){var a=this.storyData[this.currentLocation][this.currentRoom].transitions[t];if(a){if(a.includes("_")){var e=a.split("_");this.currentLocation=e[0],this.currentRoom=e[1]}else this.currentRoom=a;this.displayCurrentState()}else console.error("GameManager: No transition found for choice:",t)}};var GameAutoLocationDatabase=pc.createScript("gameAutoLocationDatabase");GameAutoLocationDatabase.prototype.initialize=function(){},GameAutoLocationDatabase.prototype.update=function(a){};var SceneIntegrationManager=pc.createScript("sceneIntegrationManager");SceneIntegrationManager.attributes.add("integrationRules",{type:"json",schema:[{name:"tagMatch",type:"string",default:"interactive"},{name:"scriptToAdd",type:"string",default:"interactionController"},{name:"componentConfig",type:"json",default:{}}],array:!0,title:"Integration Rules"}),SceneIntegrationManager.prototype.initialize=function(){this.sceneTypes={MEDICAL:"medical",SCIFI:"scifi",FANTASY:"fantasy",CUSTOM:"custom"},this.currentSceneType=null,this.mappings=new Map,this.app.on("scene:loaded",this.onSceneLoaded,this),this.app.on("scene:analyze",this.analyzeScene,this),this.integrationRules&&0!==this.integrationRules.length||this.setupDefaultRules(),console.log("[Integration] Scene Integration Manager ready")},SceneIntegrationManager.prototype.setupDefaultRules=function(){this.integrationRules=[{tagMatch:"interactive",scriptToAdd:"dynamicInteraction",componentConfig:{interactionDistance:5}},{tagMatch:"character",scriptToAdd:"characterBehavior",componentConfig:{dialogueEnabled:!0}}]},SceneIntegrationManager.prototype.onSceneLoaded=function(e){switch(console.log("[Integration] Processing loaded scene..."),this.currentSceneType=this.detectSceneType(e),console.log(`[Integration] Detected scene type: ${this.currentSceneType}`),this.currentSceneType){case this.sceneTypes.MEDICAL:this.integrateMedicalScene(e);break;case this.sceneTypes.SCIFI:this.integrateSciFiScene(e);break;default:this.integrateGenericScene(e)}this.applyIntegrationRules(e),this.generateSceneReport(e)},SceneIntegrationManager.prototype.detectSceneType=function(e){const t=[],n=new Set,collectData=e=>{t.push(e.name.toLowerCase()),e.tags._list.forEach((e=>n.add(e.toLowerCase()))),e.children.forEach(collectData)};return e.children.forEach(collectData),t.some((e=>e.includes("patient")||e.includes("surgical")||e.includes("medical")))?this.sceneTypes.MEDICAL:n.has("alien")||n.has("robot")||n.has("spacecraft")?this.sceneTypes.SCIFI:this.sceneTypes.CUSTOM},SceneIntegrationManager.prototype.integrateSciFiScene=function(e){console.log("[Integration] Applying Sci-Fi scene integration...");e.findByTag("interactive").forEach((e=>{let t="default";e.tags._list.forEach((e=>{e.startsWith("ui_display_")&&(t=e.replace("ui_display_",""))})),this.mappings.set(e.name,{type:"interactive",interactionType:t,gameEvent:this.mapInteractionToGameEvent(t)}),this.addInteractionFeedback(e)}));e.findByTag("character").forEach((e=>{this.processSciFiCharacter(e)}))},SceneIntegrationManager.prototype.mapInteractionToGameEvent=function(e){return{toggle:"story:choice",button:"story:action",screen:"story:display",overlay:"ui:overlay",cursor:"ui:focus",window:"ui:window"}[e]||"interaction:generic"},SceneIntegrationManager.prototype.processSciFiCharacter=function(e){const t={name:e.name,role:null,background:null,skills:[],traits:[],equipment:[]};e.tags._list.forEach((e=>{e.startsWith("role_")?t.role=e.replace("role_",""):e.startsWith("background_")?t.background=e.replace("background_",""):e.startsWith("skill_")?t.skills.push(e.replace("skill_","")):e.startsWith("trait_")?t.traits.push(e.replace("trait_","")):e.startsWith("equipment_")&&t.equipment.push(e.replace("equipment_",""))})),this.mappings.set(e.name,{type:"character",data:t}),e.script||e.addComponent("script"),this.addCharacterController(e,t)},SceneIntegrationManager.prototype.addCharacterController=function(e,t){const n=pc.createScript("characterBehavior_"+e.name);n.prototype.initialize=function(){this.data=t,this.interactionDistance=3,this.player=this.app.root.findByName("SurgeonCamera")||this.app.root.findByName("player")},n.prototype.update=function(e){if(!this.player)return;this.entity.getPosition().distance(this.player.getPosition())<this.interactionDistance?this.nearPlayer||(this.nearPlayer=!0,this.app.fire("character:nearby",this.entity.name,this.data)):this.nearPlayer=!1},pc.registerScript(n,"characterBehavior_"+e.name),e.script.create("characterBehavior_"+e.name)},SceneIntegrationManager.prototype.addInteractionFeedback=function(e){if(!e.render)return;const t=e.render.material;t&&(e.originalEmissive=t.emissive.clone(),e.highlightColor=new pc.Color(.3,.3,.5))},SceneIntegrationManager.prototype.applyIntegrationRules=function(e){console.log("[Integration] Applying custom integration rules..."),this.integrationRules.forEach((t=>{e.findByTag(t.tagMatch).forEach((e=>{if(console.log(`[Integration] Applying rule to ${e.name}: ${t.scriptToAdd}`),e.script||e.addComponent("script"),pc.ScriptRegistry.get(t.scriptToAdd)){if(!e.script.has(t.scriptToAdd)){e.script.create(t.scriptToAdd,{attributes:t.componentConfig})}}else console.warn(`[Integration] Script '${t.scriptToAdd}' not found in registry`)}))}))},SceneIntegrationManager.prototype.generateSceneReport=function(e){const t={sceneType:this.currentSceneType,stats:{totalEntities:0,characters:[],interactives:[],unmappedEntities:[]},mappings:[]},processEntity=e=>{t.stats.totalEntities++;const n=this.mappings.get(e.name);n?(t.mappings.push({entity:e.name,mapping:n}),"character"===n.type?t.stats.characters.push(n.data):"interactive"===n.type&&t.stats.interactives.push({name:e.name,type:n.interactionType,event:n.gameEvent})):e.script&&e.script._scripts.length>0&&t.stats.unmappedEntities.push(e.name),e.children.forEach(processEntity)};return e.children.forEach(processEntity),console.log("[Integration] Scene Report:"),console.log("========================"),console.log(`Type: ${t.sceneType}`),console.log(`Total Entities: ${t.stats.totalEntities}`),console.log(`Characters: ${t.stats.characters.length}`),console.log(`Interactives: ${t.stats.interactives.length}`),console.log(`Unmapped: ${t.stats.unmappedEntities.length}`),console.log("========================"),this.lastReport=t,this.app.fire("scene:report",t),t},SceneIntegrationManager.prototype.getEntityMapping=function(e){return this.mappings.get(e)},SceneIntegrationManager.prototype.getMappingsByType=function(e){const t=[];return this.mappings.forEach(((n,a)=>{n.type===e&&t.push({entity:a,...n})})),t},SceneIntegrationManager.prototype.analyzeScene=function(){const e=this.app.root.findComponent("sceneLoader");return e&&e.currentSceneRoot?this.generateSceneReport(e.currentSceneRoot):null};var StorySceneBridge=pc.createScript("storySceneBridge");StorySceneBridge.attributes.add("sceneMapping",{type:"json",schema:[{name:"storyLocation",type:"string",default:"tavern"},{name:"sceneUrl",type:"string",default:""},{name:"sceneType",type:"string",default:"medical"}],array:!0,title:"Story Location to Scene Mapping"}),StorySceneBridge.prototype.initialize=function(){this.gameManager=null,this.sceneLoader=null,this.integrationManager=null,this.currentStoryLocation=null,this.interactionMappings=new Map,this.findRequiredComponents(),this.app.on("story:display",this.onStoryDisplay,this),this.app.on("ui:choiceMade",this.onChoiceMade,this),this.app.on("interaction:triggered",this.onSceneInteraction,this),this.app.on("character:nearby",this.onCharacterNearby,this),this.setupDebugCommands(),console.log("[Bridge] Story-Scene Bridge initialized")},StorySceneBridge.prototype.findRequiredComponents=function(){const e=this.app.root.findComponent("script",(e=>e.has("gameManager")));e&&(this.gameManager=e.entity.script.gameManager);const t=this.app.root.findComponent("script",(e=>e.has("sceneLoader")));t&&(this.sceneLoader=t.entity.script.sceneLoader);const n=this.app.root.findComponent("script",(e=>e.has("sceneIntegrationManager")));n&&(this.integrationManager=n.entity.script.sceneIntegrationManager)},StorySceneBridge.prototype.setupDebugCommands=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,(e=>{switch(e.key){case pc.KEY_I:this.showCurrentState();break;case pc.KEY_M:this.showMappings();break;case pc.KEY_T:this.testInteraction()}}))},StorySceneBridge.prototype.onStoryDisplay=function(e){if(this.gameManager){const e=this.gameManager.currentLocation;e!==this.currentStoryLocation&&(console.log(`[Bridge] Story location changed: ${this.currentStoryLocation} -> ${e}`),this.currentStoryLocation=e,this.checkSceneTransition(e))}this.mapChoicesToScene(e.choices)},StorySceneBridge.prototype.checkSceneTransition=function(e){const t=this.sceneMapping.find((t=>t.storyLocation===e));t?(console.log(`[Bridge] Loading scene for location: ${e}`),this.sceneLoader&&(this.currentSceneMapping=t,t.sceneUrl&&(this.sceneLoader.sceneSource="url",this.sceneLoader.sceneUrl=t.sceneUrl,this.sceneLoader.loadScene()))):console.log(`[Bridge] No scene mapping for location: ${e}`)},StorySceneBridge.prototype.mapChoicesToScene=function(e){if(!e||!this.integrationManager)return;this.interactionMappings.clear();const t=this.integrationManager.getMappingsByType("interactive");e.forEach(((e,n)=>{if(n<t.length){const o=t[n];this.interactionMappings.set(o.entity,{choice:e,index:n}),console.log(`[Bridge] Mapped "${e}" to ${o.entity}`),this.updateInteractiveVisual(o.entity,e)}}))},StorySceneBridge.prototype.updateInteractiveVisual=function(e,t){if(!this.sceneLoader)return;const n=this.sceneLoader.findInScene(e);if(n&&!n.findByName("ChoiceLabel")){const e=new pc.Entity("ChoiceLabel");e.addComponent("element",{type:"text",text:t,fontSize:16,color:new pc.Color(1,1,1),opacity:.8}),e.setLocalPosition(0,2,0),n.addChild(e),e.addComponent("script");const o=pc.createScript("billboard");o.prototype.update=function(){const e=this.app.root.findByName("SurgeonCamera");e&&this.entity.lookAt(e.getPosition())},pc.registerScript(o,"billboard"),e.script.create("billboard")}},StorySceneBridge.prototype.onSceneInteraction=function(e){console.log(`[Bridge] Scene interaction with: ${e}`);const t=this.interactionMappings.get(e);t?(console.log(`[Bridge] Triggering story choice: "${t.choice}"`),this.app.fire("ui:choiceMade",t.choice)):this.handleUnmappedInteraction(e)},StorySceneBridge.prototype.onCharacterNearby=function(e,t){console.log(`[Bridge] Character nearby: ${e}`,t);const n=this.generateCharacterDescription(t);this.app.fire("story:display",{description:n,choices:this.generateCharacterChoices(t)})},StorySceneBridge.prototype.generateCharacterDescription=function(e){const{role:t,background:n,traits:o}=e;let i=`You encounter a ${t}`;return n&&(i+=` with a ${n} background`),o&&o.length>0&&(i+=`. They appear to be ${o.join(" and ")}`),i+=".",i},StorySceneBridge.prototype.generateCharacterChoices=function(e){const t=[];return e.skills&&e.skills.includes("Diplomacy")&&t.push("Negotiate peacefully"),e.equipment&&e.equipment.includes("Scanner")&&t.push("Ask about their equipment"),t.push("Greet them"),t.push("Walk away"),t},StorySceneBridge.prototype.handleUnmappedInteraction=function(e){if(!this.integrationManager)return;const t=this.integrationManager.getEntityMapping(e);t&&t.gameEvent&&(console.log(`[Bridge] Firing game event: ${t.gameEvent}`),this.app.fire(t.gameEvent,e))},StorySceneBridge.prototype.onChoiceMade=function(e){console.log(`[Bridge] Story choice made: "${e}"`),this.interactionMappings.forEach(((t,n)=>{t.choice===e&&this.showChoiceFeedback(n)}))},StorySceneBridge.prototype.showChoiceFeedback=function(e){if(!this.sceneLoader)return;const t=this.sceneLoader.findInScene(e);if(!t)return;const n=t.getLocalScale().clone();t.setLocalScale(1.2*n.x,1.2*n.y,1.2*n.z),setTimeout((()=>{t.setLocalScale(n)}),200)},StorySceneBridge.prototype.showCurrentState=function(){if(console.log("[Bridge] Current State:"),console.log("==================="),console.log(`Story Location: ${this.currentStoryLocation}`),console.log(`Active Mappings: ${this.interactionMappings.size}`),this.sceneLoader){const e=this.sceneLoader.getSceneStats();console.log(`Scene Loaded: ${e.loaded}`),e.loaded&&(console.log(`- Entities: ${e.entityCount}`),console.log(`- Characters: ${e.characters.length}`),console.log(`- Interactives: ${e.interactives.length}`))}console.log("===================")},StorySceneBridge.prototype.showMappings=function(){console.log("[Bridge] Current Interaction Mappings:"),console.log("===================================="),this.interactionMappings.forEach(((e,t)=>{console.log(`${t} -> "${e.choice}"`)})),console.log("====================================")},StorySceneBridge.prototype.testInteraction=function(){console.log("[Bridge] Testing first mapped interaction...");const e=this.interactionMappings.entries().next().value;if(e){const[t,n]=e;console.log(`[Bridge] Simulating interaction with ${t}`),this.onSceneInteraction(t)}else console.log("[Bridge] No mappings available to test")};var SceneLoader=pc.createScript("sceneLoader");SceneLoader.attributes.add("sceneSource",{type:"string",enum:[{url:"URL"},{asset:"Asset"},{text:"Text Input"}],default:"url",title:"Scene Source Type"}),SceneLoader.attributes.add("sceneUrl",{type:"string",default:"",title:"Scene URL",description:"URL to fetch dynamic scene from"}),SceneLoader.attributes.add("sceneAsset",{type:"asset",assetType:"text",title:"Scene Asset",description:"Text asset containing scene code"}),SceneLoader.attributes.add("autoLoad",{type:"boolean",default:!1,title:"Auto Load on Start"}),SceneLoader.prototype.initialize=function(){this.currentSceneRoot=null,this.preservedEntities=new Set,this.app.on("scene:load",this.loadScene,this),this.app.on("scene:unload",this.unloadCurrentScene,this),this.app.on("scene:reload",this.reloadScene,this),this.setupDebugUI(),this.autoLoad&&this.loadScene(),console.log("SceneLoader initialized. Commands:"),console.log("- Press L to load dynamic scene"),console.log("- Press U to unload dynamic scene"),console.log("- Press R to reload scene")},SceneLoader.prototype.setupDebugUI=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,(function(e){switch(e.key){case pc.KEY_L:console.log("[SceneLoader] Loading dynamic scene..."),this.loadScene();break;case pc.KEY_U:console.log("[SceneLoader] Unloading dynamic scene..."),this.unloadCurrentScene();break;case pc.KEY_R:console.log("[SceneLoader] Reloading scene..."),this.reloadScene()}}),this)},SceneLoader.prototype.loadScene=function(e){this.unloadCurrentScene();let t="";if(e&&"string"==typeof e)t=e;else switch(this.sceneSource){case"url":return void this.loadFromUrl(this.sceneUrl);case"asset":if(!this.sceneAsset||!this.sceneAsset.resource)return void console.error("[SceneLoader] Scene asset not found");t=this.sceneAsset.resource;break;case"text":t=this._textSceneCode||""}t&&this.executeSceneCode(t)},SceneLoader.prototype.loadFromUrl=function(e){e?fetch(e).then((e=>e.text())).then((e=>{console.log("[SceneLoader] Scene loaded from URL"),this.executeSceneCode(e)})).catch((e=>{console.error("[SceneLoader] Failed to load scene from URL:",e)})):console.error("[SceneLoader] No URL specified")},SceneLoader.prototype.executeSceneCode=function(e){console.log("[SceneLoader] Executing scene code..."),this.currentSceneRoot=new pc.Entity("DynamicSceneRoot"),this.app.root.addChild(this.currentSceneRoot);const t={pc:pc,app:this.app,sceneRoot:this.currentSceneRoot,_originalAddChild:this.app.root.addChild.bind(this.app.root)},n=`\n        (function() {\n            // Store original app.root.addChild\n            const originalAddChild = app.root.addChild.bind(app.root);\n            \n            // Override to add to scene root instead\n            app.root.addChild = function(entity) {\n                // Check if this is a preserved entity\n                if (entity.tags.has('preserve') || \n                    entity.name === 'SurgeonCamera' || \n                    entity.name === 'UIScreen') {\n                    originalAddChild(entity);\n                } else {\n                    sceneRoot.addChild(entity);\n                }\n            };\n            \n            // Execute the scene code\n            ${e}\n            \n            // Restore original function\n            app.root.addChild = originalAddChild;\n            \n            // Post-process the scene\n            app.fire('scene:loaded', sceneRoot);\n        })();\n    `;try{new Function(...Object.keys(t),n)(...Object.values(t)),console.log("[SceneLoader] Scene loaded successfully"),this.integrateScene()}catch(e){console.error("[SceneLoader] Failed to execute scene code:",e),this.currentSceneRoot&&(this.currentSceneRoot.destroy(),this.currentSceneRoot=null)}},SceneLoader.prototype.integrateScene=function(){if(!this.currentSceneRoot)return;console.log("[SceneLoader] Integrating dynamic scene...");this.currentSceneRoot.findComponents("script").forEach((e=>{const t=e.entity;t.tags.has("interactive")&&(t.script.has("interactionController")||console.log(`[SceneLoader] Adding interactionController to ${t.name}`)),t.tags.has("character")&&console.log(`[SceneLoader] Found character: ${t.name}`)})),this.resolveConflicts(),this.app.fire("scene:integrated",this.currentSceneRoot)},SceneLoader.prototype.resolveConflicts=function(){this.currentSceneRoot.findComponents("camera").forEach((e=>{console.log(`[SceneLoader] Disabling dynamic camera: ${e.entity.name}`),e.enabled=!1}));const e=this.currentSceneRoot.findComponents("light");e.length>0&&console.log(`[SceneLoader] Found ${e.length} dynamic lights`)},SceneLoader.prototype.unloadCurrentScene=function(){this.currentSceneRoot&&(console.log("[SceneLoader] Unloading current scene..."),this.currentSceneRoot.destroy(),this.currentSceneRoot=null,this.app.fire("scene:unloaded"))},SceneLoader.prototype.reloadScene=function(){console.log("[SceneLoader] Reloading scene..."),this.loadScene()},SceneLoader.prototype.setTextScene=function(e){this._textSceneCode=e},SceneLoader.prototype.getSceneRoot=function(){return this.currentSceneRoot},SceneLoader.prototype.findInScene=function(e){return this.currentSceneRoot?this.currentSceneRoot.findByName(e):null},SceneLoader.prototype.getSceneStats=function(){if(!this.currentSceneRoot)return{loaded:!1};const e={loaded:!0,entityCount:0,characters:[],interactives:[],scripts:[]},processEntity=t=>{e.entityCount++,t.tags.has("character")&&e.characters.push({name:t.name,tags:Array.from(t.tags._list)}),t.tags.has("interactive")&&e.interactives.push({name:t.name,tags:Array.from(t.tags._list)}),t.script&&t.script._scripts.forEach((n=>{e.scripts.push({entity:t.name,script:n.__scriptType.__name})})),t.children.forEach(processEntity)};return this.currentSceneRoot.children.forEach(processEntity),e};var ControlManager=pc.createScript("controlManager");ControlManager.attributes.add("showControlsOnStart",{type:"boolean",default:!0,title:"Show Controls on Start"}),ControlManager.prototype.initialize=function(){this.modes={GAMEPLAY:"gameplay",UI_INTERACTION:"ui_interaction",DEBUG:"debug"},this.currentMode=this.modes.GAMEPLAY,this.controlMappings={[this.modes.GAMEPLAY]:{W:"move_forward",S:"move_backward",A:"move_left",D:"move_right",Q:"rotate_left",E:"rotate_right",UP:"look_up",DOWN:"look_down",F:"interact",TAB:"toggle_ui",SPACE:"jump"},[this.modes.UI_INTERACTION]:{TAB:"toggle_ui",ESCAPE:"close_ui","1-9":"select_choice"},[this.modes.DEBUG]:{L:"load_scene",U:"unload_scene",R:"reload_scene",C:"show_catalog",I:"show_info",M:"show_mappings",H:"show_help"}},this.activeKeys=new Set,this.blockedKeys=new Set,this.setupInputListeners(),this.app.on("ui:toggled",this.onUIToggled,this),this.showControlsOnStart&&this.showCurrentControls(),console.log("[ControlManager] Initialized - Press F1 for help")},ControlManager.prototype.setupInputListeners=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.app.keyboard.on(pc.EVENT_KEYUP,this.onKeyUp,this)},ControlManager.prototype.onKeyDown=function(o){const e=this.getKeyName(o.key);if(o.key===pc.KEY_F1)return o.event.preventDefault(),void this.showFullHelp();if(this.blockedKeys.has(e))return;this.activeKeys.add(e);const t=this.getActionForKey(e);t&&(this.app.fire(`control:${this.currentMode}:${t}`,o),this.app.fire("control:action",{mode:this.currentMode,action:t,key:e}),["TAB","SPACE"].includes(e)&&o.event.preventDefault())},ControlManager.prototype.onKeyUp=function(o){const e=this.getKeyName(o.key);this.activeKeys.delete(e)},ControlManager.prototype.getKeyName=function(o){const e={[pc.KEY_W]:"W",[pc.KEY_A]:"A",[pc.KEY_S]:"S",[pc.KEY_D]:"D",[pc.KEY_Q]:"Q",[pc.KEY_E]:"E",[pc.KEY_F]:"F",[pc.KEY_R]:"R",[pc.KEY_L]:"L",[pc.KEY_U]:"U",[pc.KEY_C]:"C",[pc.KEY_I]:"I",[pc.KEY_M]:"M",[pc.KEY_H]:"H",[pc.KEY_TAB]:"TAB",[pc.KEY_SPACE]:"SPACE",[pc.KEY_ESCAPE]:"ESCAPE",[pc.KEY_UP]:"UP",[pc.KEY_DOWN]:"DOWN",[pc.KEY_LEFT]:"LEFT",[pc.KEY_RIGHT]:"RIGHT",[pc.KEY_F1]:"F1"};for(let o=1;o<=9;o++)e[pc.KEY_1+o-1]=o.toString();return e[o]||"UNKNOWN"},ControlManager.prototype.getActionForKey=function(o){const e=this.controlMappings[this.currentMode];return e[o]?e[o]:this.currentMode===this.modes.UI_INTERACTION&&/^[1-9]$/.test(o)?"select_choice_"+o:null},ControlManager.prototype.setMode=function(o){if(void 0===this.modes[o])return void console.error(`[ControlManager] Unknown mode: ${o}`);const e=this.currentMode;this.currentMode=this.modes[o],console.log(`[ControlManager] Mode changed: ${e} -> ${this.currentMode}`),this.activeKeys.clear(),this.app.fire("control:modeChanged",{previous:e,current:this.currentMode}),this.showCurrentControls()},ControlManager.prototype.onUIToggled=function(o){o?this.blockGameplayControls():this.unblockGameplayControls()},ControlManager.prototype.blockGameplayControls=function(){["W","A","S","D","Q","E","UP","DOWN","SPACE","F"].forEach((o=>this.blockedKeys.add(o))),console.log("[ControlManager] Gameplay controls blocked (UI active)")},ControlManager.prototype.unblockGameplayControls=function(){this.blockedKeys.clear(),console.log("[ControlManager] Gameplay controls unblocked")},ControlManager.prototype.showCurrentControls=function(){console.log(`\n=== CONTROLS (${this.currentMode.toUpperCase()}) ===`);const o=this.controlMappings[this.currentMode];Object.entries({movement:["W","S","A","D"],camera:["Q","E","UP","DOWN"],interaction:["F","TAB"],debug:["L","U","R","C","I","M","H"]}).forEach((([e,t])=>{const n=t.filter((e=>o[e]));n.length>0&&(console.log(`\n${e.toUpperCase()}:`),n.forEach((e=>{console.log(`  ${e} - ${o[e].replace(/_/g," ")}`)})))})),this.blockedKeys.size>0&&console.log("\nBLOCKED: "+Array.from(this.blockedKeys).join(", ")),console.log("\nPress F1 for full help"),console.log("===================\n")},ControlManager.prototype.showFullHelp=function(){console.log("\n=== COMPLETE CONTROL REFERENCE ==="),console.log("\nGAMEPLAY MODE:"),console.log("  Movement: WASD"),console.log("  Camera: Q/E (rotate), Arrow Keys (pitch)"),console.log("  Interact: F (with objects)"),console.log("  UI: TAB (toggle story panel)"),console.log("\nUI INTERACTION MODE:"),console.log("  TAB - Close UI and return to game"),console.log("  1-9 - Select story choices"),console.log("  ESC - Close UI"),console.log("\nDEBUG MODE (when implemented):"),console.log("  L - Load dynamic scene"),console.log("  U - Unload scene"),console.log("  R - Reload scene"),console.log("  C - Show scene catalog"),console.log("  I - Show current info"),console.log("  M - Show mappings"),console.log("\nCURRENT STATE:"),console.log(`  Mode: ${this.currentMode}`),console.log(`  Active Keys: ${Array.from(this.activeKeys).join(", ")||"none"}`),console.log(`  Blocked Keys: ${Array.from(this.blockedKeys).join(", ")||"none"}`),console.log("================================\n")},ControlManager.prototype.isKeyActive=function(o){return this.activeKeys.has(o)},ControlManager.prototype.isActionActive=function(o){for(const e of this.activeKeys)if(this.getActionForKey(e)===o)return!0;return!1},ControlManager.prototype.blockKey=function(o){this.blockedKeys.add(o)},ControlManager.prototype.unblockKey=function(o){this.blockedKeys.delete(o)},ControlManager.prototype.getCurrentMode=function(){return this.currentMode};var UiController=pc.createScript("uiController");UiController.attributes.add("descriptionElement",{type:"entity",title:"Description Text Entity"}),UiController.attributes.add("choicesContainer",{type:"entity",title:"Choices Container Entity"}),UiController.attributes.add("choiceButtonTemplate",{type:"asset",assetType:"template",title:"Choice Button Template"}),UiController.attributes.add("uiPanel",{type:"entity",title:"UI Panel Entity",description:"The main panel that contains all UI elements"}),UiController.prototype.initialize=function(){this.app.on("story:display",this.onDisplay,this),console.log("UiController: Initialized and listening for 'story:display' events."),this.isVisible=!0,this.setupToggleControls(),this.setupTextWrapping(),this.validateSetup(),console.log("=== UI CONTROLS ==="),console.log("Press TAB to toggle story UI"),console.log("Press H to show/hide this help"),console.log("=================="),this.app.fire("ui:ready"),console.log("UiController: Fired 'ui:ready' event.")},UiController.prototype.setupToggleControls=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,(function(e){switch(e.key){case pc.KEY_TAB:e.event.preventDefault(),this.toggleUI();break;case pc.KEY_H:this.showHelp()}}),this)},UiController.prototype.setupTextWrapping=function(){this.descriptionElement&&this.descriptionElement.element&&(this.descriptionElement.element.autoWidth=!1,this.descriptionElement.element.wrapLines=!0,this.descriptionElement.element.width=600,this.descriptionElement.element.fontSize||(this.descriptionElement.element.fontSize=16),this.descriptionElement.element.alignment=pc.Vec2.ZERO,this.descriptionElement.element.margin=new pc.Vec4(20,20,20,20),console.log("UiController: Text wrapping configured"))},UiController.prototype.toggleUI=function(){this.isVisible=!this.isVisible,this.uiPanel?this.uiPanel.enabled=this.isVisible:(this.descriptionElement&&(this.descriptionElement.enabled=this.isVisible),this.choicesContainer&&(this.choicesContainer.enabled=this.isVisible)),console.log("[UI] Story UI "+(this.isVisible?"shown":"hidden")),this.app.fire("ui:toggled",this.isVisible)},UiController.prototype.showHelp=function(){console.log("\n=== UI HELP ==="),console.log("TAB - Toggle story UI visibility"),console.log("H - Show this help"),console.log("F - Interact with objects (when UI is hidden)"),console.log("WASD - Move"),console.log("Q/E - Rotate camera"),console.log("===============\n")},UiController.prototype.validateSetup=function(){console.log("UiController: Validating setup..."),this.descriptionElement||console.error("UiController VALIDATION ERROR: 'Description Text Entity' is not assigned in the editor!"),this.choicesContainer||console.error("UiController VALIDATION ERROR: 'Choices Container Entity' is not assigned in the editor!"),this.choiceButtonTemplate?"template"!==this.choiceButtonTemplate.type&&console.error("UiController VALIDATION ERROR: The asset assigned to 'Choice Button Template' must be a Template asset."):console.error("UiController VALIDATION ERROR: 'Choice Button Template' asset is not assigned in the editor!"),this.uiPanel||console.warn("UiController: 'UI Panel Entity' not assigned. Toggle will affect individual elements.")},UiController.prototype.onDisplay=function(e){console.log("UiController: Received 'story:display' event."),e?(this.isVisible||this.toggleUI(),this.updateDescription(e.description),this.updateChoices(e.choices)):console.error("UiController: Received event but data was null or undefined.")},UiController.prototype.updateDescription=function(e){this.descriptionElement&&this.descriptionElement.element&&(this.descriptionElement.element.text=e||"Description text is missing.",this.descriptionElement.element._text.width=this.descriptionElement.element.width,this.descriptionElement.element._text.autoFitWidth=!1,this.descriptionElement.element._text.wrapLines=!0)},UiController.prototype.updateChoices=function(e){if(this.choicesContainer){for(;this.choicesContainer.children.length>0;)this.choicesContainer.children[0].destroy();e&&e.length>0&&e.forEach(((e,t)=>{this.createChoiceButton(e,t)}))}},UiController.prototype.createChoiceButton=function(e,t){if(this.choiceButtonTemplate&&this.choiceButtonTemplate.resource){var i=this.choiceButtonTemplate.resource.instantiate();this.choicesContainer.addChild(i);var o=i.element,n=t%2,s=Math.floor(t/2);o.width=280,o.height=50;var l=0===n?10:-290,r=-(60*s+20);0===n?(o.anchor=new pc.Vec4(0,1,0,1),o.pivot=new pc.Vec2(0,1)):(o.anchor=new pc.Vec4(1,1,1,1),o.pivot=new pc.Vec2(1,1)),i.setLocalPosition(l,r,0);var c=i.findByName("ButtonText");c&&c.element&&(c.element.text=e,c.element.wrapLines=!0,c.element.width=260,c.element.fontSize=14,c.element.alignment=new pc.Vec2(.5,.5)),i.button&&(i.button.on("click",(function(){console.log(`[UI] Choice selected: "${e}"`),this.app.fire("ui:choiceMade",e)}),this),i.button.on("mouseenter",(function(){i.setLocalScale(1.05,1.05,1)})),i.button.on("mouseleave",(function(){i.setLocalScale(1,1,1)})))}},UiController.prototype.show=function(){this.isVisible||this.toggleUI()},UiController.prototype.hide=function(){this.isVisible&&this.toggleUI()},UiController.prototype.isUIVisible=function(){return this.isVisible};var UiDebugFix=pc.createScript("uiDebugFix");UiDebugFix.prototype.initialize=function(){console.log("=== UI DEBUG STARTING ==="),setTimeout((()=>{this.debugAndFix()}),100),this.app.on("story:display",(()=>{setTimeout((()=>{this.debugAndFix()}),100)}))},UiDebugFix.prototype.debugAndFix=function(){console.log("\n=== CHECKING UI ELEMENTS ===");const e=this.app.root.findByName("DescriptionText");e&&e.element?(console.log("DescriptionText found!"),console.log("- Current width:",e.element.width),console.log("- Auto width:",e.element.autoWidth),console.log("- Wrap lines:",e.element.wrapLines),console.log("- Font size:",e.element.fontSize),console.log("- Text content:",e.element.text?.substring(0,50)+"..."),console.log("\nFIXING TEXT SETTINGS..."),e.element.autoWidth=!1,e.element.width=1400,e.element.wrapLines=!0,e.element.fontSize=20,e.element.lineHeight=30,e.element.anchor=e.element.anchor,e.element._calculateSize(),console.log("Text settings fixed!")):console.error("DescriptionText NOT FOUND!");const o=this.app.root.findByName("ChoicesContainer");if(o){console.log("\nChoicesContainer found!"),console.log("- Number of buttons:",o.children.length),console.log("- Container width:",o.element?.width||"No element component");const e=o.children;if(e.length>0){console.log("\nFIXING BUTTON POSITIONS...");const o=350,n=60,t=20,l=e.length,i=-(o*l+t*(l-1))/2+o/2;e.forEach(((e,l)=>{e.element&&(e.element.width=o,e.element.height=n,e.enabled=!0,console.log(`- Button ${l+1}: "${e.name}"`));const s=i+l*(o+t);e.setLocalPosition(s,0,0);const c=e.findByName("ButtonText");c&&c.element&&(c.element.width=o-30,c.element.wrapLines=!0,console.log(`  Text: "${c.element.text}"`))})),console.log("Button positions fixed!")}else console.log("No buttons found in container!")}else console.error("ChoicesContainer NOT FOUND!");const n=this.app.root.findByName("GameUIPanel");n&&(console.log("\nGameUIPanel found!"),n.element&&(console.log("- Width:",n.element.width),console.log("- Height:",n.element.height),console.log("- Type:",n.element.type))),console.log("\n=== DEBUG COMPLETE ===\n")},UiDebugFix.prototype.update=function(e){if(this.app.keyboard.wasPressed(pc.KEY_X)&&(console.log("Manual fix triggered!"),this.debugAndFix()),this.app.keyboard.wasPressed(pc.KEY_V)){const e=this.app.root.findByName("ChoicesContainer");e&&e.children.forEach(((e,o)=>{e.enabled=!0,console.log(`Button ${o} enabled:`,e.name)}))}};var SimpleSceneLoader=pc.createScript("simpleSceneLoader");SimpleSceneLoader.prototype.initialize=function(){console.log("=== SCENE LOADER READY ==="),console.log("Press 1 to load a test scene"),console.log("Press 2 to unload test scene"),console.log("========================"),this.testSceneRoot=null,this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this)},SimpleSceneLoader.prototype.onKeyDown=function(e){e.key===pc.KEY_1?this.loadTestScene():e.key===pc.KEY_2&&this.unloadTestScene()},SimpleSceneLoader.prototype.loadTestScene=function(){if(this.testSceneRoot)console.log("Test scene already loaded");else{console.log("Loading test scene..."),this.testSceneRoot=new pc.Entity("TestSceneRoot"),this.app.root.addChild(this.testSceneRoot);var e=new pc.Entity("TestCube");e.addComponent("render",{type:"box"}),e.setPosition(3,1,-3),e.setLocalScale(.5,2,.5);var t=new pc.StandardMaterial;t.diffuse.set(0,.5,1),t.emissive.set(0,.2,.5),t.update(),e.render.material=t,e.addComponent("script"),e.script.create("rotator",{attributes:{speed:30}}),this.testSceneRoot.addChild(e),console.log("Test scene loaded!")}},SimpleSceneLoader.prototype.unloadTestScene=function(){this.testSceneRoot&&(this.testSceneRoot.destroy(),this.testSceneRoot=null,console.log("Test scene unloaded"))};var Rotator=pc.createScript("rotator");Rotator.attributes.add("speed",{type:"number",default:30}),Rotator.prototype.update=function(e){this.entity.rotate(0,this.speed*e,0)};var HuggingFaceSceneLoader=pc.createScript("huggingFaceSceneLoader");HuggingFaceSceneLoader.prototype.initialize=function(){this.baseUrl="https://huggingface.co/datasets/KwabsHug/playcanvas-scenes-experiment/resolve/main/",this.currentSceneRoot=null,this.catalog=null,this.catalogLoaded=!1,this.missionControllers=[],this.firstDigit=null,this.selectionTimeout=null,console.log("=== HF SCENE LOADER READY ==="),console.log("Dataset: KwabsHug/playcanvas-scenes-experiment"),console.log("Press C to load scene catalog"),console.log("Press two digits to load scenes:"),console.log("  00 - Return to default scene"),console.log("  01-99 - Load scenes from catalog"),console.log("  C - Load catalog / V - Interactive overlay / G - 3D gallery"),console.log("============================="),this.catalogOverlay=null,this.catalogVisible=!1,this.galleryVisible=!1,this.galleryEntities=[],this.galleryMonitors=[],this.currentMonitor=0,this.selectedGalleryItem=null,this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.loadCatalog(),this.app.on("mission:loadScene",this.onMissionLoadScene,this)},HuggingFaceSceneLoader.prototype.onKeyDown=function(e){if(e.key!==pc.KEY_C)if(e.key!==pc.KEY_V)if(e.key!==pc.KEY_G){if(e.key>=pc.KEY_0&&e.key<=pc.KEY_9){const t=e.key-pc.KEY_0;if(null===this.firstDigit)this.firstDigit=t,console.log(`First digit: ${t} - Enter second digit...`),this.selectionTimeout&&clearTimeout(this.selectionTimeout),this.selectionTimeout=setTimeout((()=>{this.firstDigit=null,console.log("Selection timeout - cleared")}),2e3);else{clearTimeout(this.selectionTimeout);const e=10*this.firstDigit+t;this.firstDigit=null,0===e?this.loadDefaultScene():this.loadSceneByIndex(e-1)}}}else this.toggleGalleryMode();else this.toggleCatalogOverlay();else this.loadCatalog()},HuggingFaceSceneLoader.prototype.loadDefaultScene=function(){console.log("[HF Loader] Loading default scene..."),this.unloadCurrentScene(),this.app.clearRoom&&this.app.clearRoom();const e=this.app.root.findComponent("script",(e=>e.has("sceneScaffolder")));if(e&&e.entity.script.sceneScaffolder){const t=e.entity.script.sceneScaffolder;t.rebuildRoom||(t.rebuildRoom=function(){console.log("[Scaffolder] Rebuilding default room..."),this.createWall(this.app,"BackWall",0,2.5,-7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(this.app,"FrontWall",0,2.5,7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(this.app,"LeftWall",-10,2.5,0,.2,5,15,new pc.Color(.95,.97,1)),this.createWall(this.app,"RightWall",10,2.5,0,.2,5,15,new pc.Color(.95,.97,1));var e=new pc.Entity("SterileFloor");e.tags.add("room_entity");var t=new pc.StandardMaterial;t.diffuse=new pc.Color(.92,.95,.98),t.metalness=.1,t.gloss=.8,t.useMetalness=!0,t.update(),e.addComponent("render",{type:"plane",material:t,receiveShadows:!0,castShadows:!1}),e.setLocalScale(20,1,15),this.app.root.addChild(e),this.createOperatingTable(),this.createSurgicalLights(),this.createMedicalEquipment(),this.createVitalSignsMonitor(this.app,new pc.Vec3(-2,0,3)),console.log("[Scaffolder] Default room rebuilt")}.bind(t),t.createOperatingTable=function(){var e=new pc.Entity("OperatingTableBase");e.tags.add("room_entity");var t=new pc.StandardMaterial;t.diffuse=new pc.Color(.8,.8,.85),t.metalness=.7,t.gloss=.6,t.useMetalness=!0,t.update(),e.addComponent("render",{type:"cylinder",material:t,castShadows:!0,receiveShadows:!0}),e.setLocalScale(.8,.7,.8),e.setPosition(0,.35,0),this.app.root.addChild(e);var o=new pc.Entity("OperatingTableSurface");o.tags.add("room_entity");var n=new pc.StandardMaterial;n.diffuse=new pc.Color(.9,.92,.95),n.metalness=.2,n.gloss=.9,n.useMetalness=!0,n.update(),o.addComponent("render",{type:"box",material:n,castShadows:!0,receiveShadows:!0}),o.setLocalScale(2.2,.1,.8),o.setPosition(0,.75,0),o.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(1.1,.05,.4)}),o.addComponent("rigidbody",{type:"static"}),this.app.root.addChild(o);var a=new pc.Entity("PatientBody");a.tags.add("room_entity");var i=new pc.StandardMaterial;i.diffuse=new pc.Color(.95,.85,.75),i.metalness=.1,i.gloss=.2,i.useMetalness=!0,i.update(),a.addComponent("render",{type:"box",material:i,castShadows:!0,receiveShadows:!0}),a.addComponent("collision",{type:"box"}),a.addComponent("rigidbody",{type:"static"}),a.setLocalScale(.6,.3,1.8),a.setPosition(0,.95,0),this.app.root.addChild(a);var s=new pc.Entity("SurgicalDrape");s.tags.add("room_entity");var l=new pc.StandardMaterial;l.diffuse=new pc.Color(.8,.9,.95),l.metalness=0,l.gloss=.1,l.update(),s.addComponent("render",{type:"box",material:l,castShadows:!0,receiveShadows:!0}),s.setLocalScale(.8,.05,2),s.setPosition(0,1.15,0),this.app.root.addChild(s)}.bind(t),t.createSurgicalLights=function(){var e=new pc.Entity("MainSurgicalLight");e.tags.add("room_entity"),e.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:3,range:15,innerConeAngle:15,outerConeAngle:35,castShadows:!0,shadowBias:.1,shadowDistance:20,shadowResolution:2048}),e.addComponent("render",{type:"box"}),e.setLocalScale(.5,.2,.5),e.addComponent("collision",{type:"box"}),e.addComponent("rigidbody",{type:"static"}),e.setPosition(0,4,0),e.setEulerAngles(90,0,0),this.app.root.addChild(e);var t=new pc.Entity("SecondarySurgicalLight");t.tags.add("room_entity"),t.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:2.5,range:12,innerConeAngle:20,outerConeAngle:40,castShadows:!0,shadowBias:.1}),t.setPosition(-1.5,3.8,-.5),t.setEulerAngles(75,15,0),this.app.root.addChild(t);var o=new pc.Entity("AmbientRoomLight");o.tags.add("room_entity"),o.addComponent("light",{type:"directional",color:new pc.Color(.9,.95,1),intensity:.4,castShadows:!1}),o.setEulerAngles(30,45,0),this.app.root.addChild(o);var n=new pc.Entity("SurgicalLightArm1");n.tags.add("room_entity");var a=new pc.StandardMaterial;a.diffuse=new pc.Color(.9,.9,.92),a.metalness=.8,a.useMetalness=!0,a.update(),n.addComponent("render",{type:"cylinder",material:a,castShadows:!0,receiveShadows:!0}),n.setLocalScale(.15,2,.15),n.setPosition(0,3,0),this.app.root.addChild(n)}.bind(t),t.createMedicalEquipment=function(){var e=new pc.Entity("AnesthesiaMachine");e.tags.add("room_entity");var t=new pc.StandardMaterial;t.diffuse=new pc.Color(.7,.75,.8),t.metalness=.8,t.useMetalness=!0,t.update(),e.addComponent("render",{type:"box",material:t,castShadows:!0,receiveShadows:!0}),e.setLocalScale(1.2,1.8,.8),e.setPosition(-4,.9,2),this.app.root.addChild(e);var o=new pc.Entity("InstrumentTable");o.tags.add("room_entity");var n=new pc.StandardMaterial;n.diffuse=new pc.Color(.85,.87,.9),n.metalness=.6,n.gloss=.8,n.useMetalness=!0,n.update(),o.addComponent("render",{type:"box",material:n,castShadows:!0,receiveShadows:!0}),o.setLocalScale(1.5,1.2,.8),o.setPosition(3,.6,-1),this.app.root.addChild(o);var a=new pc.Entity("XRayViewer");a.tags.add("room_entity");var i=new pc.StandardMaterial;i.diffuse=new pc.Color(.1,.1,.12),i.metalness=.9,i.useMetalness=!0,i.update(),a.addComponent("render",{type:"box",material:i,castShadows:!0,receiveShadows:!0}),a.setLocalScale(1.8,1.2,.1),a.setPosition(-4,2.5,-6),this.app.root.addChild(a);var s=new pc.Entity("XRayScreen");s.tags.add("room_entity");var l=new pc.StandardMaterial;l.diffuse=new pc.Color(.9,.95,1),l.emissive=new pc.Color(.3,.35,.4),l.update(),s.addComponent("render",{type:"box",material:l,castShadows:!1,receiveShadows:!1}),s.addComponent("collision",{type:"box"}),s.addComponent("rigidbody",{type:"static"}),s.setLocalScale(1.6,1,.05),s.setPosition(-4,2.5,-5.9),this.app.root.addChild(s)}.bind(t)),t.rebuildRoom()}else console.log("[HF Loader] No scaffolder found - creating basic room manually"),this.createBasicRoom();setTimeout((()=>{const e=this.app.root.findByName("GameManager");e&&e.script&&e.script.objectiveManager&&(console.log("[HF Loader] Resetting objectives to tutorial..."),e.script.objectiveManager.activateObjective("tutorial_start"))}),1e3),this.app.fire("dataset:sceneUnloaded"),this.app.fire("scene:default"),console.log("[HF Loader] Default scene loaded")},HuggingFaceSceneLoader.prototype.onMissionLoadScene=function(e){if(console.log("[HF Loader] Mission requesting scene:",e),"default"===e)this.loadDefaultScene();else{const t={medical_lab:2,scifi_env:1};void 0!==t[e]?this.loadSceneByIndex(t[e]):console.error("[HF Loader] Unknown scene ID:",e)}},HuggingFaceSceneLoader.prototype.loadCatalog=async function(){const e=this.baseUrl+"scene_catalog.json";console.log("Loading scene catalog...");try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);this.catalog=await t.json(),this.catalogLoaded=!0,console.log("\n=== AVAILABLE SCENES ==="),this.catalog.scenes.forEach(((e,t)=>{const o=(t+1).toString().padStart(2,"0");console.log(`[${o}] ${e.name}`),console.log(`     ${e.description}`),e.tags&&console.log(`     Tags: ${e.tags.join(", ")}`)})),console.log("\nPress two digits to load a scene:"),console.log("  00 - Return to default scene"),console.log("  01-"+this.catalog.scenes.length.toString().padStart(2,"0")+" - Load scenes"),console.log("======================\n")}catch(e){console.error("Failed to load catalog:",e),console.log("Using fallback scene list..."),this.catalog={scenes:[{name:"Test Crystal",file:"scenes/test_scene.js",description:"Simple floating crystal",position:"center"},{name:"Sci-Fi Environment",file:"scenes/scifi_scene.js",description:"Futuristic scene with holograms",position:"center"},{name:"Medical Lab",file:"scenes/medical_lab_scene.js",description:"Additional medical equipment",position:"adjacent"}]},this.catalogLoaded=!0}},HuggingFaceSceneLoader.prototype.loadSceneByIndex=function(e){if(!this.catalogLoaded||!this.catalog)return void console.log("Catalog not loaded yet. Press C to load catalog.");if(e>=this.catalog.scenes.length){const t=(e+1).toString().padStart(2,"0");return void console.log(`No scene at index ${t}. Available scenes: 01-${this.catalog.scenes.length.toString().padStart(2,"0")}`)}const t=this.catalog.scenes[e];this.lastLoadedIndex=e;const o=(e+1).toString().padStart(2,"0");console.log(`[${o}] Loading scene: ${t.name}`),this.loadScene(t.file,t)},HuggingFaceSceneLoader.prototype.loadScene=async function(e,t){this.unloadCurrentScene();const o=this.baseUrl+e;console.log(`Loading scene from: ${o}`);try{const e=await fetch(o);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const n=await e.text();console.log(`Loaded ${n.length} bytes of scene code`);t&&"mission_controller"===t.position?(console.log("[HF Loader] Loading mission controller scene..."),this.executeMissionCode(n,t)):(console.log("[HF Loader] Loading regular scene..."),this.executeRegularSceneCode(n,t))}catch(e){console.error("Failed to load scene:",e)}},HuggingFaceSceneLoader.prototype.executeRegularSceneCode=function(e,t){this.currentSceneRoot=new pc.Entity("DynamicSceneRoot"),this.app.root.addChild(this.currentSceneRoot);const o=["(function() {","    const originalAddChild = app.root.addChild.bind(app.root);","    ","    app.root.addChild = function(entity) {",'        if (entity.camera || entity.screen || entity.name === "SurgeonCamera") {',"            originalAddChild(entity);","        } else {","            sceneRoot.addChild(entity);","        }","    };","    ","    try {","        "+e,"    } catch (error) {",'        console.error("Scene execution error:", error);',"        throw error;","    }","    ","    app.root.addChild = originalAddChild;","})();"].join("\n");try{new Function("app","pc","sceneRoot",o)(this.app,pc,this.currentSceneRoot),console.log("Scene loaded successfully!"),this.postProcessScene(),console.log("[HF Loader] Firing dataset:sceneLoaded"),this.app.fire("dataset:sceneLoaded",t,this.currentSceneRoot)}catch(e){console.error("Failed to execute scene:",e),this.currentSceneRoot&&(this.currentSceneRoot.destroy(),this.currentSceneRoot=null)}},HuggingFaceSceneLoader.prototype.executeMissionCode=function(e,t){console.log("[HF Loader] Executing mission code directly...");try{new Function("app","pc",e)(this.app,pc);this.app.root.findComponents("script").filter((e=>e._scripts.some((e=>{const t=e.__scriptType.__name;return t.includes("Mission")||t.includes("mission")})))).forEach((e=>{this.missionControllers.includes(e.entity)||(this.missionControllers.push(e.entity),console.log("[HF Loader] Tracked mission controller:",e.entity.name))})),console.log("Mission loaded successfully!"),this.app.fire("dataset:sceneLoaded",t,null)}catch(e){console.error("Failed to execute mission:",e)}},HuggingFaceSceneLoader.prototype.postProcessScene=function(){if(!this.currentSceneRoot)return;this.currentSceneRoot.findComponents("camera").forEach((e=>{console.log(`Disabling camera: ${e.entity.name}`),e.enabled=!1}));const e=this.currentSceneRoot.findComponents("light");console.log(`Scene contains ${e.length} lights`)},HuggingFaceSceneLoader.prototype.unloadCurrentScene=function(){if(console.log("[HF Loader] Unloading current scene..."),this.currentSceneRoot){const e=this.currentSceneRoot.name;this.currentSceneRoot.destroy(),this.currentSceneRoot=null,console.log(`[HF Loader] Unloaded scene root: ${e}`)}this.missionControllers.forEach((e=>{if(e&&!e._destroyed){const t=e.script._scripts.find((e=>e.cleanup&&"function"==typeof e.cleanup));t&&(console.log("[HF Loader] Calling mission cleanup..."),t.cleanup()),e.destroy()}})),this.missionControllers=[];this.app.root.findByTag("mission_entity").forEach((e=>{e._destroyed||e.destroy()}));["RecordingStudioMission","ResearchFacilityMission","MissionController","StudioFloor","MixingConsole","StudioMonitorL","StudioMonitorR","MicrophoneStand","GuitarStand","Synthesizer","IsolationBooth","TapeMachine","StudioMainLight","MoodLight","StudioWindow"].forEach((e=>{const t=this.app.root.findByName(e);t&&!t._destroyed&&(t.destroy(),console.log(`[HF Loader] Cleaned up mission entity: ${e}`))}));const e=this.app.root.findByName("GameManager");if(e&&e.script&&e.script.objectiveManager){console.log("[HF Loader] Clearing objectives...");const t=e.script.objectiveManager;"function"==typeof t.clearAllObjectives?t.clearAllObjectives():(console.log("[HF Loader] Using fallback objective clearing..."),void 0!==t.currentObjective&&(t.currentObjective=null),void 0!==t.activeObjectives&&(t.activeObjectives=[]),t.completedObjectives&&t.completedObjectives.clear&&t.completedObjectives.clear(),void 0!==t.currentAct&&(t.currentAct=0),void 0!==t.totalActs&&(t.totalActs=0),void 0!==t.actNames&&(t.actNames=[]),"function"==typeof t.updateHUD&&t.updateHUD())}else console.log("[HF Loader] No objective manager found - skipping objective cleanup");this.app.root.findByTag("item").forEach((e=>{e._destroyed||(console.log(`[HF Loader] Cleaning up item: ${e.name}`),e.destroy())}));this.app.root.findByTag("interactive").forEach((e=>{!e._destroyed&&e.tags.has("mission_entity")&&(console.log(`[HF Loader] Cleaning up interactive entity: ${e.name}`),e.destroy())})),this.galleryVisible&&this.hideGalleryMode(),this.catalogVisible&&this.hideCatalogOverlay(),this.app.fire("dataset:sceneUnloaded"),console.log("[HF Loader] Scene unload complete")},HuggingFaceSceneLoader.prototype.createBasicRoom=function(){var e=new pc.Entity("BasicFloor");e.tags.add("room_entity");var t=new pc.StandardMaterial;t.diffuse.set(.8,.8,.8),t.update(),e.addComponent("render",{type:"plane",material:t}),e.setLocalScale(20,1,20),e.setPosition(0,0,0),this.app.root.addChild(e);var o=new pc.Entity("BasicLight");o.tags.add("room_entity"),o.addComponent("light",{type:"directional",color:new pc.Color(1,1,1),intensity:.8}),o.setEulerAngles(45,0,0),this.app.root.addChild(o),console.log("[HF Loader] Basic room created")},HuggingFaceSceneLoader.prototype.toggleCatalogOverlay=function(){this.catalogVisible?this.hideCatalogOverlay():this.showCatalogOverlay()},HuggingFaceSceneLoader.prototype.toggleGalleryMode=function(){this.galleryVisible?this.hideGalleryMode():this.showGalleryMode()},HuggingFaceSceneLoader.prototype.showCatalogOverlay=async function(){this.catalogVisible||(console.log("[HF Loader] Showing visual catalog overlay..."),this.catalogLoaded&&this.catalog||(console.log("[HF Loader] Catalog not loaded, loading now..."),await this.loadCatalog()),this.catalog?(this.catalogVisible=!0,this.createCatalogOverlay()):console.error("[HF Loader] Failed to load catalog for overlay"))},HuggingFaceSceneLoader.prototype.hideCatalogOverlay=function(){this.catalogVisible&&(console.log("[HF Loader] Hiding visual catalog overlay..."),this.catalogOverlay&&(this.catalogOverlay.destroy(),this.catalogOverlay=null),this.catalogVisible=!1,this.cleanupOverlayControls())},HuggingFaceSceneLoader.prototype.createCatalogOverlay=function(){this.catalogOverlay=new pc.Entity("CatalogOverlay"),this.catalogOverlay.addComponent("screen",{referenceResolution:new pc.Vec2(1920,1080),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),this.app.root.addChild(this.catalogOverlay);var e=new pc.Entity("CatalogBackground");e.addComponent("element",{type:"image",anchor:new pc.Vec4(0,0,1,1),pivot:new pc.Vec2(.5,.5),color:new pc.Color(0,0,0),opacity:.85}),this.catalogOverlay.addChild(e);const t=this.app.root.findByName("DescriptionText")||this.app.root.findByName("InstructionText")||this.app.root.findByName("UIText");var o=new pc.Entity("CatalogTitle");o.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.95,.5,.95),pivot:new pc.Vec2(.5,1),fontSize:48,text:"SCENE CATALOG",color:new pc.Color(1,1,.2),alignment:new pc.Vec2(.5,.5)}),t&&t.element&&(t.element.font&&(o.element.font=t.element.font),t.element.fontAsset&&(o.element.fontAsset=t.element.fontAsset)),this.catalogOverlay.addChild(o);var n=new pc.Entity("CatalogInstructions");n.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.88,.5,.88),pivot:new pc.Vec2(.5,1),fontSize:24,text:"Click scene to load • Arrow keys/WASD navigate • Enter/Space select • 1-9 direct load • V/Esc close",color:new pc.Color(.8,.8,1),alignment:new pc.Vec2(.5,.5)}),t&&t.element&&(t.element.font&&(n.element.font=t.element.font),t.element.fontAsset&&(n.element.fontAsset=t.element.fontAsset)),this.catalogOverlay.addChild(n),this.createCatalogGrid(e),this.createCloseButton(),this.setupOverlayControls(),setTimeout((()=>{this.updateOverlaySelection()}),100)},HuggingFaceSceneLoader.prototype.createCatalogGrid=function(e){var t=new pc.Entity("GridContainer");t.addComponent("element",{type:"group",anchor:new pc.Vec4(.05,.1,.95,.8),pivot:new pc.Vec2(0,1)}),e.addChild(t);this.catalog.scenes.forEach(((e,o)=>{const n=320*(o%5),a=200*-Math.floor(o/5);this.createCatalogItem(e,o,t,n,a,300,180)}))},HuggingFaceSceneLoader.prototype.createCatalogItem=function(e,t,o,n,a,i,s){const l=this.app.root.findByName("DescriptionText")||this.app.root.findByName("InstructionText")||this.app.root.findByName("UIText");var c=new pc.Entity(`CatalogItem_${t}`);c.tags.add("catalog_item"),c.addComponent("element",{type:"image",anchor:new pc.Vec4(0,1,0,1),pivot:new pc.Vec2(0,1),width:i,height:s,color:new pc.Color(.2,.2,.3),opacity:.9}),c.setLocalPosition(n,a,0),o.addChild(c),c.addComponent("button",{imageEntity:c});var r=new pc.Entity(`ItemNumber_${t}`);r.addComponent("element",{type:"text",anchor:new pc.Vec4(.05,.85,.25,1),pivot:new pc.Vec2(0,1),fontSize:32,text:(t+1).toString().padStart(2,"0"),color:new pc.Color(1,1,.2),alignment:new pc.Vec2(0,.5)}),l&&l.element&&(l.element.font&&(r.element.font=l.element.font),l.element.fontAsset&&(r.element.fontAsset=l.element.fontAsset)),c.addChild(r);var d=new pc.Entity(`ItemName_${t}`);d.addComponent("element",{type:"text",anchor:new pc.Vec4(.05,.6,.95,.85),pivot:new pc.Vec2(0,1),fontSize:24,text:e.name,color:new pc.Color(.9,.9,1),wrapLines:!0,alignment:new pc.Vec2(0,1)}),l&&l.element&&(l.element.font&&(d.element.font=l.element.font),l.element.fontAsset&&(d.element.fontAsset=l.element.fontAsset)),c.addChild(d);var p=new pc.Entity(`ItemDesc_${t}`);if(p.addComponent("element",{type:"text",anchor:new pc.Vec4(.05,.3,.95,.6),pivot:new pc.Vec2(0,1),fontSize:16,text:e.description,color:new pc.Color(.7,.7,.8),wrapLines:!0,alignment:new pc.Vec2(0,1)}),l&&l.element&&(l.element.font&&(p.element.font=l.element.font),l.element.fontAsset&&(p.element.fontAsset=l.element.fontAsset)),c.addChild(p),e.tags&&e.tags.length>0){var g=new pc.Entity(`ItemTags_${t}`);g.addComponent("element",{type:"text",anchor:new pc.Vec4(.05,.05,.95,.3),pivot:new pc.Vec2(0,0),fontSize:14,text:e.tags.join(", "),color:new pc.Color(.5,.8,.5),wrapLines:!0,alignment:new pc.Vec2(0,0)}),l&&l.element&&(l.element.font&&(g.element.font=l.element.font),l.element.fontAsset&&(g.element.fontAsset=l.element.fontAsset)),c.addChild(g)}c.button.on("click",(()=>{console.log(`[Catalog Overlay] CLICK DETECTED! Loading scene ${t}: ${e.name}`),this.hideCatalogOverlay(),this.loadSceneByIndex(t)})),c.button.on("mousedown",(()=>{console.log(`[Catalog Overlay] Mouse down on scene ${t}`)})),c.button.on("mouseup",(()=>{console.log(`[Catalog Overlay] Mouse up on scene ${t}`)})),c.button.on("hoverstart",(()=>{c.element.color=new pc.Color(.3,.3,.5)})),c.button.on("hoverend",(()=>{c.element.color=new pc.Color(.2,.2,.3)}))},HuggingFaceSceneLoader.prototype.createCloseButton=function(){const e=this.app.root.findByName("DescriptionText")||this.app.root.findByName("InstructionText")||this.app.root.findByName("UIText");var t=new pc.Entity("CloseButton");t.addComponent("element",{type:"image",anchor:new pc.Vec4(.95,.95,.95,.95),pivot:new pc.Vec2(1,1),width:60,height:60,color:new pc.Color(.8,.2,.2),opacity:.8}),this.catalogOverlay.addChild(t),t.addComponent("button",{imageEntity:t});var o=new pc.Entity("CloseText");o.addComponent("element",{type:"text",anchor:new pc.Vec4(0,0,1,1),pivot:new pc.Vec2(.5,.5),fontSize:32,text:"×",color:new pc.Color(1,1,1),alignment:new pc.Vec2(.5,.5)}),e&&e.element&&(e.element.font&&(o.element.font=e.element.font),e.element.fontAsset&&(o.element.fontAsset=e.element.fontAsset)),t.addChild(o),t.button.on("click",(()=>{this.hideCatalogOverlay()}))},HuggingFaceSceneLoader.prototype.setupOverlayControls=function(){this.selectedItemIndex=0,this.totalItems=this.catalog.scenes.length,this.overlayKeyHandler=e=>{if(e.key!==pc.KEY_ESCAPE&&e.key!==pc.KEY_V)if(e.key!==pc.KEY_LEFT&&e.key!==pc.KEY_A)if(e.key!==pc.KEY_RIGHT&&e.key!==pc.KEY_D)if(e.key!==pc.KEY_UP&&e.key!==pc.KEY_W)if(e.key!==pc.KEY_DOWN&&e.key!==pc.KEY_S)if(e.key!==pc.KEY_ENTER&&e.key!==pc.KEY_SPACE){if(e.key>=pc.KEY_1&&e.key<=pc.KEY_9){const t=e.key-pc.KEY_0;t<=this.totalItems&&this.selectItemByIndex(t-1)}}else this.selectCurrentItem();else this.navigateOverlay(5);else this.navigateOverlay(-5);else this.navigateOverlay(1);else this.navigateOverlay(-1);else this.hideCatalogOverlay()},this.app.keyboard.on(pc.EVENT_KEYDOWN,this.overlayKeyHandler,this)},HuggingFaceSceneLoader.prototype.navigateOverlay=function(e){this.selectedItemIndex=Math.max(0,Math.min(this.totalItems-1,this.selectedItemIndex+e)),console.log(`[Catalog Overlay] Navigated to item ${this.selectedItemIndex}: ${this.catalog.scenes[this.selectedItemIndex].name}`),this.updateOverlaySelection()},HuggingFaceSceneLoader.prototype.selectCurrentItem=function(){console.log(`[Catalog Overlay] KEYBOARD SELECT! Loading scene ${this.selectedItemIndex}: ${this.catalog.scenes[this.selectedItemIndex].name}`),this.hideCatalogOverlay(),this.loadSceneByIndex(this.selectedItemIndex)},HuggingFaceSceneLoader.prototype.selectItemByIndex=function(e){console.log(`[Catalog Overlay] DIRECT SELECT! Loading scene ${e}: ${this.catalog.scenes[e].name}`),this.hideCatalogOverlay(),this.loadSceneByIndex(e)},HuggingFaceSceneLoader.prototype.updateOverlaySelection=function(){this.app.root.findByTag("catalog_item").forEach(((e,t)=>{t===this.selectedItemIndex?(e.element.color=new pc.Color(.5,.6,.8),e.element.opacity=1,console.log(`[Catalog Overlay] Highlighted item ${t}: ${this.catalog.scenes[t].name}`)):(e.element.color=new pc.Color(.2,.2,.3),e.element.opacity=.9)}))},HuggingFaceSceneLoader.prototype.cleanupOverlayControls=function(){this.overlayKeyHandler&&(this.app.keyboard.off(pc.EVENT_KEYDOWN,this.overlayKeyHandler,this),this.overlayKeyHandler=null),this.selectedItemIndex=0,this.totalItems=0},HuggingFaceSceneLoader.prototype.showGalleryMode=async function(){this.galleryVisible||(console.log("[HF Loader] Showing 3D catalog gallery..."),this.catalogLoaded&&this.catalog||(console.log("[HF Loader] Catalog not loaded, loading now..."),await this.loadCatalog()),this.catalog?(this.catalogVisible&&this.hideCatalogOverlay(),this.galleryVisible=!0,this.createGalleryEnvironment(),this.setupGalleryControls()):console.error("[HF Loader] Failed to load catalog for gallery"))},HuggingFaceSceneLoader.prototype.hideGalleryMode=function(){this.galleryVisible&&(console.log("[HF Loader] Hiding 3D catalog gallery..."),this.galleryEntities.forEach((e=>{e&&!e._destroyed&&e.destroy()})),this.galleryEntities=[],this.galleryMonitors=[],this.selectedGalleryItem=null,this.galleryVisible=!1,this.cleanupGalleryControls())},HuggingFaceSceneLoader.prototype.createGalleryEnvironment=function(){console.log("[HF Loader] Creating gallery environment..."),this.createGalleryRoom();const e=Math.ceil(this.catalog.scenes.length/25);console.log(`[HF Loader] Creating ${e} monitors for ${this.catalog.scenes.length} scenes`),this.createGalleryMonitors(e),this.createGalleryLighting(),console.log("[HF Loader] Gallery environment created")},HuggingFaceSceneLoader.prototype.createGalleryRoom=function(){var e=new pc.Entity("GalleryFloor"),t=new pc.StandardMaterial;t.diffuse.set(.2,.2,.25),t.metalness=.8,t.gloss=.9,t.useMetalness=!0,t.update(),e.addComponent("render",{type:"plane",material:t}),e.setLocalScale(30,1,30),e.setPosition(0,0,0),this.app.root.addChild(e),this.galleryEntities.push(e);var o=new pc.Entity("GalleryCeiling"),n=new pc.StandardMaterial;n.diffuse.set(.15,.15,.2),n.update(),o.addComponent("render",{type:"plane",material:n}),o.setLocalScale(30,1,30),o.setPosition(0,8,0),o.setEulerAngles(180,0,0),this.app.root.addChild(o),this.galleryEntities.push(o),this.createGalleryWall("NorthWall",0,4,-15,30,8,.5),this.createGalleryWall("SouthWall",0,4,15,30,8,.5),this.createGalleryWall("EastWall",15,4,0,.5,8,30),this.createGalleryWall("WestWall",-15,4,0,.5,8,30)},HuggingFaceSceneLoader.prototype.createGalleryWall=function(e,t,o,n,a,i,s){var l=new pc.Entity(e),c=new pc.StandardMaterial;c.diffuse.set(.25,.25,.3),c.update(),l.addComponent("render",{type:"box",material:c}),l.setPosition(t,o,n),l.setLocalScale(a,i,s),this.app.root.addChild(l),this.galleryEntities.push(l)},HuggingFaceSceneLoader.prototype.createGalleryMonitors=function(e){console.log(`[HF Loader] Starting to create ${e} monitors`);const t=[{pos:[0,4,-14.5],rot:[0,0,0]},{pos:[14.5,4,0],rot:[0,-90,0]},{pos:[0,4,14.5],rot:[0,180,0]},{pos:[-14.5,4,0],rot:[0,90,0]}];this.galleryMonitors=[];for(let o=0;o<e;o++){const e=o%t.length,n=8*Math.floor(o/t.length),a=t[e];let i=[...a.pos];0===e||2===e?i[0]+=n-4:i[2]+=n-4,this.createGalleryMonitor(o,i,a.rot)}console.log(`[HF Loader] Created ${this.galleryMonitors.length} monitors`)},HuggingFaceSceneLoader.prototype.createGalleryMonitor=function(e,t,o){console.log(`[HF Loader] Creating monitor ${e} at position`,t);var n=new pc.Entity(`Monitor_${e}`),a=new pc.StandardMaterial;a.diffuse.set(.1,.1,.15),a.metalness=.9,a.useMetalness=!0,a.update(),n.addComponent("render",{type:"box",material:a}),n.setLocalScale(6,4,.3),n.setPosition(t[0],t[1],t[2]),n.setEulerAngles(o[0],o[1],o[2]),this.app.root.addChild(n),this.galleryEntities.push(n);var i=new pc.Entity(`Screen_${e}`),s=new pc.StandardMaterial;s.diffuse.set(.05,.05,.1),s.emissive.set(.1,.1,.15),s.update(),i.addComponent("render",{type:"box",material:s}),i.setLocalScale(5,3,.1),i.setLocalPosition(0,0,.1),n.addChild(i),this.galleryEntities.push(i),console.log(`[Gallery] Screen ${e} world position:`,i.getPosition()),this.createGalleryMonitorGrid(e,i),this.galleryMonitors.push({monitor:n,screen:i,items:[]})},HuggingFaceSceneLoader.prototype.createGalleryMonitorGrid=function(e,t){const o=25*e,n=Math.min(o+25,this.catalog.scenes.length),a=.05,i=.04;console.log("[Gallery] Grid dimensions: 0.27 x 0.22, Screen scale: 5x3");for(let s=o;s<n;s++){const n=this.catalog.scenes[s],l=s-o,c=.055*(l%5)-.135+.025,r=.11-.045*Math.floor(l/5)-.02;console.log(`[Gallery] Creating scene item ${s} at local position (${c}, ${r}) on screen ${e}`),this.createGallerySceneItem(s,n,t,c,r,a,i)}},HuggingFaceSceneLoader.prototype.createGallerySceneItem=function(e,t,o,n,a,i,s){const l=this.app.root.findByName("DescriptionText")||this.app.root.findByName("InstructionText")||this.app.root.findByName("UIText");var c=new pc.Entity(`SceneItem_${e}`),r=new pc.StandardMaterial;r.diffuse.set(.3,.3,.4),r.emissive.set(.1,.1,.2),r.update(),c.addComponent("render",{type:"box",material:r}),c.setLocalScale(i,s,.1),c.setLocalPosition(n,a,.5),c.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(i/2,s/2,.05)}),c.addComponent("rigidbody",{type:"static"}),c.sceneData=t,c.sceneIndex=e,o.addChild(c),this.galleryEntities.push(c),this.createGalleryItemText(c,e,t,i,s,l);const d=Math.floor(e/25);this.galleryMonitors[d]&&this.galleryMonitors[d].items.push(c)},HuggingFaceSceneLoader.prototype.createGalleryLighting=function(){var e=new pc.Entity("GalleryAmbient");e.addComponent("light",{type:"directional",color:new pc.Color(.4,.4,.5),intensity:.3}),e.setEulerAngles(45,0,0),this.app.root.addChild(e),this.galleryEntities.push(e)},HuggingFaceSceneLoader.prototype.createGalleryItemText=function(e,t,o,n,a,i){var s=new pc.Entity(`SceneNumber_${t}`),l=new pc.StandardMaterial;l.diffuse.set(1,1,.2),l.emissive.set(.3,.3,.1),l.update(),s.addComponent("render",{type:"plane",material:l}),s.setLocalScale(.3,.2,1),s.setLocalPosition(0,.25*a,.05),e.addChild(s),this.galleryEntities.push(s);var c=new pc.Entity(`SceneIndicator_${t}`),r=new pc.StandardMaterial;o.tags&&o.tags.includes("mission")?r.diffuse.set(.2,.8,.2):o.tags&&o.tags.includes("test")?r.diffuse.set(.8,.2,.2):r.diffuse.set(.2,.2,.8),r.emissive.set(.1,.1,.1),r.update(),c.addComponent("render",{type:"box",material:r}),c.setLocalScale(.8*n,.1,.05),c.setLocalPosition(0,.3*-a,.05),e.addChild(c),this.galleryEntities.push(c)},HuggingFaceSceneLoader.prototype.setupGalleryControls=function(){this.galleryMouseHandler=this.onGalleryMouseClick.bind(this),this.app.mouse.on(pc.EVENT_MOUSEDOWN,this.galleryMouseHandler,this),this.galleryKeyHandler=e=>{e.key!==pc.KEY_ESCAPE&&e.key!==pc.KEY_G||this.hideGalleryMode(),e.key===pc.KEY_ENTER&&this.selectedGalleryItem&&this.loadSceneByIndex(this.selectedGalleryItem.sceneIndex)},this.app.keyboard.on(pc.EVENT_KEYDOWN,this.galleryKeyHandler,this)},HuggingFaceSceneLoader.prototype.cleanupGalleryControls=function(){this.galleryMouseHandler&&(this.app.mouse.off(pc.EVENT_MOUSEDOWN,this.galleryMouseHandler,this),this.galleryMouseHandler=null),this.galleryKeyHandler&&(this.app.keyboard.off(pc.EVENT_KEYDOWN,this.galleryKeyHandler,this),this.galleryKeyHandler=null)},HuggingFaceSceneLoader.prototype.onGalleryMouseClick=function(e){if(e.button===pc.MOUSEBUTTON_LEFT){var t=this.app.root.findComponent("camera");if(!t)return;var o=t.entity.getPosition(),n=t.screenToWorld(e.x,e.y,10),a=this.app.systems.rigidbody.raycastFirst(o,n);a&&a.entity.sceneData&&(console.log(`[Gallery] Loading scene: ${a.entity.sceneData.name}`),this.hideGalleryMode(),this.loadSceneByIndex(a.entity.sceneIndex))}};var ObjectiveManager=pc.createScript("objectiveManager");ObjectiveManager.attributes.add("hudEnabled",{type:"boolean",default:!0,title:"Show HUD"}),ObjectiveManager.prototype.initialize=function(){console.log("=== OBJECTIVE MANAGER INITIALIZED ==="),this.objectives={},this.activeObjectives=[],this.completedObjectives=new Set,this.currentObjective=null,this.currentAct=0,this.totalActs=0,this.actNames=[],this.hudEnabled&&this.createHUD(),this.setupEventListeners(),this.app.on("scene:objectives",this.onSceneObjectives,this),this.app.on("mission:objectives",this.onMissionObjectives,this),this.app.on("mission:actChange",this.onActChange,this),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),console.log("Press O to toggle objectives HUD"),console.log("Press P to show progress"),console.log("Press B to show all objectives"),setTimeout((()=>{this.updateHUD()}),100)},ObjectiveManager.prototype.setupEventListeners=function(){this.app.on("interaction:triggered",(e=>{console.log("[Objectives] Interaction:",e),this.checkAllTasks({type:"interaction",target:e})})),this.app.on("ui:toggled",(e=>{console.log("[Objectives] UI toggled"),this.checkAllTasks({type:"ui_toggle"})})),this.app.on("dataset:sceneLoaded",(e=>{console.log("[Objectives] Scene loaded:",e.id),this.checkAllTasks({type:"scene_loaded",sceneId:e.id})})),this.app.on("dataset:sceneUnloaded",(()=>{console.log("[Objectives] Scene unloaded"),this.checkAllTasks({type:"scene_unloaded"})})),this.timer=0},ObjectiveManager.prototype.update=function(e){this.currentObjective&&(this.timer+=e,this.currentObjective.tasks.forEach((e=>{e.completed||"time"!==e.condition.type||this.timer>=e.condition.value&&this.completeTask(e)}))),this.checkProximityConditions()},ObjectiveManager.prototype.checkProximityConditions=function(){if(!this.currentObjective)return;const e=this.app.root.findByName("SurgeonCamera");if(!e)return;const t=e.getPosition();this.currentObjective.tasks.forEach((e=>{if(!e.completed&&"proximity"===e.condition.type){let i=this.app.root.findByName(e.condition.target);if(!i){const t=[];this.collectAllEntities(this.app.root,t),i=t.find((t=>t.name.toLowerCase().includes(e.condition.target.toLowerCase())||e.condition.target.toLowerCase().includes(t.name.toLowerCase())))}if(i){t.distance(i.getPosition())<e.condition.distance&&(console.log(`[Objectives] Proximity condition met for ${e.condition.target}`),this.completeTask(e))}}}))},ObjectiveManager.prototype.collectAllEntities=function(e,t){t.push(e),e.children.forEach((e=>this.collectAllEntities(e,t)))},ObjectiveManager.prototype.onMissionObjectives=function(e){console.log("[Objectives] Received mission objectives:",e),this.currentAct=e.currentAct||1,this.totalActs=e.totalActs||1,this.actNames=e.actNames||[],this.setObjective(e.objective)},ObjectiveManager.prototype.onActChange=function(e){console.log("[Objectives] Act changed:",e),this.currentAct=e.currentAct,this.totalActs=e.totalActs,e.actName&&(this.actNames[e.currentAct-1]=e.actName),this.updateHUD()},ObjectiveManager.prototype.onSceneObjectives=function(e){console.log("[Objectives] Received scene objectives:",e),this.setObjective(e)},ObjectiveManager.prototype.setObjective=function(e){e&&(console.log(`\n=== NEW OBJECTIVE: ${e.title} ===`),console.log(e.description),console.log("Tasks:",e.tasks.length),this.timer=0,e.tasks.forEach((e=>{e.completed=!1})),this.currentObjective=e,this.objectives[e.id]=e,this.activeObjectives.includes(e)||this.activeObjectives.push(e),this.updateHUD())},ObjectiveManager.prototype.checkAllTasks=function(e){this.currentObjective&&this.currentObjective.tasks.forEach((t=>{if(t.completed)return;const i=t.condition;let c=!1;switch(i.type){case"interaction":if("interaction"===e.type){const t=i.target.toLowerCase(),o=e.target.toLowerCase();(o===t||o.includes(t)||t.includes(o))&&(c=!0)}break;case"ui_toggle":"ui_toggle"===e.type&&(c=!0);break;case"scene_loaded":"scene_loaded"===e.type&&e.sceneId===i.sceneId&&(c=!0);break;case"scene_unloaded":"scene_unloaded"===e.type&&(c=!0)}c&&this.completeTask(t)}))},ObjectiveManager.prototype.completeTask=function(e){if(e&&!e.completed&&(console.log(`[Objectives] Completing task: ${e.text}`),e.completed=!0,this.updateHUD(!0),this.app.fire("objective:taskCompleted",{task:e,objective:this.currentObjective}),this.currentObjective)){this.currentObjective.tasks.every((e=>e.completed))&&(console.log("[Objectives] All tasks complete for current objective!"),this.app.fire("objective:completed",this.currentObjective.id))}},ObjectiveManager.prototype.checkObjectiveCompletion=function(){if(!this.currentObjective)return;this.currentObjective.tasks.every((e=>e.completed))&&(console.log(`\n🎉 OBJECTIVE COMPLETE: ${this.currentObjective.title}`),this.completedObjectives.add(this.currentObjective.id),this.app.fire("objective:completed",this.currentObjective.id),this.currentObjective.nextObjective&&setTimeout((()=>{const e=this.objectives[this.currentObjective.nextObjective];e&&this.setObjective(e)}),2e3))},ObjectiveManager.prototype.createHUD=function(){let e=this.app.root.findByName("ObjectivesUIScreen");e||(e=new pc.Entity("ObjectivesUIScreen"),e.addComponent("screen",{referenceResolution:new pc.Vec2(1920,1080),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),this.app.root.addChild(e)),this.hudPanel=new pc.Entity("ObjectivesHUD"),this.hudPanel.addComponent("element",{type:"image",anchor:new pc.Vec4(.98,.98,.98,.98),pivot:new pc.Vec2(1,1),width:450,height:400,color:new pc.Color(.05,.05,.1),opacity:.95}),e.addChild(this.hudPanel),this.hudPanel.setLocalPosition(-20,-20,0);const t=new pc.Entity("TitleBg");t.addComponent("element",{type:"image",anchor:new pc.Vec4(0,.88,1,1),pivot:new pc.Vec2(.5,.5),color:new pc.Color(.15,.15,.25),opacity:1}),this.hudPanel.addChild(t),this.titleText=new pc.Entity("ObjectivesTitle"),this.titleText.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),fontSize:20,text:"OBJECTIVES",color:new pc.Color(1,1,1),autoWidth:!1,wrapLines:!1,alignment:new pc.Vec2(.5,.5)}),t.addChild(this.titleText),this.actProgress=new pc.Entity("ActProgress"),this.actProgress.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.84,.5,.84),pivot:new pc.Vec2(.5,1),fontSize:14,text:"Act 1 of 1",color:new pc.Color(.9,.9,.9),autoWidth:!1,wrapLines:!1,alignment:new pc.Vec2(.5,.5)}),this.hudPanel.addChild(this.actProgress),this.objectiveName=new pc.Entity("ObjectiveName"),this.objectiveName.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.78,.5,.78),pivot:new pc.Vec2(.5,1),fontSize:16,text:"",color:new pc.Color(1,.9,.1),autoWidth:!1,wrapLines:!0,width:380,alignment:new pc.Vec2(.5,.5)}),this.hudPanel.addChild(this.objectiveName),this.taskList=new pc.Entity("TaskList"),this.taskList.addComponent("element",{type:"group",anchor:new pc.Vec4(.05,.05,.95,.74),pivot:new pc.Vec2(.5,1),useInput:!1}),this.hudPanel.addChild(this.taskList),this.copyFonts(),console.log("[Objectives] HUD created successfully")},ObjectiveManager.prototype.copyFonts=function(){const e=this.app.root.findByName("DescriptionText");if(e&&e.element){[this.titleText,this.actProgress,this.objectiveName].forEach((t=>{t&&t.element&&(e.element.font&&(t.element.font=e.element.font),e.element.fontAsset&&(t.element.fontAsset=e.element.fontAsset))}))}},ObjectiveManager.prototype.updateHUD=function(e=!1){if(this.hudPanel){if(console.log("[Objectives] Updating HUD..."),this.actProgress){let e="";this.totalActs>0?(e=`Act ${this.currentAct} of ${this.totalActs}`,this.actNames[this.currentAct-1]&&(e+=`: ${this.actNames[this.currentAct-1]}`)):e="Objectives",this.actProgress.element.text=e}for(this.objectiveName&&(this.objectiveName.element.text=this.currentObjective?this.currentObjective.title:"No active objectives");this.taskList.children.length>0;)this.taskList.children[0].destroy();if(this.currentObjective&&(console.log("[Objectives] Current objective:",this.currentObjective.title),console.log("[Objectives] Tasks:",this.currentObjective.tasks)),this.currentObjective&&this.currentObjective.tasks&&this.currentObjective.tasks.length>0){const t=4;if(this.currentObjective.tasks.slice(0,t).forEach(((t,i)=>{const c=new pc.Entity("TaskContainer"+i);c.addComponent("element",{type:"group",anchor:new pc.Vec4(0,1,1,1),pivot:new pc.Vec2(0,1),height:50}),c.setLocalPosition(0,-10-55*i,0);const o=new pc.Entity("Task"+i);o.addComponent("element",{type:"text",anchor:new pc.Vec4(0,.5,0,.5),pivot:new pc.Vec2(0,.5),fontSize:14,text:(t.completed?"✓ ":"• ")+t.text,color:t.completed?new pc.Color(.3,1,.3):new pc.Color(1,1,1),autoWidth:!1,wrapLines:!0,width:350,alignment:new pc.Vec2(0,.5)});const n=this.app.root.findByName("DescriptionText");if(n&&n.element&&(n.element.font&&(o.element.font=n.element.font),n.element.fontAsset&&(o.element.fontAsset=n.element.fontAsset)),o.setLocalPosition(15,0,0),c.addChild(o),!t.completed&&t.hint){const e=new pc.Entity("Hint"+i);e.addComponent("element",{type:"text",anchor:new pc.Vec4(0,0,0,0),pivot:new pc.Vec2(0,1),fontSize:11,text:"  → "+t.hint,color:new pc.Color(.7,.7,.7),autoWidth:!1,wrapLines:!0,width:330,alignment:new pc.Vec2(0,.5)}),n&&n.element&&(n.element.font&&(e.element.font=n.element.font),n.element.fontAsset&&(e.element.fontAsset=n.element.fontAsset)),e.setLocalPosition(25,-20,0),c.addChild(e)}this.taskList.addChild(c),e&&t.completed&&(o.setLocalScale(1.2,1.2,1),setTimeout((()=>{o&&!o._destroyed&&o.setLocalScale(1,1,1)}),300))})),this.currentObjective.tasks.length>t){const e=new pc.Entity("MoreTasks");e.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,0,.5,0),pivot:new pc.Vec2(.5,1),fontSize:12,text:`... and ${this.currentObjective.tasks.length-t} more`,color:new pc.Color(.6,.6,.6),alignment:new pc.Vec2(.5,.5)}),e.setLocalPosition(0,-10-55*t,0),this.taskList.addChild(e)}}else{const e=new pc.Entity("NoTasks");e.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),fontSize:14,text:"No active tasks",color:new pc.Color(.6,.6,.6),alignment:new pc.Vec2(.5,.5)}),this.taskList.addChild(e)}}},ObjectiveManager.prototype.toggleHUD=function(){this.hudPanel&&(this.hudPanel.enabled=!this.hudPanel.enabled,console.log("[Objectives] HUD",this.hudPanel.enabled?"shown":"hidden"))},ObjectiveManager.prototype.onKeyDown=function(e){switch(e.key){case pc.KEY_O:this.toggleHUD();break;case pc.KEY_P:this.showProgress();break;case pc.KEY_B:this.showAllObjectives()}},ObjectiveManager.prototype.showProgress=function(){if(console.log("\n=== OBJECTIVES PROGRESS ==="),console.log(`Completed: ${this.completedObjectives.size}`),this.totalActs>0&&(console.log(`Current Act: ${this.currentAct} of ${this.totalActs}`),this.actNames[this.currentAct-1]&&console.log(`Act Name: ${this.actNames[this.currentAct-1]}`)),this.currentObjective){const e=this.currentObjective.tasks.filter((e=>e.completed)).length,t=this.currentObjective.tasks.length;console.log(`Current: ${this.currentObjective.title} (${e}/${t})`),this.currentObjective.tasks.forEach((e=>{console.log(`  ${e.completed?"✓":"○"} ${e.text}`),!e.completed&&e.hint&&console.log(`    → ${e.hint}`)}))}console.log("========================\n")},ObjectiveManager.prototype.showAllObjectives=function(){console.log("\n=== ALL OBJECTIVES ==="),console.log("Available:",Object.keys(this.objectives)),console.log("Active:",this.activeObjectives.map((e=>e.id))),console.log("Completed:",Array.from(this.completedObjectives)),console.log("Current:",this.currentObjective?.id),console.log("===================\n")},ObjectiveManager.prototype.hasCompletedObjective=function(e){return this.completedObjectives.has(e)},ObjectiveManager.prototype.getCurrentProgress=function(){if(!this.currentObjective)return null;const e=this.currentObjective.tasks.filter((e=>e.completed)).length,t=this.currentObjective.tasks.length;return{objective:this.currentObjective.id,completed:e,total:t,percentage:e/t*100,currentAct:this.currentAct,totalActs:this.totalActs}};var SceneInteractivityManager=pc.createScript("sceneInteractivityManager");SceneInteractivityManager.attributes.add("sceneObjectivesUrl",{type:"string",default:"https://huggingface.co/datasets/KwabsHug/playcanvas-scenes-experiment/resolve/main/scene_objectives.json",title:"Scene Objectives URL"}),SceneInteractivityManager.prototype.initialize=function(){console.log("=== SCENE INTERACTIVITY MANAGER ==="),this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this),this.interactiveEntities=new Map,this.sceneObjectives=null,this.sceneObjectives=this.getDefaultSceneObjectives(),console.log("[Interactivity] Using default scene objectives"),this.interactionTemplates={control_panel:{onInteract:function(e){console.log("Control panel activated!");const t=e.findByName("PanelScreen");if(t&&t.render){const e=t.render.material,n=e.emissive.r>.5;return e.emissive.set(0,n?.5:1,n?0:.5),e.update(),"Panel "+(n?"deactivated":"activated")}return"Panel activated"}},hologram:{onInteract:function(e){if(console.log("Hologram touched!"),e.render){const t=e.render.material,n=Date.now()/1e3%1;t.emissive.set(n,1-n,.5),t.update()}return"Hologram data accessed"}},equipment:{onInteract:function(e){if(console.log(`Equipment ${e.name} activated!`),e.name.toLowerCase().includes("centrifuge")){const t=e.findByName("CentrifugeLid");if(t){if(!e._spinning){e._spinning=!0,e._spinTime=0;const spin=()=>{e._spinning&&!e._destroyed&&(e._spinTime+=.016,t.rotate(0,10,0),e._spinTime<3?requestAnimationFrame(spin):e._spinning=!1)};spin()}return"Centrifuge spinning"}}return this.flashEntity(e),`${e.name} activated`}},crystal:{onInteract:function(e){console.log("Crystal touched!");const t=e.getLocalScale().clone();return e.setLocalScale(1.5*t.x,1.5*t.y,1.5*t.z),setTimeout((()=>{e.setLocalScale(t)}),300),"Crystal resonates with energy"}}},this.app.on("interaction:triggered",this.onDirectInteraction,this)},SceneInteractivityManager.prototype.onSceneLoaded=function(e,t){console.log("\n[Interactivity] === SCENE LOADED ==="),console.log("[Interactivity] Scene Info:",e),this.interactiveEntities.clear();const n=[];this.collectEntities(t,n),console.log(`[Interactivity] Found ${n.length} entities in scene`),this.processParentEntities(n),console.log(`[Interactivity] Made ${this.interactiveEntities.size} entities interactive`),setTimeout((()=>{this.activateSceneObjectives(e.id)}),500)},SceneInteractivityManager.prototype.processParentEntities=function(e){const t=new Set;e.forEach((e=>{const n=e.name.toLowerCase();"centrifuge"!==n&&"microscope"!==n&&"controlpanel"!==n&&"hologramdisplay"!==n&&"floatingcrystal"!==n||(t.add(e),console.log(`[Interactivity] Found parent entity: ${e.name}`))})),t.forEach((e=>{const t=e.name.toLowerCase();let n="default";t.includes("centrifuge")||t.includes("microscope")?n="equipment":t.includes("control")||t.includes("panel")?n="control_panel":t.includes("hologram")?n="hologram":t.includes("crystal")&&(n="crystal"),this.makeParentInteractive(e,n)})),e.forEach((e=>{!e.render||this.hasInteractiveParent(e)||t.has(e)||this.processIndividualEntity(e)}))},SceneInteractivityManager.prototype.hasInteractiveParent=function(e){let t=e.parent;for(;t&&"DynamicSceneRoot"!==t.name;){if(this.interactiveEntities.has(t.name))return!0;t=t.parent}return!1},SceneInteractivityManager.prototype.makeParentInteractive=function(e,t){console.log(`[Interactivity] Making parent ${e.name} interactive (type: ${t})`);let n=null,i=0;if(e.children.forEach((e=>{if(e.render){const t=e.getLocalScale(),a=t.x*t.y*t.z;a>i&&(i=a,n=e)}})),n){if(console.log(`[Interactivity] Using ${n.name} as collision target for ${e.name}`),n.collision||this.addCollisionToEntity(n),this.interactiveEntities.set(e.name,{entity:e,collisionEntity:n,type:t,originalMaterial:n.render?n.render.material:null}),this.interactiveEntities.set(n.name,{entity:e,collisionEntity:n,type:t,originalMaterial:n.render?n.render.material:null}),n.render&&n.render.material){const e=n.render.material;(!e.emissive||0===e.emissive.r&&0===e.emissive.g&&0===e.emissive.b)&&(e.emissive.set(.1,.1,.2),e.update())}e.tags.add("interactive"),e.tags.add("dynamic_scene"),e._dynamicInteraction=n=>{const i=this.interactionTemplates[t];if(i&&i.onInteract){const n=i.onInteract.call(this,e);return this.app.fire("dynamic:interaction",{entity:e,type:t,result:n}),this.app.fire("interaction:triggered",e.name),n}return`Interacted with ${e.name}`}}else console.log(`[Interactivity] No renderable children found for ${e.name}`)},SceneInteractivityManager.prototype.addCollisionToEntity=function(e){const t=e.getLocalScale();let n="box",i={};"sphere"===e.render.type?(n="sphere",i.radius=.5*Math.max(t.x,t.y,t.z)):"cylinder"===e.render.type?(n="cylinder",i.radius=.5*Math.max(t.x,t.z),i.height=t.y):"capsule"===e.render.type?(n="capsule",i.radius=.5*Math.max(t.x,t.z),i.height=t.y):"plane"===e.render.type?(n="box",i.halfExtents=new pc.Vec3(t.x/2,.1,t.z/2)):i.halfExtents=new pc.Vec3(t.x/2,t.y/2,t.z/2);try{e.addComponent("collision",Object.assign({type:n},i)),e.rigidbody||e.addComponent("rigidbody",{type:"static"}),console.log(`[Interactivity] Added ${n} collision to ${e.name}`)}catch(t){console.error(`[Interactivity] Failed to add collision to ${e.name}:`,t)}},SceneInteractivityManager.prototype.processIndividualEntity=function(e){const t=e.name.toLowerCase();let n=!1,i="default";t.includes("button")||t.includes("switch")?(n=!0,i="button"):t.includes("platform")&&!t.includes("floating")&&(n=!0,i="platform"),n&&!e.collision&&(console.log(`[Interactivity] Making individual entity ${e.name} interactive`),this.addCollisionToEntity(e),this.interactiveEntities.set(e.name,{entity:e,collisionEntity:e,type:i}),e.tags.add("interactive"),e.tags.add("dynamic_scene"))},SceneInteractivityManager.prototype.onDirectInteraction=function(e){console.log(`[Interactivity] Interaction detected with: ${e}`);const t=this.interactiveEntities.get(e);if(t&&t.entity._dynamicInteraction){const e=t.entity._dynamicInteraction(null);this.showInteractionResult(t.entity,e)}else console.log(`[Interactivity] No interaction handler for ${e}`)},SceneInteractivityManager.prototype.collectEntities=function(e,t){t.push(e),e.children.forEach((e=>this.collectEntities(e,t)))},SceneInteractivityManager.prototype.flashEntity=function(e){let t=e;if(!e.render&&e.children.length>0)for(let n of e.children)if(n.render){t=n;break}if(!t.render||!t.render.material)return;const n=t.render.material,i=n.emissive.clone();n.emissive.set(1,1,1),n.update(),setTimeout((()=>{n.emissive.copy(i),n.update()}),200)},SceneInteractivityManager.prototype.showInteractionResult=function(e,t){if(!t)return;const n=new pc.Entity("InteractionText");n.addComponent("element",{type:"text",text:t,fontSize:24,color:new pc.Color(1,1,0),alignment:new pc.Vec2(.5,.5)});const i=e.getPosition();n.setPosition(i.x,i.y+2,i.z);const a=this.app.root.findByName("DescriptionText");a&&a.element&&(a.element.font&&(n.element.font=a.element.font),a.element.fontAsset&&(n.element.fontAsset=a.element.fontAsset)),this.app.root.addChild(n);let o=0;const update=()=>{o+=.016,n.setPosition(i.x,i.y+2+o,i.z),n.element.opacity=1-o/2,o<2?requestAnimationFrame(update):n.destroy()};update()},SceneInteractivityManager.prototype.getDefaultObjectives=function(){return{medical_lab:{id:"explore_lab",title:"Investigate the Laboratory",description:"Explore the research facility",type:"parallel",autoActivate:!0,tasks:[{id:"find_microscope",text:"Find the microscope",hint:"Look for it on a bench",condition:{type:"proximity",target:"Microscope",distance:3},completed:!1},{id:"check_centrifuge",text:"Check the centrifuge",hint:"Press F to interact",condition:{type:"interaction",target:"Centrifuge"},completed:!1},{id:"explore_lab_time",text:"Explore the lab for 10 seconds",hint:"Take your time looking around",condition:{type:"time",value:10},completed:!1}]},scifi_env:{id:"explore_scifi",title:"Alien Technology",description:"Investigate the futuristic environment",type:"sequential",autoActivate:!0,tasks:[{id:"find_hologram",text:"Find the central hologram",hint:"Look for the glowing blue box",condition:{type:"proximity",target:"HologramDisplay",distance:5},completed:!1},{id:"activate_panel",text:"Activate any control panel",hint:"Press F near a panel",condition:{type:"interaction",target:"ControlPanel"},completed:!1},{id:"explore_time",text:"Study the environment",hint:"Observe for 5 seconds",condition:{type:"time",value:5},completed:!1}]},test_crystal:{id:"crystal_test",title:"Crystal Analysis",description:"Study the mysterious crystal",type:"simple",autoActivate:!0,tasks:[{id:"observe_crystal",text:"Observe the floating crystal",hint:"Watch it for a few seconds",condition:{type:"time",value:5},completed:!1}]}}},SceneInteractivityManager.prototype.activateSceneObjectives=function(e){const t={medical_lab:"medical_lab",scifi_scene:"scifi_env",scifi_env:"scifi_env",test_scene:"test_crystal",test_crystal:"test_crystal"}[e]||e,n=this.sceneObjectives[t];n&&(console.log(`[Interactivity] Activating objectives for: ${t}`),this.app.fire("scene:objectives",n))};var DebugInteractivityManager=pc.createScript("debugInteractivityManager");DebugInteractivityManager.prototype.initialize=function(){console.log("=== DEBUG INTERACTIVITY MANAGER ==="),this.debugMarkers=[],this.showDebug=!0,this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),console.log("Press D to toggle debug markers"),console.log("Press V to list all scene entities"),console.log("Press B to check raycast setup")},DebugInteractivityManager.prototype.onKeyDown=function(e){switch(e.key){case pc.KEY_D:this.toggleDebugMarkers();break;case pc.KEY_V:this.listAllEntities();break;case pc.KEY_B:this.checkRaycastSystem()}},DebugInteractivityManager.prototype.onSceneLoaded=function(e,t){console.log("\n[DEBUG] === ANALYZING LOADED SCENE ==="),console.log("[DEBUG] Scene:",e.name),this.clearDebugMarkers();const o={total:0,withRender:0,withCollision:0,withRigidbody:0,withTags:0,potentiallyInteractive:[]};this.analyzeEntity(t,o),console.log("[DEBUG] Analysis Results:"),console.log(`  Total Entities: ${o.total}`),console.log(`  With Render: ${o.withRender}`),console.log(`  With Collision: ${o.withCollision}`),console.log(`  With Rigidbody: ${o.withRigidbody}`),console.log(`  With Tags: ${o.withTags}`),console.log(`  Potentially Interactive: ${o.potentiallyInteractive.length}`),console.log("\n[DEBUG] Making ALL rendered objects interactive..."),o.potentiallyInteractive.forEach((e=>{this.makeInteractiveDebug(e)})),this.showDebug&&this.createDebugMarkers()},DebugInteractivityManager.prototype.analyzeEntity=function(e,t){e&&!e._destroyed&&(t.total++,e.render&&(t.withRender++,t.potentiallyInteractive.push(e),console.log(`[DEBUG] Renderable: ${e.name} (${e.render.type})`)),e.collision&&(t.withCollision++,console.log(`[DEBUG] Has Collision: ${e.name}`)),e.rigidbody&&t.withRigidbody++,e.tags&&e.tags._list.length>0&&(t.withTags++,console.log(`[DEBUG] Has Tags: ${e.name} - ${e.tags._list.join(", ")}`)),e.children.forEach((e=>this.analyzeEntity(e,t))))},DebugInteractivityManager.prototype.makeInteractiveDebug=function(e){if(console.log(`[DEBUG] Processing: ${e.name}`),e.collision)console.log(`[DEBUG] ${e.name} already has collision`);else try{const t=e.getLocalScale();let o=!1;"box"===e.render.type?(e.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(t.x/2,t.y/2,t.z/2)}),o=!0):"sphere"===e.render.type?(e.addComponent("collision",{type:"sphere",radius:Math.max(t.x,t.y,t.z)/2}),o=!0):"cylinder"===e.render.type?(e.addComponent("collision",{type:"cylinder",radius:Math.max(t.x,t.z)/2,height:t.y}),o=!0):"capsule"===e.render.type?(e.addComponent("collision",{type:"capsule",radius:Math.max(t.x,t.z)/2,height:t.y}),o=!0):(e.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(t.x/2,t.y/2,t.z/2)}),o=!0),o&&(e.addComponent("rigidbody",{type:"static"}),e.tags.add("interactive"),e.tags.add("debug_interactive"),console.log(`[DEBUG] ✓ Made interactive: ${e.name}`))}catch(t){console.error(`[DEBUG] Failed to make ${e.name} interactive:`,t)}},DebugInteractivityManager.prototype.createDebugMarkers=function(){console.log("[DEBUG] Creating visual markers...");this.app.root.findByTag("interactive").forEach((e=>{const t=new pc.Entity("DebugMarker_"+e.name);t.addComponent("render",{type:"sphere"});const o=new pc.StandardMaterial;o.diffuse.set(1,1,0),o.emissive.set(1,1,0),o.opacity=.3,o.blendType=pc.BLEND_NORMAL,o.update(),t.render.material=o;const n=e.getPosition();t.setPosition(n.x,n.y+1,n.z),t.setLocalScale(.2,.2,.2),e.addChild(t),this.debugMarkers.push(t)})),console.log(`[DEBUG] Created ${this.debugMarkers.length} debug markers`)},DebugInteractivityManager.prototype.clearDebugMarkers=function(){this.debugMarkers.forEach((e=>{e&&!e._destroyed&&e.destroy()})),this.debugMarkers=[]},DebugInteractivityManager.prototype.toggleDebugMarkers=function(){this.showDebug=!this.showDebug,this.showDebug?this.createDebugMarkers():this.clearDebugMarkers(),console.log("[DEBUG] Debug markers: "+(this.showDebug?"ON":"OFF"))},DebugInteractivityManager.prototype.listAllEntities=function(){console.log("\n[DEBUG] === ALL SCENE ENTITIES ===");const e=this.app.root.findByName("SurgeonCamera");if(!e)return void console.error("[DEBUG] Camera not found!");const t=e.getPosition();console.log(`[DEBUG] Camera position: ${t.x.toFixed(2)}, ${t.y.toFixed(2)}, ${t.z.toFixed(2)}`);const o=[];this.findEntitiesWithComponent(this.app.root,"collision",o),console.log(`\n[DEBUG] Entities with collision (${o.length}):`),o.forEach((e=>{const o=e.getPosition(),n=t.distance(o);console.log(`  - ${e.name} at (${o.x.toFixed(2)}, ${o.y.toFixed(2)}, ${o.z.toFixed(2)}) - Distance: ${n.toFixed(2)}`)})),console.log("[DEBUG] ========================\n")},DebugInteractivityManager.prototype.findEntitiesWithComponent=function(e,t,o){e[t]&&o.push(e),e.children.forEach((e=>this.findEntitiesWithComponent(e,t,o)))},DebugInteractivityManager.prototype.checkRaycastSystem=function(){if(console.log("\n[DEBUG] === RAYCAST SYSTEM CHECK ==="),"undefined"==typeof Ammo)return void console.error("[DEBUG] Ammo physics not loaded!");const e=this.app.root.findByName("SurgeonCamera");if(e){if(e.script&&e.script.has("interactionController")){console.log("[DEBUG] ✓ Interaction controller found on camera");const t=e.getPosition(),o=e.forward,n=(new pc.Vec3).copy(o).mulScalar(10).add(t);console.log(`[DEBUG] Test raycast from: ${t.toString()}`),console.log(`[DEBUG] Test raycast to: ${n.toString()}`);const i=this.app.systems.rigidbody.raycastFirst(t,n);i?console.log(`[DEBUG] Raycast hit: ${i.entity.name} at distance ${i.point.distance(t).toFixed(2)}`):console.log("[DEBUG] Raycast hit nothing")}else console.error("[DEBUG] No interaction controller on camera!");console.log("[DEBUG] ========================\n")}else console.error("[DEBUG] Camera not found!")};var SimpleInteractionTest=pc.createScript("simpleInteractionTest");SimpleInteractionTest.prototype.initialize=function(){console.log("=== SIMPLE INTERACTION TEST ==="),console.log("Press T to create a test cube"),console.log("Press Y to list interactable objects"),console.log("=============================="),this.testCube=null,this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.app.on("interaction:triggered",(function(e){console.log("[TEST] Interaction triggered with:",e)})),setTimeout((()=>{this.checkCameraSetup()}),1e3)},SimpleInteractionTest.prototype.onKeyDown=function(e){e.key===pc.KEY_T?this.createTestCube():e.key===pc.KEY_Y&&this.listInteractables()},SimpleInteractionTest.prototype.checkCameraSetup=function(){console.log("\n[TEST] Checking camera setup...");const e=this.app.root.findByName("SurgeonCamera");if(e)if(console.log("[TEST] ✓ Camera found"),e.script){if(console.log("[TEST] ✓ Camera has script component"),!e.script.has("interactionController"))return console.error("[TEST] ERROR: Camera missing interactionController!"),void console.log("[TEST] Available scripts:",e.script._scripts.map((e=>e.__scriptType.__name)));console.log("[TEST] ✓ Camera has interactionController"),console.log("[TEST] System should be working!\n")}else console.error("[TEST] ERROR: Camera has no script component!");else console.error("[TEST] ERROR: SurgeonCamera not found!")},SimpleInteractionTest.prototype.createTestCube=function(){this.testCube&&this.testCube.destroy(),console.log("[TEST] Creating test cube..."),this.testCube=new pc.Entity("TestInteractionCube"),this.testCube.addComponent("render",{type:"box"});const e=new pc.StandardMaterial;e.diffuse.set(1,0,0),e.emissive.set(.5,0,0),e.update(),this.testCube.render.material=e;const t=this.app.root.findByName("SurgeonCamera");if(t){const e=t.getPosition(),o=t.forward;this.testCube.setPosition(e.x+3*o.x,e.y+3*o.y,e.z+3*o.z)}else this.testCube.setPosition(0,1,-3);this.testCube.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(.5,.5,.5)}),this.testCube.addComponent("rigidbody",{type:"static"}),this.app.root.addChild(this.testCube),console.log("[TEST] Test cube created at:",this.testCube.getPosition().toString()),console.log("[TEST] Try looking at the RED CUBE and pressing F")},SimpleInteractionTest.prototype.listInteractables=function(){console.log("\n[TEST] === INTERACTABLE OBJECTS ===");const e=[];this.findWithCollision(this.app.root,e),console.log(`[TEST] Found ${e.length} objects with collision:`);const t=this.app.root.findByName("SurgeonCamera"),o=t?t.getPosition():new pc.Vec3;e.forEach(((e,t)=>{const i=e.getPosition(),n=o.distance(i),s=e.collision.type;console.log(`${t+1}. ${e.name}`),console.log(`   Position: (${i.x.toFixed(1)}, ${i.y.toFixed(1)}, ${i.z.toFixed(1)})`),console.log(`   Distance: ${n.toFixed(1)}m`),console.log(`   Collision: ${s}`),console.log(`   Has rigidbody: ${!!e.rigidbody}`)})),console.log("[TEST] ========================\n")},SimpleInteractionTest.prototype.findWithCollision=function(e,t){e.collision&&e.rigidbody&&t.push(e),e.children.forEach((e=>this.findWithCollision(e,t)))};var EntityNameDebugger=pc.createScript("entityNameDebugger");EntityNameDebugger.prototype.initialize=function(){console.log("=== ENTITY NAME DEBUGGER ==="),console.log('Press N to list all entities with "centrifuge" in name'),console.log('Press M to list all entities with "panel" in name'),console.log("Press L to list ALL entities in dynamic scenes"),console.log("==========================="),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this)},EntityNameDebugger.prototype.onKeyDown=function(e){switch(e.key){case pc.KEY_N:this.findEntitiesWithName("centrifuge");break;case pc.KEY_M:this.findEntitiesWithName("panel");break;case pc.KEY_L:this.listAllDynamicEntities()}},EntityNameDebugger.prototype.onSceneLoaded=function(e,o){console.log(`\n[NAME DEBUG] Scene loaded: ${e.name}`),console.log("[NAME DEBUG] Analyzing entity names...");const n={total:0,byKeyword:{centrifuge:[],panel:[],microscope:[],hologram:[],control:[],screen:[],base:[],body:[],lid:[]}};this.analyzeNames(o,n),console.log(`[NAME DEBUG] Total entities: ${n.total}`),console.log("[NAME DEBUG] Entities by keyword:"),Object.entries(n.byKeyword).forEach((([e,o])=>{o.length>0&&(console.log(`  "${e}": ${o.length} entities`),o.forEach((e=>{console.log(`    - ${e}`)})))})),console.log("[NAME DEBUG] ==================\n")},EntityNameDebugger.prototype.analyzeNames=function(e,o){o.total++;const n=e.name.toLowerCase();Object.keys(o.byKeyword).forEach((t=>{n.includes(t)&&o.byKeyword[t].push(e.name)})),e.children.forEach((e=>this.analyzeNames(e,o)))},EntityNameDebugger.prototype.findEntitiesWithName=function(e){console.log(`\n[NAME DEBUG] Searching for entities with "${e}" in name...`);const o=[];this.searchEntity(this.app.root,e.toLowerCase(),o),0===o.length?console.log(`[NAME DEBUG] No entities found with "${e}" in name`):(console.log(`[NAME DEBUG] Found ${o.length} entities:`),o.forEach((({entity:e,path:o})=>{const n=e.getPosition();console.log(`\n  Entity: ${e.name}`),console.log(`  Path: ${o}`),console.log(`  Position: (${n.x.toFixed(2)}, ${n.y.toFixed(2)}, ${n.z.toFixed(2)})`),console.log(`  Has render: ${!!e.render}`),console.log(`  Has collision: ${!!e.collision}`),console.log(`  Has rigidbody: ${!!e.rigidbody}`),console.log(`  Tags: ${e.tags._list.join(", ")||"none"}`),e.render&&console.log(`  Render type: ${e.render.type}`)}))),console.log("[NAME DEBUG] ==================\n")},EntityNameDebugger.prototype.searchEntity=function(e,o,n,t=""){const i=t?`${t} > ${e.name}`:e.name;e.name.toLowerCase().includes(o)&&n.push({entity:e,path:i}),e.children.forEach((e=>{this.searchEntity(e,o,n,i)}))},EntityNameDebugger.prototype.listAllDynamicEntities=function(){console.log("\n[NAME DEBUG] === ALL DYNAMIC SCENE ENTITIES ===");const e=this.app.root.findByName("DynamicSceneRoot");if(!e)return void console.log("[NAME DEBUG] No dynamic scene loaded");const o=[];this.collectAll(e,o);const n={};o.forEach((e=>{const o=e.render?e.render.type:"no-render";n[o]||(n[o]=[]),n[o].push(e.name)})),console.log(`[NAME DEBUG] Total entities: ${o.length}`),console.log("[NAME DEBUG] By render type:"),Object.entries(n).forEach((([e,o])=>{console.log(`\n  ${e.toUpperCase()} (${o.length}):`),o.sort().forEach((e=>{console.log(`    - ${e}`)}))})),console.log("\n[NAME DEBUG] ========================\n")},EntityNameDebugger.prototype.collectAll=function(e,o){o.push(e),e.children.forEach((e=>this.collectAll(e,o)))};var SimpleDirectInteractivity=pc.createScript("simpleDirectInteractivity");SimpleDirectInteractivity.prototype.initialize=function(){console.log("=== SIMPLE DIRECT INTERACTIVITY ==="),this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this),this.checkInterval=setInterval((()=>{this.checkForDynamicScene()}),1e3),console.log("[Simple] Waiting for dynamic scenes...")},SimpleDirectInteractivity.prototype.onSceneLoaded=function(e,i){console.log("[Simple] Scene loaded event received:",e.name),setTimeout((()=>{this.processScene()}),500)},SimpleDirectInteractivity.prototype.checkForDynamicScene=function(){this.app.root.findByName("DynamicSceneRoot")&&!this.processed&&(console.log("[Simple] Found DynamicSceneRoot via interval check"),this.processScene())},SimpleDirectInteractivity.prototype.processScene=function(){console.log("[Simple] Processing scene...");const e=this.app.root.findByName("DynamicSceneRoot");if(!e)return void console.error("[Simple] No DynamicSceneRoot found!");this.processed=!0;[{name:"Centrifuge",type:"equipment"},{name:"Microscope",type:"equipment"},{name:"ControlPanel",type:"control_panel"},{name:"HologramDisplay",type:"hologram"},{name:"FloatingCrystal",type:"crystal"}].forEach((i=>{const t=e.findByName(i.name);t?(console.log(`[Simple] Found ${i.name}, making interactive...`),this.makeEntityInteractive(t,i.type)):console.log(`[Simple] ${i.name} not found in scene`)})),this.findAndProcessByPartialName(e,"CentrifugeBody","Centrifuge","equipment"),this.findAndProcessByPartialName(e,"PanelBase","ControlPanel","control_panel"),this.findAndProcessByPartialName(e,"MicroscopeBase","Microscope","equipment")},SimpleDirectInteractivity.prototype.findAndProcessByPartialName=function(e,i,t,n){const o=[];this.collectAll(e,o);const c=o.find((e=>e.name===i));c&&(console.log(`[Simple] Found ${i}, checking parent...`),c.parent&&c.parent.name===t?(console.log(`[Simple] Making ${t} interactive via ${i}`),this.makeParentInteractiveViaChild(c.parent,c,n)):(console.log(`[Simple] Making ${i} directly interactive`),this.makeEntityInteractive(c,n)))},SimpleDirectInteractivity.prototype.makeEntityInteractive=function(e,i){let t=e;if(!e.render&&e.children.length>0)for(let i of e.children)if(i.render){t=i,console.log(`[Simple] Using child ${i.name} for collision`);break}if(t.render){if(t.collision||this.addCollision(t),t.render.material){const e=t.render.material;(!e.emissive||0===e.emissive.r&&0===e.emissive.g&&0===e.emissive.b)&&(e.emissive.set(.1,.1,.3),e.update())}console.log(`[Simple] ${e.name} is now interactive!`)}else console.log(`[Simple] No renderable part found for ${e.name}`)},SimpleDirectInteractivity.prototype.makeParentInteractiveViaChild=function(e,i,t){if(i.collision||this.addCollision(i),i.render&&i.render.material){const e=i.render.material;(!e.emissive||0===e.emissive.r&&0===e.emissive.g&&0===e.emissive.b)&&(e.emissive.set(.1,.1,.3),e.update())}console.log(`[Simple] ${e.name} is now interactive via ${i.name}!`)},SimpleDirectInteractivity.prototype.addCollision=function(e){const i=e.getLocalScale();let t="box",n={};"sphere"===e.render.type?(t="sphere",n.radius=.5*Math.max(i.x,i.y,i.z)):"cylinder"===e.render.type?(t="cylinder",n.radius=.5*Math.max(i.x,i.z),n.height=i.y):n.halfExtents=new pc.Vec3(i.x/2,i.y/2,i.z/2);try{e.addComponent("collision",Object.assign({type:t},n)),e.addComponent("rigidbody",{type:"static"}),console.log(`[Simple] Added ${t} collision to ${e.name}`)}catch(e){console.error("[Simple] Failed to add collision:",e)}},SimpleDirectInteractivity.prototype.collectAll=function(e,i){i.push(e),e.children.forEach((e=>this.collectAll(e,i)))},SimpleDirectInteractivity.prototype.destroy=function(){this.checkInterval&&clearInterval(this.checkInterval)};var SceneFixes=pc.createScript("sceneFixes");SceneFixes.prototype.initialize=function(){console.log("=== SCENE FIXES ==="),this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this),this.checkInterval=setInterval((()=>{this.checkAndFix()}),1e3)},SceneFixes.prototype.onSceneLoaded=function(e,n){console.log("[Fixes] Scene loaded:",e.name),setTimeout((()=>{this.fixScene(e.id||e.name)}),100)},SceneFixes.prototype.checkAndFix=function(){this.app.root.findByName("DynamicSceneRoot")&&!this.fixed&&(this.fixed=!0,this.fixScene("unknown"))},SceneFixes.prototype.fixScene=function(e){console.log("[Fixes] Applying fixes for scene:",e);const n=this.app.root.findByName("SciFiFloor");if(n&&(console.log("[Fixes] Found SciFiFloor, fixing rotation and material..."),n.setEulerAngles(0,0,0),n.render&&n.render.material)){const e=n.render.material;e.diffuse.set(.3,.3,.35),e.metalness=.7,e.gloss=.6,e.update(),console.log("[Fixes] Floor material updated")}const o=[];this.findByRenderType(this.app.root,"plane",o),o.forEach((e=>{const n=e.getEulerAngles();90===Math.abs(n.x)&&e.name.toLowerCase().includes("floor")&&(console.log(`[Fixes] Fixing rotation for ${e.name}`),e.setEulerAngles(0,n.y,n.z))}))},SceneFixes.prototype.findByRenderType=function(e,n,o){e.render&&e.render.type===n&&o.push(e),e.children.forEach((e=>this.findByRenderType(e,n,o)))},SceneFixes.prototype.destroy=function(){this.checkInterval&&clearInterval(this.checkInterval)};var ManualInteractionAdder=pc.createScript("manualInteractionAdder");ManualInteractionAdder.prototype.initialize=function(){console.log("=== MANUAL INTERACTION ADDER ==="),console.log("Press X to manually add interactions to scene"),console.log("================================"),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this)},ManualInteractionAdder.prototype.onKeyDown=function(e){e.key===pc.KEY_X&&this.addInteractions()},ManualInteractionAdder.prototype.addInteractions=function(){console.log("[Manual] Adding interactions...");const e=this.app.root.findByName("DynamicSceneRoot");if(!e){console.error("[Manual] No DynamicSceneRoot found!"),console.log("[Manual] Searching entire scene...");const e=[];this.collectAll(this.app.root,e),console.log(`[Manual] Total entities in scene: ${e.length}`);const n=e.filter((e=>{const n=e.name.toLowerCase();return n.includes("centrifuge")||n.includes("panel")||n.includes("microscope")||n.includes("hologram")||n.includes("crystal")}));return console.log(`[Manual] Found ${n.length} interesting entities:`),void n.forEach((e=>{console.log(`  - ${e.name} (has render: ${!!e.render}, has collision: ${!!e.collision})`),e.render&&!e.collision&&(this.addCollisionToEntity(e),e.render.material&&(e.render.material.emissive.set(.2,.2,.5),e.render.material.update()),console.log(`[Manual] Made ${e.name} interactive!`))}))}["Centrifuge","CentrifugeBody","CentrifugeLid","ControlPanel","PanelBase","PanelScreen","Microscope","MicroscopeBase","HologramDisplay","FloatingCrystal"].forEach((n=>{const o=e.findByName(n);o&&(console.log(`[Manual] Processing ${n}...`),o.render&&!o.collision?(this.addCollisionToEntity(o),o.render.material&&(o.render.material.emissive.set(.2,.2,.5),o.render.material.update()),console.log(`[Manual] Made ${n} interactive!`)):o.render?o.collision&&console.log(`[Manual] ${n} already has collision`):console.log(`[Manual] ${n} has no render component`))})),console.log("[Manual] Done!")},ManualInteractionAdder.prototype.addCollisionToEntity=function(e){const n=e.getLocalScale();let o="box",a={};"sphere"===e.render.type?(o="sphere",a.radius=.5*Math.max(n.x,n.y,n.z)):"cylinder"===e.render.type?(o="cylinder",a.radius=.5*Math.max(n.x,n.z),a.height=n.y):a.halfExtents=new pc.Vec3(n.x/2,n.y/2,n.z/2);try{e.addComponent("collision",Object.assign({type:o},a)),e.addComponent("rigidbody",{type:"static"}),console.log(`[Manual] Added ${o} collision to ${e.name}`)}catch(n){console.error(`[Manual] Failed to add collision to ${e.name}:`,n)}},ManualInteractionAdder.prototype.collectAll=function(e,n){n.push(e),e.children.forEach((e=>this.collectAll(e,n)))};var DiagnosticScript=pc.createScript("diagnosticScript");DiagnosticScript.prototype.initialize=function(){console.log("=== DIAGNOSTIC SCRIPT INITIALIZED ==="),console.log("Time:",(new Date).toTimeString()),console.log("Entity name:",this.entity.name),this.entity.script&&(console.log("Scripts on this entity:"),this.entity.script._scripts.forEach((o=>{console.log("  -",o.__scriptType.__name)})));["dataset:sceneLoaded","scene:loaded","scene:integrated","interaction:triggered"].forEach((o=>{this.app.on(o,((...e)=>{console.log(`[DIAG] Event fired: ${o}`,e)}))}));let o=0;this.interval=setInterval((()=>{o++,console.log(`[DIAG] Check #${o}`);const e=this.app.root.findByName("DynamicSceneRoot");if(e){console.log("[DIAG] Found DynamicSceneRoot!");let o=0;const countEntities=e=>{o++,e.children.forEach(countEntities)};countEntities(e),console.log(`[DIAG] Total entities in dynamic scene: ${o}`);["Centrifuge","ControlPanel","SciFiFloor","CentrifugeBody","PanelBase"].forEach((o=>{const t=e.findByName(o);console.log(`[DIAG] ${o}: ${t?"FOUND":"NOT FOUND"}`),t&&t.collision&&console.log("[DIAG]   - Has collision: YES")})),clearInterval(this.interval)}else console.log("[DIAG] No DynamicSceneRoot yet")}),1e3),this.app.keyboard.on(pc.EVENT_KEYDOWN,(o=>{o.key===pc.KEY_G&&this.manualCheck()})),console.log("[DIAG] Press G for manual check"),console.log("=========================")},DiagnosticScript.prototype.manualCheck=function(){console.log("\n[DIAG] === MANUAL CHECK ===");const o=[];this.findAllScripts(this.app.root,o),console.log(`[DIAG] Total script components: ${o.length}`);const e={};o.forEach((o=>{o._scripts.forEach((o=>{const t=o.__scriptType.__name;e[t]=(e[t]||0)+1}))})),console.log("[DIAG] Script types in scene:"),Object.entries(e).forEach((([o,e])=>{console.log(`  - ${o}: ${e}`)}));["simpleDirectInteractivity","sceneFixes","sceneInteractivityManager"].forEach((o=>{e[o]?console.log(`[DIAG] ✓ ${o} is in scene`):console.log(`[DIAG] ✗ ${o} NOT FOUND`)})),console.log("[DIAG] ===================\n")},DiagnosticScript.prototype.findAllScripts=function(o,e){o.script&&e.push(o.script),o.children.forEach((o=>this.findAllScripts(o,e)))},DiagnosticScript.prototype.destroy=function(){this.interval&&clearInterval(this.interval)};var NpcManager=pc.createScript("npcManager");NpcManager.attributes.add("npcDefinitions",{type:"json",schema:[{name:"id",type:"string",default:"npc_1"},{name:"name",type:"string",default:"Lab Assistant"},{name:"sceneId",type:"string",default:"medical_lab"},{name:"position",type:"vec3",default:[0,0,0]},{name:"color",type:"rgb",default:[.2,.4,.8]},{name:"dialogue",type:"string",default:"Hello! Need any help with the equipment?"},{name:"role",type:"string",default:"assistant"}],array:!0,title:"NPC Definitions"}),NpcManager.prototype.initialize=function(){console.log("=== NPC MANAGER INITIALIZED ==="),this.spawnedNpcs=new Map,this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this),this.app.on("npc:interact",this.onNpcInteract,this),this.npcDefinitions&&0!==this.npcDefinitions.length||this.setupDefaultNpcs(),console.log(`[NPCs] ${this.npcDefinitions.length} NPCs defined`)},NpcManager.prototype.setupDefaultNpcs=function(){this.npcDefinitions=[{id:"lab_assistant",name:"Dr. Sarah Chen",sceneId:"medical_lab",position:new pc.Vec3(-4,0,-8),color:new pc.Color(.2,.3,.6),dialogue:"Welcome to the lab! The centrifuge is running samples from this morning.",role:"scientist"},{id:"lab_tech",name:"Tech Johnson",sceneId:"medical_lab",position:new pc.Vec3(4,0,-8),color:new pc.Color(.6,.3,.2),dialogue:"Be careful with the microscope - it's calibrated for nanoscale imaging.",role:"technician"},{id:"alien_ambassador",name:"Zyx-9",sceneId:"scifi_env",position:new pc.Vec3(-3,0,-3),color:new pc.Color(.2,.8,.4),dialogue:"Greetings, human. The hologram contains star maps from my homeworld.",role:"alien"},{id:"security_officer",name:"Officer Martinez",sceneId:"scifi_env",position:new pc.Vec3(5,0,-5),color:new pc.Color(.4,.4,.5),dialogue:"This sector is restricted. You'll need clearance to access the control panels.",role:"security"}]},NpcManager.prototype.onSceneLoaded=function(e,t){console.log(`[NPCs] Scene loaded: ${e.id}`),this.clearNpcs(),setTimeout((()=>{this.spawnNpcsForScene(e.id)}),500)},NpcManager.prototype.spawnNpcsForScene=function(e){const t=this.npcDefinitions.filter((t=>{const n=t.sceneId.toLowerCase(),o=e.toLowerCase();return n===o||"medical_lab"===n&&o.includes("medical")||"scifi_env"===n&&o.includes("scifi")}));console.log(`[NPCs] Spawning ${t.length} NPCs for scene ${e}`),t.forEach((e=>{this.spawnNpc(e)}))},NpcManager.prototype.spawnNpc=function(e){console.log(`[NPCs] Spawning ${e.name} at ${e.position.x}, ${e.position.z}`);const t=new pc.Entity(e.id);t.addComponent("render",{type:"capsule"}),t.setLocalScale(.8,2,.8);const n=new pc.StandardMaterial;n.diffuse.set(e.color.r,e.color.g,e.color.b),n.update(),t.render.material=n,t.addComponent("collision",{type:"capsule",radius:.4,height:2}),t.addComponent("rigidbody",{type:"kinematic"}),t.setPosition(e.position.x,e.position.y+1,e.position.z),this.addNameTag(t,e.name),this.addNpcBehavior(t,e),t.tags.add("npc"),t.tags.add("interactive"),t.tags.add(`role_${e.role}`),t.npcData=e;const o=this.app.root.findByName("DynamicSceneRoot");o?o.addChild(t):this.app.root.addChild(t),this.spawnedNpcs.set(e.id,t)},NpcManager.prototype.addNameTag=function(e,t){const n=new pc.Entity("NameTag");n.addComponent("element",{type:"text",text:t,fontSize:16,color:new pc.Color(1,1,1),alignment:new pc.Vec2(.5,.5),anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:200,height:30}),n.setLocalPosition(0,1.5,0),n.setLocalScale(.01,.01,.01);const o=this.app.root.findByName("DescriptionText");o&&o.element&&(o.element.font&&(n.element.font=o.element.font),o.element.fontAsset&&(n.element.fontAsset=o.element.fontAsset)),n.addComponent("script");const i=pc.createScript("npcBillboard");i.prototype.update=function(){const e=this.app.root.findByName("SurgeonCamera");e&&(this.entity.lookAt(e.getPosition()),this.entity.rotate(0,180,0))},pc.registerScript(i,"npcBillboard"),n.script.create("npcBillboard"),e.addChild(n)},NpcManager.prototype.addNpcBehavior=function(e,t){e.addComponent("script");const n=pc.createScript("npcBehavior_"+t.id);n.prototype.initialize=function(){this.npcData=t,this.originalPos=this.entity.getPosition().clone(),this.time=Math.random()*Math.PI*2,this.player=null,this.state="idle",this.lookAtTimer=0},n.prototype.update=function(e){if(this.time+=e,!this.player)return void(this.player=this.app.root.findByName("SurgeonCamera"));const t=this.player.getPosition(),n=this.entity.getPosition(),o=t.distance(n);switch(this.state){case"idle":const i=.1*Math.sin(.5*this.time),a=.1*Math.cos(.7*this.time);this.entity.setPosition(this.originalPos.x+i,this.originalPos.y,this.originalPos.z+a),o<5&&(this.state="turning");break;case"turning":const c=new pc.Vec3(t.x,n.y,t.z);this.entity.lookAt(c),this.lookAtTimer+=e,this.lookAtTimer>.5&&(this.state="talking",this.lookAtTimer=0),o>6&&(this.state="idle",this.lookAtTimer=0);break;case"talking":const s=new pc.Vec3(t.x,n.y,t.z);this.entity.lookAt(s);const p=.02*Math.sin(3*this.time);this.entity.translateLocal(0,p,0),o>6&&(this.state="idle")}},pc.registerScript(n,"npcBehavior_"+t.id),e.script.create("npcBehavior_"+t.id)},NpcManager.prototype.onNpcInteract=function(e){const t=this.spawnedNpcs.get(e);if(!t)return;const n=t.npcData;console.log(`[NPCs] Interaction with ${n.name}`),this.showNpcDialogue(n),this.app.fire("story:npcInteraction",{npcId:n.id,npcName:n.name,role:n.role,dialogue:n.dialogue})},NpcManager.prototype.showNpcDialogue=function(e){console.log("[NPCs] Showing dialogue for:",e.name);const t=this.app.root.findByName("DialoguePanel");t&&t.destroy();let n=this.app.root.findByName("ObjectivesUIScreen");n||(n=this.app.root.findByName("UIScreen")),n||(n=new pc.Entity("NPCUIScreen"),n.addComponent("screen",{referenceResolution:new pc.Vec2(1920,1080),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),this.app.root.addChild(n));const o=new pc.Entity("DialoguePanel");o.addComponent("element",{type:"image",anchor:new pc.Vec4(.5,.15,.5,.15),pivot:new pc.Vec2(.5,.5),width:700,height:180,color:new pc.Color(.05,.05,.1),opacity:.95}),n.addChild(o);const i=new pc.Entity("DialogueBorder");i.addComponent("element",{type:"image",anchor:new pc.Vec4(0,0,1,1),pivot:new pc.Vec2(.5,.5),margin:new pc.Vec4(-2,-2,-2,-2),color:new pc.Color(1,.8,0),opacity:.3}),o.addChild(i);const a=new pc.Entity("DialogueName");a.addComponent("element",{type:"text",anchor:new pc.Vec4(.05,.85,.95,.95),pivot:new pc.Vec2(0,1),fontSize:22,text:e.name,color:new pc.Color(1,.8,0),autoWidth:!1,wrapLines:!1,alignment:new pc.Vec2(0,.5)}),o.addChild(a);const c=new pc.Entity("DialogueText");c.addComponent("element",{type:"text",anchor:new pc.Vec4(.05,.1,.95,.75),pivot:new pc.Vec2(0,1),fontSize:18,text:e.dialogue,color:new pc.Color(1,1,1),autoWidth:!1,wrapLines:!0,alignment:new pc.Vec2(0,1)}),o.addChild(c);const s=new pc.Entity("ContinueHint");s.addComponent("element",{type:"text",anchor:new pc.Vec4(.95,.05,.95,.05),pivot:new pc.Vec2(1,0),fontSize:14,text:"[Space to continue]",color:new pc.Color(.7,.7,.7),alignment:new pc.Vec2(1,.5)}),o.addChild(s);const p=this.app.root.findByName("DescriptionText");p&&p.element&&[a,c,s].forEach((e=>{p.element.font&&(e.element.font=p.element.font),p.element.fontAsset&&(e.element.fontAsset=p.element.fontAsset)})),o.element.opacity=0;let r=0;const l=setInterval((()=>{r+=.1,r>=.95&&(r=.95,clearInterval(l)),o.element.opacity=r}),16),removeDialogue=()=>{const e=setInterval((()=>{r-=.1,r<=0?(clearInterval(e),o&&!o._destroyed&&o.destroy()):o.element.opacity=r}),16)},d=setTimeout(removeDialogue,7e3),onKeyDown=e=>{e.key===pc.KEY_SPACE&&(clearTimeout(d),removeDialogue(),this.app.keyboard.off(pc.EVENT_KEYDOWN,onKeyDown))};this.app.keyboard.on(pc.EVENT_KEYDOWN,onKeyDown)},NpcManager.prototype.clearNpcs=function(){this.spawnedNpcs.forEach((e=>{e&&!e._destroyed&&e.destroy()})),this.spawnedNpcs.clear()},NpcManager.prototype.getNpc=function(e){return this.spawnedNpcs.get(e)},NpcManager.prototype.moveNpc=function(e,t){const n=this.spawnedNpcs.get(e);n&&n.rigidbody&&n.rigidbody.teleport(t)},NpcManager.prototype.setNpcDialogue=function(e,t){const n=this.spawnedNpcs.get(e);n&&n.npcData&&(n.npcData.dialogue=t)};var InventoryManager=pc.createScript("inventoryManager");InventoryManager.attributes.add("maxSlots",{type:"number",default:12,title:"Max Inventory Slots"}),InventoryManager.attributes.add("startingItems",{type:"json",schema:[{name:"id",type:"string",default:"item_1"},{name:"name",type:"string",default:"Health Potion"},{name:"description",type:"string",default:"Restores 50 HP"},{name:"icon",type:"string",default:"❤️"},{name:"quantity",type:"number",default:1},{name:"type",type:"string",default:"consumable"}],array:!0,title:"Starting Items"}),InventoryManager.prototype.initialize=function(){console.log("=== INVENTORY MANAGER INITIALIZED ==="),this.inventory=[],this.isOpen=!1,this.stats={health:100,maxHealth:100,energy:100,maxEnergy:100,experience:0,level:1,credits:1e3},this.createInventoryUI(),this.createStatsUI(),this.startingItems&&0!==this.startingItems.length||this.setupDefaultItems(),this.startingItems.forEach((t=>{this.addItem(t)})),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.app.on("item:pickup",this.onItemPickup,this),this.app.on("item:use",this.onItemUse,this),console.log("Press I to toggle inventory"),console.log("Press U to toggle stats"),this.inventoryPanel.enabled=!1,this.statsPanel.enabled=!1,this.updateStatsDisplay()},InventoryManager.prototype.setupDefaultItems=function(){this.startingItems=[{id:"health_potion",name:"Health Potion",description:"Restores 50 HP",icon:"🧪",quantity:3,type:"consumable"},{id:"keycard_red",name:"Red Keycard",description:"Opens red security doors",icon:"🔑",quantity:1,type:"key"},{id:"scanner",name:"Data Scanner",description:"Analyzes unknown objects",icon:"📟",quantity:1,type:"tool"}]},InventoryManager.prototype.createInventoryUI=function(){let t=this.app.root.findByName("InventoryUIScreen");t||(t=new pc.Entity("InventoryUIScreen"),t.addComponent("screen",{referenceResolution:new pc.Vec2(1920,1080),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),this.app.root.addChild(t)),this.inventoryPanel=new pc.Entity("InventoryPanel"),this.inventoryPanel.addComponent("element",{type:"image",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:400,height:500,color:new pc.Color(0,0,0),opacity:.9}),t.addChild(this.inventoryPanel);const e=new pc.Entity("InventoryTitle");e.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.95,.5,.95),pivot:new pc.Vec2(.5,.5),fontSize:24,text:"INVENTORY",color:new pc.Color(1,.8,0),alignment:new pc.Vec2(.5,.5)}),this.inventoryPanel.addChild(e),this.creditsText=new pc.Entity("CreditsText"),this.creditsText.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.85,.5,.85),pivot:new pc.Vec2(.5,.5),fontSize:18,text:"Credits: 1000",color:new pc.Color(.8,1,.8),alignment:new pc.Vec2(.5,.5)}),this.inventoryPanel.addChild(this.creditsText),this.itemGrid=new pc.Entity("ItemGrid"),this.itemGrid.addComponent("element",{type:"group",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:360,height:360}),this.inventoryPanel.addChild(this.itemGrid),this.slots=[];for(let t=0;t<this.maxSlots;t++){const e=Math.floor(t/4),n=t%4,o=this.createInventorySlot(t),i=90*n-135,s=90*(Math.ceil(this.maxSlots/4)-1)/2-90*e;o.setLocalPosition(i,s,0),this.itemGrid.addChild(o),this.slots.push(o)}this.itemDescription=new pc.Entity("ItemDescription"),this.itemDescription.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.05,.5,.05),pivot:new pc.Vec2(.5,.5),fontSize:14,text:"Click an item to view details",color:new pc.Color(.8,.8,.8),alignment:new pc.Vec2(.5,.5),wrapLines:!0,width:350}),this.inventoryPanel.addChild(this.itemDescription),this.copyFonts([e,this.creditsText,this.itemDescription])},InventoryManager.prototype.createInventorySlot=function(t){const e=new pc.Entity("Slot_"+t);e.addComponent("element",{type:"image",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:80,height:80,color:new pc.Color(.2,.2,.3),opacity:.8});const n=new pc.Entity("SlotIcon");n.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),fontSize:36,text:"",color:new pc.Color(1,1,1),alignment:new pc.Vec2(.5,.5)}),e.addChild(n);const o=new pc.Entity("SlotQuantity");return o.addComponent("element",{type:"text",anchor:new pc.Vec4(.8,.2,.8,.2),pivot:new pc.Vec2(.5,.5),fontSize:14,text:"",color:new pc.Color(1,1,0),alignment:new pc.Vec2(.5,.5)}),e.addChild(o),e.addComponent("button"),e.button.on("click",(()=>{this.onSlotClick(t)})),this.copyFonts([n,o]),e},InventoryManager.prototype.createStatsUI=function(){this.statsPanel=new pc.Entity("StatsPanel"),this.statsPanel.addComponent("element",{type:"image",anchor:new pc.Vec4(.02,.98,.02,.98),pivot:new pc.Vec2(0,1),width:250,height:200,color:new pc.Color(0,0,0),opacity:.7});this.app.root.findByName("InventoryUIScreen").addChild(this.statsPanel);const t=new pc.Entity("StatsTitle");t.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.9,.5,.9),pivot:new pc.Vec2(.5,.5),fontSize:18,text:"STATS",color:new pc.Color(1,.8,0),alignment:new pc.Vec2(.5,.5)}),this.statsPanel.addChild(t);this.statDisplays={},["Health","Energy","Level","Experience"].forEach(((t,e)=>{const n=new pc.Entity(t+"Row");n.addComponent("element",{type:"text",anchor:new pc.Vec4(.1,.7-.15*e,.1,.7-.15*e),pivot:new pc.Vec2(0,.5),fontSize:14,text:t+": ",color:new pc.Color(1,1,1),alignment:new pc.Vec2(0,.5)}),this.statsPanel.addChild(n),this.statDisplays[t.toLowerCase()]=n})),this.copyFonts([t,...Object.values(this.statDisplays)])},InventoryManager.prototype.copyFonts=function(t){const e=this.app.root.findByName("DescriptionText");e&&e.element&&t.forEach((t=>{t&&t.element&&(e.element.font&&(t.element.font=e.element.font),e.element.fontAsset&&(t.element.fontAsset=e.element.fontAsset))}))},InventoryManager.prototype.onKeyDown=function(t){switch(t.key){case pc.KEY_I:this.toggleInventory();break;case pc.KEY_U:this.toggleStats();break;case pc.KEY_H:console.log("[Inventory] Debug: Adding test item"),this.addItem({id:"debug_item",name:"Debug Item",description:"Test item added via hotkey",icon:"🎯",type:"consumable",quantity:1})}},InventoryManager.prototype.toggleInventory=function(){this.isOpen=!this.isOpen,this.inventoryPanel.enabled=this.isOpen,this.isOpen?(this.refreshInventoryDisplay(),this.app.fire("ui:opened","inventory")):this.app.fire("ui:closed","inventory")},InventoryManager.prototype.toggleStats=function(){this.statsPanel.enabled=!this.statsPanel.enabled},InventoryManager.prototype.refreshInventoryDisplay=function(){this.creditsText.element.text=`Credits: ${this.stats.credits}`,this.slots.forEach(((t,e)=>{const n=t.findByName("SlotIcon"),o=t.findByName("SlotQuantity");if(e<this.inventory.length){const i=this.inventory[e];n.element.text=i.icon,o.element.text=i.quantity>1?i.quantity.toString():"",t.element.color.set(.3,.3,.4)}else n.element.text="",o.element.text="",t.element.color.set(.2,.2,.3)}))},InventoryManager.prototype.updateStatsDisplay=function(){this.statDisplays.health&&(this.statDisplays.health.element.text=`Health: ${this.stats.health}/${this.stats.maxHealth}`),this.statDisplays.energy&&(this.statDisplays.energy.element.text=`Energy: ${this.stats.energy}/${this.stats.maxEnergy}`),this.statDisplays.level&&(this.statDisplays.level.element.text=`Level: ${this.stats.level}`),this.statDisplays.experience&&(this.statDisplays.experience.element.text=`Experience: ${this.stats.experience}`)},InventoryManager.prototype.onSlotClick=function(t){if(t<this.inventory.length){const e=this.inventory[t];this.itemDescription.element.text=`${e.name}\n${e.description}`,this.slots.forEach(((e,n)=>{n===t?e.element.color.set(.4,.4,.6):n<this.inventory.length?e.element.color.set(.3,.3,.4):e.element.color.set(.2,.2,.3)}))}},InventoryManager.prototype.addItem=function(t){if(this.inventory.length>=this.maxSlots)return console.log("[Inventory] Full! Cannot add:",t.name),!1;const e=this.inventory.find((e=>e.id===t.id));return e&&"consumable"===t.type?e.quantity+=t.quantity||1:this.inventory.push({...t,quantity:t.quantity||1}),console.log(`[Inventory] Added: ${t.name}`),this.refreshInventoryDisplay(),!0},InventoryManager.prototype.removeItem=function(t,e=1){const n=this.inventory.findIndex((e=>e.id===t));if(-1===n)return!1;const o=this.inventory[n];return o.quantity-=e,o.quantity<=0&&this.inventory.splice(n,1),this.refreshInventoryDisplay(),!0},InventoryManager.prototype.hasItem=function(t){return this.inventory.some((e=>e.id===t))},InventoryManager.prototype.modifyStat=function(t,e){void 0!==this.stats[t]&&(this.stats[t]+=e,"health"===t?this.stats.health=Math.max(0,Math.min(this.stats.health,this.stats.maxHealth)):"energy"===t&&(this.stats.energy=Math.max(0,Math.min(this.stats.energy,this.stats.maxEnergy))),this.updateStatsDisplay(),this.app.fire("stat:changed",{stat:t,value:this.stats[t]}))},InventoryManager.prototype.onItemPickup=function(t){console.log("[Inventory] Received item pickup event:",t);this.addItem(t)?console.log("[Inventory] Item added successfully"):console.log("[Inventory] Failed to add item (inventory full?)")},InventoryManager.prototype.onItemUse=function(t){const e=this.inventory.find((e=>e.id===t));if(e)switch(e.type){case"consumable":"health_potion"===e.id&&(this.modifyStat("health",50),this.removeItem(t,1),console.log("[Inventory] Used health potion"));break;case"key":console.log(`[Inventory] Using key: ${e.name}`);break;case"tool":console.log(`[Inventory] Using tool: ${e.name}`)}};var ItemPickupSystem=pc.createScript("itemPickupSystem");ItemPickupSystem.prototype.initialize=function(){console.log("=== ITEM PICKUP SYSTEM ==="),console.log("Press P to spawn a random item"),console.log("Look at items and press F to pick them up"),console.log("========================="),this.itemTemplates=[{id:"energy_cell",name:"Energy Cell",description:"Restores 25 energy",icon:"🔋",type:"consumable",color:new pc.Color(.2,.8,1)},{id:"data_chip",name:"Data Chip",description:"Contains encrypted information",icon:"💾",type:"quest",color:new pc.Color(.8,.8,.2)},{id:"blue_keycard",name:"Blue Keycard",description:"Opens blue security doors",icon:"🔑",type:"key",color:new pc.Color(.2,.4,1)},{id:"medkit",name:"Medkit",description:"Fully restores health",icon:"🏥",type:"consumable",color:new pc.Color(1,.2,.2)},{id:"credits_small",name:"Credit Chip",description:"50 Credits",icon:"💰",type:"currency",value:50,color:new pc.Color(1,.8,.2)}],this.spawnedItems=[],this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.app.on("dataset:sceneLoaded",this.onSceneLoaded,this)},ItemPickupSystem.prototype.onKeyDown=function(t){t.key===pc.KEY_P&&this.spawnRandomItem()},ItemPickupSystem.prototype.onSceneLoaded=function(t,e){console.log("[Items] Spawning items for scene:",t.id),this.clearItems(),setTimeout((()=>{"medical_lab"===t.id||t.id.includes("medical")?(this.spawnItem("medkit",new pc.Vec3(0,1,-12)),this.spawnItem("data_chip",new pc.Vec3(-8,1,-10))):("scifi_env"===t.id||t.id.includes("scifi"))&&(this.spawnItem("energy_cell",new pc.Vec3(-5,1,0)),this.spawnItem("blue_keycard",new pc.Vec3(5,1,-5)),this.spawnItem("credits_small",new pc.Vec3(0,1,5)))}),1e3)},ItemPickupSystem.prototype.spawnRandomItem=function(){const t=this.app.root.findByName("SurgeonCamera");if(!t)return;const e=t.getPosition(),i=t.forward,o=new pc.Vec3(e.x+3*i.x,1,e.z+3*i.z),n=this.itemTemplates[Math.floor(Math.random()*this.itemTemplates.length)];this.spawnItem(n.id,o)},ItemPickupSystem.prototype.spawnItem=function(t,e){const i=this.itemTemplates.find((e=>e.id===t));if(!i)return;console.log(`[Items] Spawning ${i.name} at`,e);const o=new pc.Entity("Item_"+i.id);o.addComponent("render",{type:"box"}),o.setLocalScale(.4,.4,.4);const n=new pc.StandardMaterial;n.diffuse.copy(i.color),n.emissive.copy(i.color),n.emissiveIntensity=.3,n.update(),o.render.material=n,o.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(.2,.2,.2)}),o.addComponent("rigidbody",{type:"static"}),o.setPosition(e),o.addComponent("script");const a=pc.createScript("itemFloat");a.prototype.initialize=function(){this.time=0,this.baseY=this.entity.getPosition().y},a.prototype.update=function(t){this.time+=t;const e=this.baseY+.1*Math.sin(2*this.time);this.entity.rotate(0,60*t,0),this.entity.setPosition(this.entity.getPosition().x,e,this.entity.getPosition().z)},pc.registerScript(a,"itemFloat"),o.script.create("itemFloat");const s=new pc.Entity("ItemIcon");s.addComponent("element",{type:"text",text:i.icon,fontSize:24,color:new pc.Color(1,1,1),alignment:new pc.Vec2(.5,.5)}),s.setLocalPosition(0,.5,0),s.setLocalScale(.02,.02,.02),s.addComponent("script");const c=pc.createScript("itemBillboard");c.prototype.update=function(){const t=this.app.root.findByName("SurgeonCamera");t&&(this.entity.lookAt(t.getPosition()),this.entity.rotate(0,180,0))},pc.registerScript(c,"itemBillboard"),s.script.create("itemBillboard"),o.addChild(s),o.tags.add("item"),o.tags.add("interactive"),o.itemData=i;const p=this.app.root.findByName("DynamicSceneRoot");p?p.addChild(o):this.app.root.addChild(o),this.spawnedItems.push(o)},ItemPickupSystem.prototype.clearItems=function(){this.spawnedItems.forEach((t=>{t&&!t._destroyed&&t.destroy()})),this.spawnedItems=[]},ItemPickupSystem.prototype.postInitialize=function(){const t=this,e=this.app.root.findByName("SurgeonCamera");if(!e||!e.script||!e.script.interactionController)return console.log("[Items] Waiting for interaction controller..."),void setTimeout((()=>this.postInitialize()),1e3);const i=e.script.interactionController,o=i.interactWith.bind(i);i.interactWith=function(e){if(e.tags.has("item")&&e.itemData){console.log("[Items] Picking up:",e.itemData.name);const i={id:e.itemData.id,name:e.itemData.name,description:e.itemData.description,icon:e.itemData.icon,type:e.itemData.type,quantity:e.itemData.quantity||1};if(t.app.fire("item:pickup",i),"currency"===e.itemData.type&&e.itemData.value){const i=t.app.root.findByName("GameManager");if(i&&i.script&&i.script.inventoryManager)i.script.inventoryManager.modifyStat("credits",e.itemData.value),console.log(`[Items] Added ${e.itemData.value} credits`);else{console.warn("[Items] Inventory manager not found on GameManager");const i=t.app.root.findComponent("inventoryManager");i&&i.modifyStat("credits",e.itemData.value)}}const o=t.spawnedItems.indexOf(e);o>-1&&t.spawnedItems.splice(o,1),e.destroy()}else o(e)},console.log("[Items] Interaction controller extended for item pickups")};var MissionTestValidator=pc.createScript("missionTestValidator");MissionTestValidator.prototype.initialize=function(){console.log("=== MISSION TEST VALIDATOR ==="),console.log("Press V to run validation tests"),console.log("Press N to test NPC spawning"),console.log("Press T to test objective progression"),console.log("============================="),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),setTimeout((()=>{this.runValidation()}),3e3)},MissionTestValidator.prototype.onKeyDown=function(e){switch(e.key){case pc.KEY_V:this.runValidation();break;case pc.KEY_N:this.testNPCSystem();break;case pc.KEY_T:this.testObjectiveProgression()}},MissionTestValidator.prototype.runValidation=function(){console.log("\n=== RUNNING VALIDATION TESTS ===");var e={passed:0,failed:0,tests:[]};this.runTest(e,"Game Manager exists",(()=>!!this.app.root.findByName("GameManager"))),this.runTest(e,"Objective Manager initialized",(()=>{var e=this.app.root.findByName("GameManager");return e&&e.script&&e.script.objectiveManager})),this.runTest(e,"NPC Manager exists",(()=>!!this.app.root.findComponent("script",(e=>e.has("npcManager"))))),this.runTest(e,"Mission Helper available",(()=>"undefined"!=typeof MissionHelper)),this.runTest(e,"Objective HUD created",(()=>!!this.app.root.findByName("ObjectivesHUD"))),this.runTest(e,"Act tracking functional",(()=>{var e=this.app.root.findByName("GameManager");if(e&&e.script&&e.script.objectiveManager){var t=e.script.objectiveManager;return t.hasOwnProperty("currentAct")&&t.hasOwnProperty("totalActs")}return!1})),this.runTest(e,"NPCs properly tagged",(()=>{var e=this.app.root.findByTag("npc");return 0===e.length||e.every((e=>e.tags.has("npc")&&(e.tags.has("interactive")||e.collision)&&e.npcData))})),this.runTest(e,"Mission entities tagged",(()=>this.app.root.findByTag("mission_entity").length>0||!this.isMissionActive())),this.runTest(e,"UI Screen exists",(()=>!!this.app.root.findByName("UIScreen"))),this.runTest(e,"Fonts configured",(()=>{var e=this.app.root.findByName("DescriptionText");return e&&e.element&&(e.element.font||e.element.fontAsset)})),console.log("\n=== VALIDATION RESULTS ==="),console.log(`Total Tests: ${e.tests.length}`),console.log(`Passed: ${e.passed} ✓`),console.log(`Failed: ${e.failed} ✗`),console.log("\nDetails:"),e.tests.forEach((e=>{console.log(`${e.passed?"✓":"✗"} ${e.name}`),!e.passed&&e.error&&console.log(`  └─ ${e.error}`)})),console.log("========================\n"),0===e.failed?console.log("🎉 ALL TESTS PASSED! Mission system is properly configured."):(console.log("⚠️  Some tests failed. Check the details above."),this.suggestFixes(e))},MissionTestValidator.prototype.runTest=function(e,t,s){try{var o=s();e.tests.push({name:t,passed:o}),o?e.passed++:e.failed++}catch(s){e.tests.push({name:t,passed:!1,error:s.message}),e.failed++}},MissionTestValidator.prototype.isMissionActive=function(){return["RecordingStudioMission","ResearchFacilityMission","GeneratorFacilityMission"].some((e=>!!this.app.root.findByName(e)))},MissionTestValidator.prototype.suggestFixes=function(e){console.log("\n=== SUGGESTED FIXES ==="),e.tests.forEach((e=>{if(!e.passed)switch(e.name){case"Game Manager exists":console.log("• Add GameManager entity to your scene");break;case"Objective Manager initialized":console.log("• Add objectiveManager script to GameManager"),console.log("• Ensure objectiveManager.js is loaded");break;case"NPC Manager exists":console.log("• Add npcManager script to GameManager or another entity");break;case"Mission Helper available":console.log("• Ensure missionHelper.js is loaded in your project");break;case"Objective HUD created":console.log("• Check that objective manager hudEnabled is true");break;case"Act tracking functional":console.log("• Update to the fixed objectiveManager.js");break;case"NPCs properly tagged":console.log('• Ensure all NPCs have "npc" and "interactive" tags'),console.log("• Add npcData to NPC entities");break;case"UI Screen exists":console.log("• Ensure UI is created in your scene scaffolding");break;case"Fonts configured":console.log("• Check that story UI has proper fonts set")}})),console.log("=====================\n")},MissionTestValidator.prototype.testNPCSystem=function(){if(console.log("\n=== TESTING NPC SYSTEM ==="),"undefined"!=typeof MissionHelper){var e=MissionHelper.spawnNPC(this,{id:"test_npc",name:"Test NPC Charlie",dialogue:"Hello! I am a test NPC to verify the system works.",role:"tester",position:new pc.Vec3(0,1,-3),color:new pc.Color(1,0,1)});console.log("Test NPC spawned at (0, 1, -3)"),console.log("Try interacting with it using F"),setTimeout((()=>{e&&!e._destroyed&&(e.destroy(),console.log("Test NPC removed"))}),1e4)}else console.error("MissionHelper not available!");console.log("========================\n")},MissionTestValidator.prototype.testObjectiveProgression=function(){console.log("\n=== TESTING OBJECTIVE PROGRESSION ===");"undefined"!=typeof MissionHelper?(MissionHelper.setActObjectives(this,1,"Test Act",{id:"test_objective",title:"System Validation Test",description:"Testing objective system",type:"sequential",tasks:[{id:"test_time",text:"Wait 3 seconds",hint:"Just wait...",condition:{type:"time",value:3},completed:!1},{id:"test_interact",text:"Interact with any object",hint:"Press F on something",condition:{type:"interaction",target:"any"},completed:!1},{id:"test_ui",text:"Toggle the UI",hint:"Press TAB",condition:{type:"ui_toggle"},completed:!1}]}),console.log("Test objectives loaded - check the HUD (press O if hidden)")):console.error("MissionHelper not available!");var e=null,t=this.getObjectiveManager();t&&(e=t.checkAllTasks,t.checkAllTasks=function(s){"interaction"===s.type&&(s.target="any"),e.call(t,s)},setTimeout((()=>{t&&e&&(t.checkAllTasks=e,console.log("Test objectives removed"))}),3e4)),console.log("========================\n")},MissionTestValidator.prototype.getObjectiveManager=function(){var e=this.app.root.findByName("GameManager");return e&&e.script&&e.script.objectiveManager?e.script.objectiveManager:null};var MissionHelper=pc.createScript("missionHelper");MissionHelper.initializeMission=function(e,t){console.log(`[MissionHelper] Initializing mission: ${t.name}`),e.currentAct=0,e.totalActs=t.totalActs||1,e.actNames=t.actNames||[],e.missionComplete=!1,e.initializationComplete=!1,MissionHelper.ensureObjectiveManager(),setTimeout((()=>{e.app.clearRoom&&(console.log("[MissionHelper] Clearing existing room..."),e.app.clearRoom()),setTimeout((()=>{e.initializationComplete=!0,e.app.fire("mission:initialized",t.name)}),500)}),100)},MissionHelper.ensureObjectiveManager=function(){const e=pc.app.root.findByName("GameManager");if(!e)return console.error("[MissionHelper] GameManager not found!"),null;if(!e.script||!e.script.objectiveManager){if(console.log("[MissionHelper] Adding objective manager to GameManager..."),e.script||e.addComponent("script"),!pc.ScriptRegistry.get("objectiveManager"))return console.error("[MissionHelper] ObjectiveManager script not found in registry!"),null;e.script.create("objectiveManager")}return e.script.objectiveManager},MissionHelper.setActObjectives=function(e,t,n,o){console.log(`[MissionHelper] Setting objectives for Act ${t}: ${n}`);const i=MissionHelper.ensureObjectiveManager();i?(e.app.fire("mission:actChange",{currentAct:t,totalActs:e.totalActs,actName:n}),e.app.fire("mission:objectives",{currentAct:t,totalActs:e.totalActs,actNames:e.actNames,objective:o}),i.setObjective&&(i.currentAct=t,i.totalActs=e.totalActs,i.actNames=e.actNames,i.setObjective(o))):setTimeout((()=>{MissionHelper.setActObjectives(e,t,n,o)}),500)},MissionHelper.spawnNPC=function(e,t){console.log(`[MissionHelper] Spawning NPC: ${t.name}`);const n=e.app.root.findComponent("script",(e=>e.has("npcManager")))?.entity.script.npcManager,o=new pc.Entity(t.id);o.tags.add("npc"),o.tags.add("interactive"),o.tags.add("mission_entity");const i=new pc.StandardMaterial;i.diffuse.copy(t.color||new pc.Color(.5,.5,.5)),i.update(),o.addComponent("render",{type:"capsule",material:i}),o.setLocalScale(.8,2,.8),o.setPosition(t.position.x,t.position.y||1,t.position.z),o.addComponent("collision",{type:"capsule",radius:.4,height:2}),o.addComponent("rigidbody",{type:"kinematic"}),o.npcData={id:t.id,name:t.name,dialogue:t.dialogue,role:t.role||"npc"};const s=new pc.Entity("NameTag");s.addComponent("element",{type:"text",text:t.name,fontSize:16,color:new pc.Color(1,1,1),alignment:new pc.Vec2(.5,.5),anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:300,height:30,autoWidth:!1,wrapLines:!1}),s.setLocalPosition(0,1.2,0),s.setLocalScale(.01,.01,.01);const c=e.app.root.findByName("DescriptionText");c&&c.element&&(c.element.font&&(s.element.font=c.element.font),c.element.fontAsset&&(s.element.fontAsset=c.element.fontAsset)),s.addComponent("script");const a=pc.createScript("npcBillboard_"+t.id);a.prototype.update=function(){const e=this.app.root.findByName("SurgeonCamera");e&&(this.entity.lookAt(e.getPosition()),this.entity.rotate(0,180,0))},pc.registerScript(a,"npcBillboard_"+t.id),s.script.create("npcBillboard_"+t.id),o.addChild(s);const r=new pc.Entity("HoverIndicator");r.addComponent("element",{type:"text",text:"[Press F to talk]",fontSize:12,color:new pc.Color(.8,.8,.8),alignment:new pc.Vec2(.5,.5),anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:200,height:20}),r.setLocalPosition(0,.8,0),r.setLocalScale(.01,.01,.01),r.enabled=!1,c&&c.element&&(c.element.font&&(r.element.font=c.element.font),c.element.fontAsset&&(r.element.fontAsset=c.element.fontAsset)),o.addChild(r),e.app.root.addChild(o),n&&n.spawnedNpcs?(n.spawnedNpcs.set(t.id,o),n.addNpcBehavior&&n.addNpcBehavior(o,o.npcData)):MissionHelper.addSimpleNPCBehavior(o,t),o.addComponent("script");const p=pc.createScript("npcHover_"+t.id);return p.prototype.initialize=function(){this.hoverIndicator=this.entity.findByName("HoverIndicator"),this.camera=null},p.prototype.update=function(e){if(!this.camera)return void(this.camera=this.app.root.findByName("SurgeonCamera"));const t=this.entity.getPosition().distance(this.camera.getPosition());this.hoverIndicator&&(this.hoverIndicator.enabled=t<5)},pc.registerScript(p,"npcHover_"+t.id),o.script.create("npcHover_"+t.id),o},MissionHelper.addSimpleNPCBehavior=function(e,t){e.addComponent("script");const n=pc.createScript("simpleBehavior_"+t.id);n.prototype.initialize=function(){this.player=null,this.time=0},n.prototype.update=function(e){this.time+=e;const t=.02*Math.sin(2*this.time);if(this.entity.translateLocal(0,t,0),this.player||(this.player=this.app.root.findByName("SurgeonCamera")),this.player){if(this.entity.getPosition().distance(this.player.getPosition())<5){const e=new pc.Vec3(this.player.getPosition().x,this.entity.getPosition().y,this.player.getPosition().z);this.entity.lookAt(e)}}},pc.registerScript(n,"simpleBehavior_"+t.id),e.script.create("simpleBehavior_"+t.id)},MissionHelper.completeTask=function(e,t){const n=MissionHelper.ensureObjectiveManager();if(!n||!n.currentObjective)return;const o=n.currentObjective.tasks.find((e=>e.id===t));if(o&&!o.completed){o.completed=!0,n.updateHUD&&n.updateHUD(!0);n.currentObjective.tasks.every((e=>e.completed))&&e.app.fire("objective:completed",n.currentObjective.id)}},MissionHelper.showMissionText=function(e,t,n,o){let i=e.app.root.findByName("MissionPanel");i&&i.destroy();let s=e.app.root.findByName("MissionUIScreen");s||(s=new pc.Entity("MissionUIScreen"),s.tags.add("mission_entity"),s.addComponent("screen",{referenceResolution:new pc.Vec2(1920,1080),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),e.app.root.addChild(s)),i=new pc.Entity("MissionPanel"),i.tags.add("mission_entity"),i.addComponent("element",{type:"image",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:700,height:450,color:new pc.Color(0,0,0),opacity:.9}),s.addChild(i);const c=new pc.Entity("MissionTitle");c.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.9,.5,.9),pivot:new pc.Vec2(.5,.5),fontSize:28,text:t||"MISSION UPDATE",color:new pc.Color(1,.8,0),alignment:new pc.Vec2(.5,.5)}),i.addChild(c);const a=new pc.Entity("MissionDesc");a.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.6,.5,.6),pivot:new pc.Vec2(.5,.5),fontSize:18,text:n,color:new pc.Color(1,1,1),autoWidth:!1,wrapLines:!0,width:650,alignment:new pc.Vec2(.5,.5)}),i.addChild(a),o.forEach(((t,n)=>{const o=new pc.Entity("MissionChoice"+n);o.addComponent("element",{type:"image",anchor:new pc.Vec4(.5,.25-.12*n,.5,.25-.12*n),pivot:new pc.Vec2(.5,.5),width:350,height:50,color:new pc.Color(.2,.2,.3),useInput:!0}),o.addComponent("button");const s=new pc.Entity("ButtonText");s.addComponent("element",{type:"text",anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),fontSize:20,text:t,color:new pc.Color(1,1,1),alignment:new pc.Vec2(.5,.5)}),o.addChild(s),o.button.on("click",(()=>{i.destroy(),e.app.fire("mission:choice",t)})),i.addChild(o)})),MissionHelper.copyFontsToElement(i)},MissionHelper.copyFontsToElement=function(e){const t=pc.app.root.findByName("DescriptionText");t&&t.element&&e.findComponents("element").forEach((e=>{e.type===pc.ELEMENTTYPE_TEXT&&(t.element.font&&(e.font=t.element.font),t.element.fontAsset&&(e.fontAsset=t.element.fontAsset))}))},MissionHelper.showHint=function(e,t,n=5e3){console.log("[Mission Hint] "+t);const o=e.app.root.findByName("HintText");o&&!o._destroyed&&o.destroy();const i=new pc.Entity("HintText");i.tags.add("mission_entity"),i.addComponent("element",{type:"text",text:t,fontSize:22,color:new pc.Color(1,1,.5),autoWidth:!1,wrapLines:!0,width:800,anchor:new pc.Vec4(.5,.88,.5,.88),pivot:new pc.Vec2(.5,.5),alignment:new pc.Vec2(.5,.5)});const s=e.app.root.findByName("UIScreen");if(s){s.addChild(i);const t=e.app.root.findByName("DescriptionText");t&&t.element&&(t.element.font&&(i.element.font=t.element.font),t.element.fontAsset&&(i.element.fontAsset=t.element.fontAsset)),setTimeout((()=>{i&&!i._destroyed&&i.destroy()}),n)}},MissionHelper.debugMissionState=function(e){console.log("\n=== MISSION STATE DEBUG ==="),console.log(`Mission initialized: ${e.initializationComplete}`),console.log(`Current Act: ${e.currentAct} of ${e.totalActs}`),e.actNames.length>0&&console.log("Act Names:",e.actNames),console.log(`Mission Complete: ${e.missionComplete}`);const t=MissionHelper.ensureObjectiveManager();if(t){if(console.log("Objective Manager: Found"),t.currentObjective){console.log(`Current Objective: ${t.currentObjective.title}`);const e=t.getCurrentProgress();e&&console.log(`Progress: ${e.completed}/${e.total} (${e.percentage.toFixed(0)}%)`)}}else console.log("Objective Manager: NOT FOUND");const n=e.app.root.findByTag("npc");console.log(`NPCs in scene: ${n.length}`),n.forEach((e=>{console.log(`- ${e.name} ${e.npcData?`(${e.npcData.name})`:""}`)})),console.log("=======================\n")};