@combos-fun/plugin-renderer-3d 0.1.13 → 0.1.14-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/plugin-renderer-3d.cjs.js +239 -12
- package/dist/plugin-renderer-3d.cjs.js.map +1 -1
- package/dist/plugin-renderer-3d.cjs.prod.js +1 -1
- package/dist/plugin-renderer-3d.d.ts +30 -7
- package/dist/plugin-renderer-3d.esm.js +238 -15
- package/dist/plugin-renderer-3d.esm.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("@combos-fun/engine"),o=require("three"),r=require("@combos-fun/inspector-decorator");const s="combosGameObjectId",n="combosTransform3D";function i(e){return!!e?.userData?.[n]}function a(e,t){e.traverse(e=>{e.userData[s]=t})}function c(e){let t=e;for(;t;){const e=t.userData?.[s];if("number"==typeof e)return e;t=t.parent}}function p(e){if(!e)return!0;const t=e.parent;return!t||t===e.scene}function d(e){return{positionX:e.positionX??0,positionY:e.positionY??0,positionZ:e.positionZ??0,rotationX:e.rotationX??0,rotationY:e.rotationY??0,rotationZ:e.rotationZ??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,scaleZ:e.scaleZ??1}}function h(e){const t=d(e);return[t.positionX,t.positionY,t.positionZ,t.rotationX,t.rotationY,t.rotationZ,t.scaleX,t.scaleY,t.scaleZ].join(",")}function l(e,t){const o=d(e);t.positionX=o.positionX,t.positionY=o.positionY,t.positionZ=o.positionZ,t.rotationX=o.rotationX,t.rotationY=o.rotationY,t.rotationZ=o.rotationZ,t.scaleX=o.scaleX,t.scaleY=o.scaleY,t.scaleZ=o.scaleZ}function m(e){const t=d(e);return 0===t.positionX&&0===t.positionY&&0===t.positionZ&&0===t.rotationX&&0===t.rotationY&&0===t.rotationZ&&1===t.scaleX&&1===t.scaleY&&1===t.scaleZ}function u(e,t){m(t)&&!m(e)&&l(e,t)}const g={none:o.NoToneMapping,aces:o.ACESFilmicToneMapping,linear:o.LinearToneMapping,reinhard:o.ReinhardToneMapping,cineon:o.CineonToneMapping},y=new o.Vector3,f=new o.Euler;class b{constructor(e){this.mixers=new Map,this.models=new Map,this.nodes=new Map,this.defaultLights=[];const{canvas:t,container:r,width:s,height:n,antialias:i=!0,backgroundColor:a=0,backgroundAlpha:c=1}=e;this.scene=new o.Scene,this.shadows=!!e.shadows,this.camera=new o.PerspectiveCamera(75,s/n,.1,1e3),this.camera.position.z=5,this.fallbackCamera=this.camera;const p={antialias:i};t&&(p.canvas=t),c<1&&(p.alpha=!0),this.renderer=new o.WebGLRenderer(p),this.renderer.setSize(s,n),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setClearColor(a,c),this.renderer.toneMapping=g[e.toneMapping??"aces"]??o.ACESFilmicToneMapping,this.renderer.toneMappingExposure=e.toneMappingExposure??1,this.shadows&&(this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=o.PCFSoftShadowMap),!t&&r&&r.appendChild(this.renderer.domElement);const d=new o.AmbientLight(16777215,e.ambientIntensity??.6);this.scene.add(d),this.defaultLights.push(d);const h=new o.DirectionalLight(16777215,e.directionalIntensity??.8);if(h.position.set(5,10,7.5),this.shadows&&(h.castShadow=!0,h.shadow.mapSize.set(1024,1024)),this.scene.add(h),this.defaultLights.push(h),!1!==e.hemisphereLight){const t="object"==typeof e.hemisphereLight?e.hemisphereLight:{},r=new o.HemisphereLight(t.skyColor??16777215,t.groundColor??4473924,t.intensity??.35);this.scene.add(r),this.defaultLights.push(r)}if(e.fog){const t="object"==typeof e.fog?e.fog:{};this.scene.fog=new o.Fog(t.color??a,t.near??8,t.far??40)}this.clock=new o.Clock}update(){const e=this.clock.getDelta();for(const t of this.mixers.values())t.update(e);this.renderer.render(this.scene,this.camera)}hasTransform3DRoot(e){return i(this.nodes.get(e))}applyModelShadows(e){this.shadows&&e.traverse(e=>{const t=e;t.isMesh&&(t.castShadow=!0,t.receiveShadow=!0)})}attachParsedModel(e,t,r,s){if(a(t,e),this.applyModelShadows(t),this.models.set(e,t),this.attachVisual(e,t,s),r&&r.length>0){const s=new o.AnimationMixer(t);this.mixers.set(e,s),t.userData.animations=r}return t}object3DFor(e){return this.nodes.get(e)}attachObject3D(e,t,o){const r=this.nodes.get(e);r&&r!==t&&(this.rehomeRegisteredChildren(r),r.parent?.remove(r)),this.nodes.set(e,t);const s=this.findParentNode(o);t.parent!==s&&s.add(t),o&&this.adoptChildGameObjects(o,t)}attachVisual(e,t,o){a(t,e);const r=this.nodes.get(e);i(r)&&r!==t?t.parent!==r&&r.add(t):this.attachObject3D(e,t,o)}detachVisual(e,t){const o=this.nodes.get(e);return i(o)&&o!==t?(t.parent?.remove(t),t):o===t?this.detachObject3D(e):(t.parent?.remove(t),t)}detachObject3D(e){const t=this.nodes.get(e);if(t)return this.rehomeRegisteredChildren(t),t.parent?.remove(t),this.nodes.delete(e),t}reparentGameObject(e){const t=this.nodes.get(e.id);if(!t)return;const o=this.findParentNode(e);t.parent!==o&&o.add(t)}findParentNode(e){if(!e||p(e))return this.scene;let t=e.parent;for(;t&&t!==e.scene;){const e=this.nodes.get(t.id);if(e)return e;t=t.parent}return this.scene}adoptChildGameObjects(e,t){const o=e.children;if(o)for(const e of o){if(!e)continue;const o=this.nodes.get(e.id);o&&o.parent!==t&&t.add(o)}}ensureTransformRoot(e,t){const r=this.nodes.get(e.id);if(i(r))return this.applyTransformPose(r,t),r;const s=new o.Group;if(s.name=e.name,s.userData[n]=!0,a(s,e.id),r&&r!==s){(function(e){const t=d(e);return 0===t.positionX&&0===t.positionY&&0===t.positionZ&&0===t.rotationX&&0===t.rotationY&&0===t.rotationZ&&1===t.scaleX&&1===t.scaleY&&1===t.scaleZ})(t)&&(t.positionX=r.position.x,t.positionY=r.position.y,t.positionZ=r.position.z,t.rotationX=r.rotation.x,t.rotationY=r.rotation.y,t.rotationZ=r.rotation.z,t.scaleX=r.scale.x,t.scaleY=r.scale.y,t.scaleZ=r.scale.z);(r.parent||this.scene).add(s),s.add(r),r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),this.nodes.set(e.id,s),this.adoptChildGameObjects(e,s)}else this.attachObject3D(e.id,s,e);return this.applyTransformPose(s,t),s}applyTransform3D(e,t){const o=this.ensureTransformRoot(e,t);return this.applyTransformPose(o,t),o.updateWorldMatrix(!0,!1),o.getWorldPosition(y),t.worldPositionX=y.x,t.worldPositionY=y.y,t.worldPositionZ=y.z,f.setFromRotationMatrix(o.matrixWorld),t.worldRotationX=f.x,t.worldRotationY=f.y,t.worldRotationZ=f.z,o}applyTransformPose(e,t){const o=d(t);e.position.set(o.positionX,o.positionY,o.positionZ),e.rotation.set(o.rotationX,o.rotationY,o.rotationZ),e.scale.set(o.scaleX,o.scaleY,o.scaleZ)}removeDefaultLights(){if(this.defaultLights.length){for(const e of this.defaultLights)e.parent?.remove(e),e.dispose?.();this.defaultLights=[]}}setActiveCamera(e){const t=this.camera;this.camera=e,t&&(e.aspect=t.aspect),e.updateProjectionMatrix()}restoreFallbackCamera(){this.camera!==this.fallbackCamera&&this.setActiveCamera(this.fallbackCamera)}rehomeRegisteredChildren(e){for(const t of[...e.children]){const e=t.userData?.[s];"number"==typeof e&&this.nodes.get(e)===t&&this.scene.add(t)}}playAnimation(e,t,o){const r=this.mixers.get(e),s=this.models.get(e);if(!r||!s)return;r.stopAllAction();const n=s.userData.animations;if(n&&n[t]){const e=r.clipAction(n[t]);e.timeScale=o,e.play()}}stopAnimation(e){const t=this.mixers.get(e);t&&t.stopAllAction()}removeModel(e){const t=this.models.get(e);t&&(this.detachVisual(e,t),t.traverse(e=>{const t=e;if(t.geometry&&t.geometry.dispose(),t.material){(Array.isArray(t.material)?t.material:[t.material]).forEach(e=>e.dispose())}}),this.models.delete(e));const o=this.mixers.get(e);o&&(o.stopAllAction(),this.mixers.delete(e))}resize(e,t){this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.fallbackCamera!==this.camera&&(this.fallbackCamera.aspect=e/t,this.fallbackCamera.updateProjectionMatrix()),this.renderer.setSize(e,t)}destroy(){for(const e of this.models.keys())this.removeModel(e);this.removeDefaultLights(),this.renderer.dispose(),this.renderer.domElement.remove(),this.nodes.clear(),this.scene=null,this.camera=null,this.fallbackCamera=null,this.renderer=null,this.clock=null}}class C{constructor({game:e,rendererSystem:t}){this.renderers=[],this.game=e,this.rendererSystem=t}register(...e){for(const t of e)t.game=this.game,t.rendererManager=this,t.threeContext=this.rendererSystem.threeContext,this.renderers.push(t)}componentChanged(e){for(const o of e)for(const e of this.renderers){const r=e.observerInfo[o.componentName];if(!r)continue;if(o.type===t.OBSERVER_TYPE.ADD||o.type===t.OBSERVER_TYPE.REMOVE){try{e.componentChanged(o)}catch(e){console.error(`gameObject: ${o.gameObject.name}, ${o.componentName} error.`,o,e)}continue}if(r.findIndex(e=>"string"==typeof e&&"string"==typeof o.prop?e===o.prop:JSON.stringify(e)===JSON.stringify(o.prop))>-1)try{e.componentChanged(o)}catch(e){console.error(`gameObject: ${o.gameObject?.name}, ${o.componentName} componentChanged error.`,o,e)}}}update(e){for(const t of e.components)for(const o of this.renderers){if(o.observerInfo[t.name])try{o.rendererUpdate(e)}catch(o){console.info(`gameObject: ${e.name}, ${t.name} update error`,o)}}}}class D extends t.Component{constructor(){super(...arguments),this.positionX=0,this.positionY=0,this.positionZ=0,this.rotationX=0,this.rotationY=0,this.rotationZ=0,this.scaleX=1,this.scaleY=1,this.scaleZ=1,this.worldPositionX=0,this.worldPositionY=0,this.worldPositionZ=0,this.worldRotationX=0,this.worldRotationY=0,this.worldRotationZ=0}static{this.componentName="Transform3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"positionX",description:"Local X position.",editor:"number-stepper"})],D.prototype,"positionX",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"positionY",description:"Local Y position.",editor:"number-stepper"})],D.prototype,"positionY",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"positionZ",description:"Local Z position.",editor:"number-stepper"})],D.prototype,"positionZ",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Transform3D",label:"rotationX",description:"Rotation around X in radians.",editor:"number-stepper"})],D.prototype,"rotationX",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Transform3D",label:"rotationY",description:"Rotation around Y in radians.",editor:"number-stepper"})],D.prototype,"rotationY",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Transform3D",label:"rotationZ",description:"Rotation around Z in radians.",editor:"number-stepper"})],D.prototype,"rotationZ",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"scaleX",description:"Scale on X.",editor:"number-stepper"})],D.prototype,"scaleX",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"scaleY",description:"Scale on Y.",editor:"number-stepper"})],D.prototype,"scaleY",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"scaleZ",description:"Scale on Z.",editor:"number-stepper"})],D.prototype,"scaleZ",void 0);let v=class extends t.System{constructor(){super(...arguments),this.name="Renderer3DSystem"}static{this.systemName="Renderer3DSystem"}init(e){const t=e||{},o=t.width||750,r=t.height||1334;this.threeContext=new b({canvas:t.canvas,container:t.container,width:o,height:r,antialias:t.antialias,backgroundColor:t.backgroundColor,backgroundAlpha:t.backgroundAlpha,fog:t.fog,hemisphereLight:t.hemisphereLight,shadows:t.shadows,toneMapping:t.toneMapping,toneMappingExposure:t.toneMappingExposure,ambientIntensity:t.ambientIntensity,directionalIntensity:t.directionalIntensity}),this.game.canvas=this.threeContext.renderer.domElement,this.rendererManager=new C({game:this.game,rendererSystem:this})}update(e){const t=this.componentObserver.clear();for(const e of t)this.handleHierarchyChange(e);for(const e of this.game.gameObjects){const t=e.getComponent(D);t&&this.threeContext.applyTransform3D(e,t),this.rendererManager.update(e)}}handleHierarchyChange(e){"GameObject"===e.componentName&&(e.type!==t.OBSERVER_TYPE.CHANGE&&e.type!==t.OBSERVER_TYPE.ADD||(this.ensureTransform3D(e.gameObject),e.gameObject.parent&&this.ensureTransform3D(e.gameObject.parent),this.threeContext?.reparentGameObject(e.gameObject)))}ensureTransform3D(e){if(!e||e.destroyed||e===e.scene)return;let t=e.getComponent(D);(t||(t=new D,e.addComponent(t)))&&this.threeContext?.ensureTransformRoot(e,t)}lateUpdate(){this.threeContext?.update()}resize(e,t){this.threeContext?.resize(e,t)}onDestroy(){this.threeContext?.destroy(),this.threeContext=null}};v=e.__decorate([t.decorators.componentObserver({GameObject:["parent"]})],v);var x=v;Object.assign(x,{packageName:"@combos-fun/plugin-renderer-3d",packageVersion:"0.1.13"});class O extends t.System{constructor(e){super(e),this.asyncIdMap={};const t=this.constructor;this.observerInfo=t.observerInfo}componentChanged(e){}rendererUpdate(e){}update(e){const t=this.componentObserver.clear();for(const e of t)this.componentChanged(e)}increaseAsyncId(e){return this.asyncIdMap[e]=(this.asyncIdMap[e]||0)+1,this.asyncIdMap[e]}validateAsyncId(e,t){return this.asyncIdMap[e]===t}}const w=new Set(["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"]);let R=class extends O{constructor(){super(...arguments),this.name="Transform3DSystem"}static{this.systemName="Transform3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("GameObject"===e.componentName)return this.ensureOn(e.gameObject),e.gameObject.parent&&this.ensureOn(e.gameObject.parent),void this.threeContext.reparentGameObject(e.gameObject);"Transform3D"===e.componentName&&(e.type===t.OBSERVER_TYPE.ADD?this.threeContext.ensureTransformRoot(e.gameObject,e.component):e.type===t.OBSERVER_TYPE.REMOVE?this.threeContext.detachObject3D(e.gameObject.id):w.has(e.prop?.prop?.[0])&&this.threeContext.applyTransform3D(e.gameObject,e.component))}rendererUpdate(e){const t=e.getComponent(D);t&&this.threeContext.applyTransform3D(e,t)}ensureOn(e){if(!e||e.destroyed||e===e.scene)return;let t=e.getComponent(D);(t||(t=new D,e.addComponent(t)))&&this.threeContext.ensureTransformRoot(e,t)}};R=e.__decorate([t.decorators.componentObserver({Transform3D:["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"],GameObject:["parent"]})],R);var _=R;class S extends t.Component{constructor(){super(...arguments),this.visible=!0,this.opacity=1,this.renderOrder=0,this.sortableChildren=!1}static{this.componentName="Render3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"boolean",group:"Render3D",label:"visible",description:"Whether this object is drawn.",editor:"toggle"})],S.prototype,"visible",void 0),e.__decorate([r.Field({type:"number",step:.01,min:0,max:1,group:"Render3D",label:"opacity",description:"Opacity from 0 to 1.",editor:"number-slider"})],S.prototype,"opacity",void 0),e.__decorate([r.Field({type:"number",step:1,group:"Render3D",label:"renderOrder",description:"Draw order; higher values render on top.",editor:"number-stepper"})],S.prototype,"renderOrder",void 0),e.__decorate([r.Field({type:"boolean",group:"Render3D",label:"sortableChildren",description:"When on, children are sorted by their render order before drawing.",editor:"toggle"})],S.prototype,"sortableChildren",void 0);let j=class extends O{constructor(){super(...arguments),this.name="Render3DSystem"}static{this.systemName="Render3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("Render3D"===e.componentName){if(e.type===t.OBSERVER_TYPE.REMOVE){const t=this.threeContext.object3DFor(e.gameObject.id);return void(t&&this.apply(t,{visible:!0,opacity:1,renderOrder:0,sortableChildren:!1}))}this.applyTo(e.gameObject,e.component)}}rendererUpdate(e){const t=e.getComponent(S);t&&this.applyTo(e,t)}applyTo(e,t){const o=this.threeContext.object3DFor(e.id);o&&(this.apply(o,t),t.sortableChildren&&this.sortChildren(e,o))}apply(e,t){e.visible=t.visible,e.traverse(e=>{e.renderOrder=t.renderOrder;const o=e;if(!o.isMesh||!o.material)return;const r=Array.isArray(o.material)?o.material:[o.material];for(const e of r){const o=e;"number"==typeof o.opacity&&(o.opacity=t.opacity,o.transparent=t.opacity<1)}})}sortChildren(e,t){const o=e.children?.map(e=>{if(!e)return null;const o=this.threeContext.object3DFor(e.id);if(!o||o.parent!==t)return null;const r=e.getComponent(S);return{node:o,order:r?.renderOrder??0}}).filter(e=>!!e).sort((e,t)=>e.order-t.order);if(o?.length)for(const e of o)t.add(e.node)}};j=e.__decorate([t.decorators.componentObserver({Render3D:["visible","opacity","renderOrder","sortableChildren"]})],j);var Y=j;class T extends t.Component{constructor(){super(...arguments),this.fov=75,this.near=.1,this.far=1e3,this.active=!0,this.lookAt=!1,this.lookAtX=0,this.lookAtY=0,this.lookAtZ=0}static{this.componentName="Camera3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"number",step:1,group:"Camera3D",label:"fov",description:"Vertical field of view in degrees.",editor:"number-stepper"})],T.prototype,"fov",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Camera3D",label:"near",description:"Near clipping plane.",editor:"number-stepper"})],T.prototype,"near",void 0),e.__decorate([r.Field({type:"number",step:1,group:"Camera3D",label:"far",description:"Far clipping plane.",editor:"number-stepper"})],T.prototype,"far",void 0),e.__decorate([r.Field({type:"boolean",group:"Camera3D",label:"active",description:"Use this camera for rendering.",editor:"toggle"})],T.prototype,"active",void 0),e.__decorate([r.Field({type:"boolean",group:"Camera3D",label:"lookAt",description:"Point the camera at lookAtX/Y/Z each frame.",editor:"toggle"})],T.prototype,"lookAt",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Camera3D",label:"lookAtX",description:"World-space look-at target on X.",editor:"number-stepper"})],T.prototype,"lookAtX",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Camera3D",label:"lookAtY",description:"World-space look-at target on Y.",editor:"number-stepper"})],T.prototype,"lookAtY",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Camera3D",label:"lookAtZ",description:"World-space look-at target on Z.",editor:"number-stepper"})],T.prototype,"lookAtZ",void 0);let E=class extends O{constructor(){super(...arguments),this.name="Camera3DSystem",this.cameras=new Map}static{this.systemName="Camera3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("Camera3D"!==e.componentName)return;const o=e.component;e.type===t.OBSERVER_TYPE.ADD?this.mount(e.gameObject,o):e.type===t.OBSERVER_TYPE.REMOVE?this.unmount(e.gameObject.id):this.sync(e.gameObject,o)}rendererUpdate(e){const t=e.getComponent(T),o=this.cameras.get(e.id);t&&o&&t.lookAt&&o.lookAt(t.lookAtX,t.lookAtY,t.lookAtZ)}mount(e,t){this.ensureTransform(e);const r=new o.PerspectiveCamera(t.fov,this.threeContext.camera.aspect,t.near,t.far);this.threeContext.attachVisual(e.id,r,e),this.cameras.set(e.id,r),this.sync(e,t)}sync(e,t){const o=this.cameras.get(e.id);o&&(o.fov=t.fov,o.near=t.near,o.far=t.far,o.updateProjectionMatrix(),t.active?this.threeContext.setActiveCamera(o):this.threeContext.camera===o&&this.activateAnother(e.id))}unmount(e){const t=this.cameras.get(e);t&&(this.threeContext.detachVisual(e,t),this.cameras.delete(e),this.threeContext.camera===t&&this.activateAnother(e))}activateAnother(e){for(const[t,o]of this.cameras){if(t===e)continue;const r=this.game.gameObjects.find(e=>e.id===t),s=r?.getComponent(T);if(s?.active)return void this.threeContext.setActiveCamera(o)}this.threeContext.restoreFallbackCamera()}ensureTransform(e){if(!e||e.destroyed)return;let t=e.getComponent(D);if(!t)return t=new D,t.positionZ=5,void e.addComponent(t);m(t)&&(t.positionZ=5)}onDestroy(){for(const[e]of this.cameras)this.unmount(e);this.cameras.clear()}};E=e.__decorate([t.decorators.componentObserver({Camera3D:["fov","near","far","active","lookAt","lookAtX","lookAtY","lookAtZ"]})],E);var A=E;class M extends t.Component{constructor(){super(...arguments),this.type="directional",this.color=16777215,this.intensity=1,this.castShadow=!1,this.skyColor=16777215,this.groundColor=4473924,this.distance=0,this.decay=2,this.angle=Math.PI/3,this.penumbra=0}static{this.componentName="Light3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"string",group:"Light3D",label:"type",description:"Light kind.",editor:"enum",enumOptions:["ambient","directional","hemisphere","point","spot"]})],M.prototype,"type",void 0),e.__decorate([r.Field({type:"number",group:"Light3D",label:"color",description:"Light color (hex).",editor:"number-stepper"})],M.prototype,"color",void 0),e.__decorate([r.Field({type:"number",step:.05,group:"Light3D",label:"intensity",description:"Light intensity.",editor:"number-stepper"})],M.prototype,"intensity",void 0),e.__decorate([r.Field({type:"boolean",group:"Light3D",label:"castShadow",description:"Whether this light casts shadows.",editor:"toggle"})],M.prototype,"castShadow",void 0),e.__decorate([r.Field({type:"number",group:"Light3D",label:"skyColor",description:"Hemisphere sky color (hex).",editor:"number-stepper"})],M.prototype,"skyColor",void 0),e.__decorate([r.Field({type:"number",group:"Light3D",label:"groundColor",description:"Hemisphere ground color (hex).",editor:"number-stepper"})],M.prototype,"groundColor",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Light3D",label:"distance",description:"Range for point and spot lights. 0 means no limit.",editor:"number-stepper"})],M.prototype,"distance",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Light3D",label:"decay",description:"Intensity falloff for point and spot lights.",editor:"number-stepper"})],M.prototype,"decay",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Light3D",label:"angle",description:"Spot light cone angle in radians.",editor:"number-stepper"})],M.prototype,"angle",void 0),e.__decorate([r.Field({type:"number",step:.01,min:0,max:1,group:"Light3D",label:"penumbra",description:"Spot light soft edge (0–1).",editor:"number-slider"})],M.prototype,"penumbra",void 0);let Z=class extends O{constructor(){super(...arguments),this.name="Light3DSystem",this.lights=new Map}static{this.systemName="Light3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("Light3D"!==e.componentName)return;const o=e.component;e.type===t.OBSERVER_TYPE.ADD?this.mount(e.gameObject,o):e.type===t.OBSERVER_TYPE.REMOVE?this.unmount(e.gameObject.id):"type"===e.prop?.prop?.[0]?(this.unmount(e.gameObject.id),this.mount(e.gameObject,o)):this.sync(e.gameObject.id,o)}rendererUpdate(e){}mount(e,t){this.ensureTransform(e),0===this.lights.size&&this.threeContext.removeDefaultLights();const o=this.createLight(t);this.threeContext.attachVisual(e.id,o,e),this.lights.set(e.id,o),this.sync(e.id,t)}createLight(e){switch(e.type){case"ambient":return new o.AmbientLight(e.color,e.intensity);case"hemisphere":return new o.HemisphereLight(e.skyColor,e.groundColor,e.intensity);case"point":return new o.PointLight(e.color,e.intensity,e.distance,e.decay);case"spot":return new o.SpotLight(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay);default:return new o.DirectionalLight(e.color,e.intensity)}}sync(e,t){const r=this.lights.get(e);r&&("color"in r&&r.color&&r.color.set(t.color),r.intensity=t.intensity,r instanceof o.HemisphereLight&&(r.color.set(t.skyColor),r.groundColor.set(t.groundColor)),(r instanceof o.PointLight||r instanceof o.SpotLight)&&(r.distance=t.distance,r.decay=t.decay),r instanceof o.SpotLight&&(r.angle=t.angle,r.penumbra=t.penumbra),"castShadow"in r&&(r.castShadow=!(!t.castShadow||!this.threeContext.shadows)))}unmount(e){const t=this.lights.get(e);t&&(this.threeContext.detachVisual(e,t),t.dispose?.(),this.lights.delete(e))}ensureTransform(e){e&&!e.destroyed&&(e.getComponent(D)||e.addComponent(new D))}onDestroy(){for(const[e]of this.lights)this.unmount(e);this.lights.clear()}};Z=e.__decorate([t.decorators.componentObserver({Light3D:["type","color","intensity","castShadow","skyColor","groundColor","distance","decay","angle","penumbra"]})],Z);var k=Z;async function X(e){const o=String(e??"").trim();if(!o)throw new Error("resource name is required; register it with resource.addResource");const r=await t.resource.getResource(o);if(!r||!r.name)throw new Error(`Unknown resource "${o}"; register it with resource.addResource first`);return r}function L(e){const t=e.data?.image;if(!t)throw new Error(`Resource "${e.name}" has no image data; use RESOURCE_TYPE.IMAGE with src.image.url`);const r=new o.Texture(t);return r.colorSpace=o.SRGBColorSpace,r.needsUpdate=!0,r}exports.COMBOS_GAME_OBJECT_ID=s,exports.COMBOS_TRANSFORM3D=n,exports.Camera3D=T,exports.Camera3DSystem=A,exports.Light3D=M,exports.Light3DSystem=k,exports.Render3D=S,exports.Render3DSystem=Y,exports.Renderer3D=O,exports.Renderer3DManager=C,exports.Renderer3DSystem=x,exports.ThreeContext=b,exports.Transform3D=D,exports.Transform3DSystem=_,exports.VisualPoseBridge=class{constructor(){this.lastVisual="",this.lastRoot=""}sync(e,t){if(!t)return!0;if(""===this.lastVisual&&""===this.lastRoot)return u(e,t),this.lastVisual=h(e),this.lastRoot=h(t),!1;const o=h(e),r=h(t);return o!==this.lastVisual&&r===this.lastRoot&&l(e,t),this.lastVisual=h(e),this.lastRoot=h(t),!1}},exports.copyPose=l,exports.gameObjectIdFromIntersection=function(e){return c(e?.object)},exports.gameObjectIdFromObject3D=c,exports.has3DChildGameObjects=function(e){return(e?.children?.length??0)>0},exports.is3DSceneParent=p,exports.isIdentityPose=m,exports.isTransform3DRoot=i,exports.poseKeyOf=h,exports.readPose=d,exports.requireNamedResource=X,exports.seedTransform3D=u,exports.tagObject3D=a,exports.textureFromNamedImage=async function(e){return L(await X(e))},exports.textureFromResourceImage=L;
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@combos-fun/engine"),o=require("three"),r=require("@combos-fun/inspector-decorator"),s=require("three/addons/loaders/KTX2Loader.js");const i="combosGameObjectId",n="combosTransform3D";function a(e){return!!e?.userData?.[n]}function c(e,t){e.traverse(e=>{e.userData[i]=t})}function p(e){let t=e;for(;t;){const e=t.userData?.[i];if("number"==typeof e)return e;t=t.parent}}function d(e){if(!e)return!0;const t=e.parent;return!t||t===e.scene}function h(e){return{positionX:e.positionX??0,positionY:e.positionY??0,positionZ:e.positionZ??0,rotationX:e.rotationX??0,rotationY:e.rotationY??0,rotationZ:e.rotationZ??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,scaleZ:e.scaleZ??1}}function l(e){const t=h(e);return[t.positionX,t.positionY,t.positionZ,t.rotationX,t.rotationY,t.rotationZ,t.scaleX,t.scaleY,t.scaleZ].join(",")}function m(e,t){const o=h(e);t.positionX=o.positionX,t.positionY=o.positionY,t.positionZ=o.positionZ,t.rotationX=o.rotationX,t.rotationY=o.rotationY,t.rotationZ=o.rotationZ,t.scaleX=o.scaleX,t.scaleY=o.scaleY,t.scaleZ=o.scaleZ}function u(e){const t=h(e);return 0===t.positionX&&0===t.positionY&&0===t.positionZ&&0===t.rotationX&&0===t.rotationY&&0===t.rotationZ&&1===t.scaleX&&1===t.scaleY&&1===t.scaleZ}function g(e,t){u(t)&&!u(e)&&m(e,t)}const f={none:o.NoToneMapping,aces:o.ACESFilmicToneMapping,linear:o.LinearToneMapping,reinhard:o.ReinhardToneMapping,cineon:o.CineonToneMapping},y=new o.Vector3,b=new o.Euler;class C{constructor(e){this.mixers=new Map,this.models=new Map,this.nodes=new Map,this.defaultLights=[];const{canvas:t,container:r,width:s,height:i,antialias:n=!0,backgroundColor:a=0,backgroundAlpha:c=1}=e;this.scene=new o.Scene,this.shadows=!!e.shadows,this.camera=new o.PerspectiveCamera(75,s/i,.1,1e3),this.camera.position.z=5,this.fallbackCamera=this.camera;const p=e.pixelRatio??1;this.width=s,this.height=i,this.pixelRatio=p;const d={antialias:n,powerPreference:e.powerPreference??"high-performance"};t&&(d.canvas=t),c<1&&(d.alpha=!0),this.renderer=new o.WebGLRenderer(d),this.renderer.setPixelRatio(p),this.renderer.setSize(s,i),this.renderer.setClearColor(a,c),this.renderer.toneMapping=f[e.toneMapping??"aces"]??o.ACESFilmicToneMapping,this.renderer.toneMappingExposure=e.toneMappingExposure??1,this.anisotropy=function(e){const t=e.capabilities,o=t?.getMaxAnisotropy?.()??0;return o>1?Math.min(8,o):1}(this.renderer);const h=e.softShadows??p<2,l=e.shadowMapSize??(h?1024:512);this.shadows&&(this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=h?o.PCFSoftShadowMap:o.PCFShadowMap),!t&&r&&r.appendChild(this.renderer.domElement);const m=new o.AmbientLight(16777215,e.ambientIntensity??.6);this.scene.add(m),this.defaultLights.push(m);const u=new o.DirectionalLight(16777215,e.directionalIntensity??.8);if(u.position.set(5,10,7.5),this.shadows&&(u.castShadow=!0,u.shadow.mapSize.set(l,l)),this.scene.add(u),this.defaultLights.push(u),!1!==e.hemisphereLight){const t="object"==typeof e.hemisphereLight?e.hemisphereLight:{},r=new o.HemisphereLight(t.skyColor??16777215,t.groundColor??4473924,t.intensity??.35);this.scene.add(r),this.defaultLights.push(r)}if(e.fog){const t="object"==typeof e.fog?e.fog:{};this.scene.fog=new o.Fog(t.color??a,t.near??8,t.far??40)}this.clock=new o.Clock}update(e){const t=this.clock.getDelta();if(!e?.skipDraw){for(const e of this.mixers.values())e.update(t);this.renderer.render(this.scene,this.camera)}}setPixelRatio(e){e>0&&e!==this.pixelRatio&&(this.pixelRatio=e,this.renderer.setPixelRatio(e),this.renderer.setSize(this.width,this.height))}configureTexture(e){!e?.isTexture||this.anisotropy<=1||e.anisotropy!==this.anisotropy&&(e.anisotropy=this.anisotropy,e.needsUpdate=!0)}configureObject(e){!e||this.anisotropy<=1||e.traverse(e=>{const t=e;if(!t.isMesh||!t.material)return;const o=Array.isArray(t.material)?t.material:[t.material];for(const e of o)D(e,e=>this.configureTexture(e))})}hasTransform3DRoot(e){return a(this.nodes.get(e))}applyModelShadows(e){this.shadows&&e.traverse(e=>{const t=e;t.isMesh&&(t.castShadow=!0,t.receiveShadow=!0)})}attachParsedModel(e,t,r,s){if(c(t,e),this.applyModelShadows(t),this.models.set(e,t),this.attachVisual(e,t,s),r&&r.length>0){const s=new o.AnimationMixer(t);this.mixers.set(e,s),t.userData.animations=r}return t}object3DFor(e){return this.nodes.get(e)}attachObject3D(e,t,o){const r=this.nodes.get(e);r&&r!==t&&(this.rehomeRegisteredChildren(r),r.parent?.remove(r)),this.nodes.set(e,t);const s=this.findParentNode(o);t.parent!==s&&s.add(t),o&&this.adoptChildGameObjects(o,t)}attachVisual(e,t,o){c(t,e),this.configureObject(t);const r=this.nodes.get(e);a(r)&&r!==t?t.parent!==r&&r.add(t):this.attachObject3D(e,t,o)}detachVisual(e,t){const o=this.nodes.get(e);return a(o)&&o!==t?(t.parent?.remove(t),t):o===t?this.detachObject3D(e):(t.parent?.remove(t),t)}detachObject3D(e){const t=this.nodes.get(e);if(t)return this.rehomeRegisteredChildren(t),t.parent?.remove(t),this.nodes.delete(e),t}reparentGameObject(e){const t=this.nodes.get(e.id);if(!t)return;const o=this.findParentNode(e);t.parent!==o&&o.add(t)}findParentNode(e){if(!e||d(e))return this.scene;let t=e.parent;for(;t&&t!==e.scene;){const e=this.nodes.get(t.id);if(e)return e;t=t.parent}return this.scene}adoptChildGameObjects(e,t){const o=e.children;if(o)for(const e of o){if(!e)continue;const o=this.nodes.get(e.id);o&&o.parent!==t&&t.add(o)}}ensureTransformRoot(e,t){const r=this.nodes.get(e.id);if(a(r))return this.applyTransformPose(r,t),r;const s=new o.Group;if(s.name=e.name,s.userData[n]=!0,c(s,e.id),r&&r!==s){(function(e){const t=h(e);return 0===t.positionX&&0===t.positionY&&0===t.positionZ&&0===t.rotationX&&0===t.rotationY&&0===t.rotationZ&&1===t.scaleX&&1===t.scaleY&&1===t.scaleZ})(t)&&(t.positionX=r.position.x,t.positionY=r.position.y,t.positionZ=r.position.z,t.rotationX=r.rotation.x,t.rotationY=r.rotation.y,t.rotationZ=r.rotation.z,t.scaleX=r.scale.x,t.scaleY=r.scale.y,t.scaleZ=r.scale.z);(r.parent||this.scene).add(s),s.add(r),r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),this.nodes.set(e.id,s),this.adoptChildGameObjects(e,s)}else this.attachObject3D(e.id,s,e);return this.applyTransformPose(s,t),s}applyTransform3D(e,t){const o=this.ensureTransformRoot(e,t);return this.applyTransformPose(o,t),o.updateWorldMatrix(!0,!1),o.getWorldPosition(y),t.worldPositionX=y.x,t.worldPositionY=y.y,t.worldPositionZ=y.z,b.setFromRotationMatrix(o.matrixWorld),t.worldRotationX=b.x,t.worldRotationY=b.y,t.worldRotationZ=b.z,o}applyTransformPose(e,t){const o=h(t);e.position.set(o.positionX,o.positionY,o.positionZ),e.rotation.set(o.rotationX,o.rotationY,o.rotationZ),e.scale.set(o.scaleX,o.scaleY,o.scaleZ)}removeDefaultLights(){if(this.defaultLights.length){for(const e of this.defaultLights)e.parent?.remove(e),e.dispose?.();this.defaultLights=[]}}setActiveCamera(e){const t=this.camera;this.camera=e,t&&(e.aspect=t.aspect),e.updateProjectionMatrix()}restoreFallbackCamera(){this.camera!==this.fallbackCamera&&this.setActiveCamera(this.fallbackCamera)}rehomeRegisteredChildren(e){for(const t of[...e.children]){const e=t.userData?.[i];"number"==typeof e&&this.nodes.get(e)===t&&this.scene.add(t)}}playAnimation(e,t,o){const r=this.mixers.get(e),s=this.models.get(e);if(!r||!s)return;r.stopAllAction();const i=s.userData.animations;if(i&&i[t]){const e=r.clipAction(i[t]);e.timeScale=o,e.play()}}stopAnimation(e){const t=this.mixers.get(e);t&&t.stopAllAction()}removeModel(e){const t=this.models.get(e);t&&(this.detachVisual(e,t),t.traverse(e=>{const t=e;if(t.geometry&&t.geometry.dispose(),t.material){(Array.isArray(t.material)?t.material:[t.material]).forEach(e=>e.dispose())}}),this.models.delete(e));const o=this.mixers.get(e);o&&(o.stopAllAction(),this.mixers.delete(e))}resize(e,t){this.width=e,this.height=t,this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.fallbackCamera!==this.camera&&(this.fallbackCamera.aspect=e/t,this.fallbackCamera.updateProjectionMatrix()),this.renderer.setSize(e,t)}destroy(){for(const e of this.models.keys())this.removeModel(e);this.removeDefaultLights(),this.renderer.dispose(),this.renderer.domElement.remove(),this.nodes.clear(),this.scene=null,this.camera=null,this.fallbackCamera=null,this.renderer=null,this.clock=null}}const x=["map","alphaMap","aoMap","bumpMap","displacementMap","emissiveMap","lightMap","metalnessMap","normalMap","roughnessMap"];function D(e,t){const o=e;for(const e of x){const r=o[e];r?.isTexture&&t(r)}}class w{constructor({game:e,rendererSystem:t}){this.renderers=[],this.game=e,this.rendererSystem=t}register(...e){for(const t of e)t.game=this.game,t.rendererManager=this,t.threeContext=this.rendererSystem.threeContext,this.renderers.push(t)}componentChanged(e){for(const o of e)for(const e of this.renderers){const r=e.observerInfo[o.componentName];if(!r)continue;if(o.type===t.OBSERVER_TYPE.ADD||o.type===t.OBSERVER_TYPE.REMOVE){try{e.componentChanged(o)}catch(e){console.error(`gameObject: ${o.gameObject.name}, ${o.componentName} error.`,o,e)}continue}if(r.findIndex(e=>"string"==typeof e&&"string"==typeof o.prop?e===o.prop:JSON.stringify(e)===JSON.stringify(o.prop))>-1)try{e.componentChanged(o)}catch(e){console.error(`gameObject: ${o.gameObject?.name}, ${o.componentName} componentChanged error.`,o,e)}}}update(e){for(const t of e.components)for(const o of this.renderers){if(o.observerInfo[t.name])try{o.rendererUpdate(e)}catch(o){console.info(`gameObject: ${e.name}, ${t.name} update error`,o)}}}}class v extends t.Component{constructor(){super(...arguments),this.positionX=0,this.positionY=0,this.positionZ=0,this.rotationX=0,this.rotationY=0,this.rotationZ=0,this.scaleX=1,this.scaleY=1,this.scaleZ=1,this.worldPositionX=0,this.worldPositionY=0,this.worldPositionZ=0,this.worldRotationX=0,this.worldRotationY=0,this.worldRotationZ=0}static{this.componentName="Transform3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"positionX",description:"Local X position.",editor:"number-stepper"})],v.prototype,"positionX",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"positionY",description:"Local Y position.",editor:"number-stepper"})],v.prototype,"positionY",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"positionZ",description:"Local Z position.",editor:"number-stepper"})],v.prototype,"positionZ",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Transform3D",label:"rotationX",description:"Rotation around X in radians.",editor:"number-stepper"})],v.prototype,"rotationX",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Transform3D",label:"rotationY",description:"Rotation around Y in radians.",editor:"number-stepper"})],v.prototype,"rotationY",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Transform3D",label:"rotationZ",description:"Rotation around Z in radians.",editor:"number-stepper"})],v.prototype,"rotationZ",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"scaleX",description:"Scale on X.",editor:"number-stepper"})],v.prototype,"scaleX",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"scaleY",description:"Scale on Y.",editor:"number-stepper"})],v.prototype,"scaleY",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Transform3D",label:"scaleZ",description:"Scale on Z.",editor:"number-stepper"})],v.prototype,"scaleZ",void 0);let R=class extends t.System{constructor(){super(...arguments),this.name="Renderer3DSystem",this.adaptive=null,this.pauseWhenHidden=!0}static{this.systemName="Renderer3DSystem"}init(e){const o=e||{},r=o.width||750,s=o.height||1334,i=t.resolveRenderQuality(o,{adaptivePixelRatio:!0});this.pauseWhenHidden=i.pauseWhenHidden,this.adaptive=new t.AdaptivePixelRatio({pixelRatio:i.pixelRatio,ceiling:i.pixelRatioCeiling,enabled:i.adaptivePixelRatio}),this.threeContext=new C({canvas:o.canvas,container:o.container,width:r,height:s,antialias:i.antialias,pixelRatio:i.pixelRatio,powerPreference:i.powerPreference,softShadows:o.softShadows,shadowMapSize:o.shadowMapSize,backgroundColor:o.backgroundColor,backgroundAlpha:o.backgroundAlpha,fog:o.fog,hemisphereLight:o.hemisphereLight,shadows:o.shadows,toneMapping:o.toneMapping,toneMappingExposure:o.toneMappingExposure,ambientIntensity:o.ambientIntensity,directionalIntensity:o.directionalIntensity}),this.game.canvas=this.threeContext.renderer.domElement,this.rendererManager=new w({game:this.game,rendererSystem:this})}update(e){const t=this.componentObserver.clear();for(const e of t)this.handleHierarchyChange(e);for(const e of this.game.gameObjects){const t=e.getComponent(v);t&&this.threeContext.applyTransform3D(e,t),this.rendererManager.update(e)}}handleHierarchyChange(e){"GameObject"===e.componentName&&(e.type!==t.OBSERVER_TYPE.CHANGE&&e.type!==t.OBSERVER_TYPE.ADD||(this.ensureTransform3D(e.gameObject),e.gameObject.parent&&this.ensureTransform3D(e.gameObject.parent),this.threeContext?.reparentGameObject(e.gameObject)))}ensureTransform3D(e){if(!e||e.destroyed||e===e.scene)return;let t=e.getComponent(v);(t||(t=new v,e.addComponent(t)))&&this.threeContext?.ensureTransformRoot(e,t)}lateUpdate(e){if(!this.threeContext)return;if(t.shouldPauseRendering(this.pauseWhenHidden))return void this.threeContext.update({skipDraw:!0});const o=this.adaptive?.sample(e?.deltaTime??0);null!=o&&this.threeContext.setPixelRatio(o),this.threeContext.update()}resize(e,t){this.threeContext?.resize(e,t)}onDestroy(){this.threeContext?.destroy(),this.threeContext=null}};R=e.__decorate([t.decorators.componentObserver({GameObject:["parent"]})],R);var O=R;Object.assign(O,{packageName:"@combos-fun/plugin-renderer-3d",packageVersion:"0.1.14-beta.1"});class _ extends t.System{constructor(e){super(e),this.asyncIdMap={};const t=this.constructor;this.observerInfo=t.observerInfo}componentChanged(e){}rendererUpdate(e){}update(e){const t=this.componentObserver.clear();for(const e of t)this.componentChanged(e)}increaseAsyncId(e){return this.asyncIdMap[e]=(this.asyncIdMap[e]||0)+1,this.asyncIdMap[e]}validateAsyncId(e,t){return this.asyncIdMap[e]===t}}const S=new Set(["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"]);let T=class extends _{constructor(){super(...arguments),this.name="Transform3DSystem"}static{this.systemName="Transform3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("GameObject"===e.componentName)return this.ensureOn(e.gameObject),e.gameObject.parent&&this.ensureOn(e.gameObject.parent),void this.threeContext.reparentGameObject(e.gameObject);"Transform3D"===e.componentName&&(e.type===t.OBSERVER_TYPE.ADD?this.threeContext.ensureTransformRoot(e.gameObject,e.component):e.type===t.OBSERVER_TYPE.REMOVE?this.threeContext.detachObject3D(e.gameObject.id):S.has(e.prop?.prop?.[0])&&this.threeContext.applyTransform3D(e.gameObject,e.component))}rendererUpdate(e){const t=e.getComponent(v);t&&this.threeContext.applyTransform3D(e,t)}ensureOn(e){if(!e||e.destroyed||e===e.scene)return;let t=e.getComponent(v);(t||(t=new v,e.addComponent(t)))&&this.threeContext.ensureTransformRoot(e,t)}};T=e.__decorate([t.decorators.componentObserver({Transform3D:["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"],GameObject:["parent"]})],T);var M=T;class E extends t.Component{constructor(){super(...arguments),this.visible=!0,this.opacity=1,this.renderOrder=0,this.sortableChildren=!1}static{this.componentName="Render3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"boolean",group:"Render3D",label:"visible",description:"Whether this object is drawn.",editor:"toggle"})],E.prototype,"visible",void 0),e.__decorate([r.Field({type:"number",step:.01,min:0,max:1,group:"Render3D",label:"opacity",description:"Opacity from 0 to 1.",editor:"number-slider"})],E.prototype,"opacity",void 0),e.__decorate([r.Field({type:"number",step:1,group:"Render3D",label:"renderOrder",description:"Draw order; higher values render on top.",editor:"number-stepper"})],E.prototype,"renderOrder",void 0),e.__decorate([r.Field({type:"boolean",group:"Render3D",label:"sortableChildren",description:"When on, children are sorted by their render order before drawing.",editor:"toggle"})],E.prototype,"sortableChildren",void 0);let j=class extends _{constructor(){super(...arguments),this.name="Render3DSystem"}static{this.systemName="Render3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("Render3D"===e.componentName){if(e.type===t.OBSERVER_TYPE.REMOVE){const t=this.threeContext.object3DFor(e.gameObject.id);return void(t&&this.apply(t,{visible:!0,opacity:1,renderOrder:0,sortableChildren:!1}))}this.applyTo(e.gameObject,e.component)}}rendererUpdate(e){const t=e.getComponent(E);t&&this.applyTo(e,t)}applyTo(e,t){const o=this.threeContext.object3DFor(e.id);o&&(this.apply(o,t),t.sortableChildren&&this.sortChildren(e,o))}apply(e,t){e.visible=t.visible,e.traverse(e=>{e.renderOrder=t.renderOrder;const o=e;if(!o.isMesh||!o.material)return;const r=Array.isArray(o.material)?o.material:[o.material];for(const e of r){const o=e;"number"==typeof o.opacity&&(o.opacity=t.opacity,o.transparent=t.opacity<1)}})}sortChildren(e,t){const o=e.children?.map(e=>{if(!e)return null;const o=this.threeContext.object3DFor(e.id);if(!o||o.parent!==t)return null;const r=e.getComponent(E);return{node:o,order:r?.renderOrder??0}}).filter(e=>!!e).sort((e,t)=>e.order-t.order);if(o?.length)for(const e of o)t.add(e.node)}};j=e.__decorate([t.decorators.componentObserver({Render3D:["visible","opacity","renderOrder","sortableChildren"]})],j);var A=j;class Y extends t.Component{constructor(){super(...arguments),this.fov=75,this.near=.1,this.far=1e3,this.active=!0,this.lookAt=!1,this.lookAtX=0,this.lookAtY=0,this.lookAtZ=0}static{this.componentName="Camera3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"number",step:1,group:"Camera3D",label:"fov",description:"Vertical field of view in degrees.",editor:"number-stepper"})],Y.prototype,"fov",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Camera3D",label:"near",description:"Near clipping plane.",editor:"number-stepper"})],Y.prototype,"near",void 0),e.__decorate([r.Field({type:"number",step:1,group:"Camera3D",label:"far",description:"Far clipping plane.",editor:"number-stepper"})],Y.prototype,"far",void 0),e.__decorate([r.Field({type:"boolean",group:"Camera3D",label:"active",description:"Use this camera for rendering.",editor:"toggle"})],Y.prototype,"active",void 0),e.__decorate([r.Field({type:"boolean",group:"Camera3D",label:"lookAt",description:"Point the camera at lookAtX/Y/Z each frame.",editor:"toggle"})],Y.prototype,"lookAt",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Camera3D",label:"lookAtX",description:"World-space look-at target on X.",editor:"number-stepper"})],Y.prototype,"lookAtX",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Camera3D",label:"lookAtY",description:"World-space look-at target on Y.",editor:"number-stepper"})],Y.prototype,"lookAtY",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Camera3D",label:"lookAtZ",description:"World-space look-at target on Z.",editor:"number-stepper"})],Y.prototype,"lookAtZ",void 0);let L=class extends _{constructor(){super(...arguments),this.name="Camera3DSystem",this.cameras=new Map}static{this.systemName="Camera3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("Camera3D"!==e.componentName)return;const o=e.component;e.type===t.OBSERVER_TYPE.ADD?this.mount(e.gameObject,o):e.type===t.OBSERVER_TYPE.REMOVE?this.unmount(e.gameObject.id):this.sync(e.gameObject,o)}rendererUpdate(e){const t=e.getComponent(Y),o=this.cameras.get(e.id);t&&o&&t.lookAt&&o.lookAt(t.lookAtX,t.lookAtY,t.lookAtZ)}mount(e,t){this.ensureTransform(e);const r=new o.PerspectiveCamera(t.fov,this.threeContext.camera.aspect,t.near,t.far);this.threeContext.attachVisual(e.id,r,e),this.cameras.set(e.id,r),this.sync(e,t)}sync(e,t){const o=this.cameras.get(e.id);o&&(o.fov=t.fov,o.near=t.near,o.far=t.far,o.updateProjectionMatrix(),t.active?this.threeContext.setActiveCamera(o):this.threeContext.camera===o&&this.activateAnother(e.id))}unmount(e){const t=this.cameras.get(e);t&&(this.threeContext.detachVisual(e,t),this.cameras.delete(e),this.threeContext.camera===t&&this.activateAnother(e))}activateAnother(e){for(const[t,o]of this.cameras){if(t===e)continue;const r=this.game.gameObjects.find(e=>e.id===t),s=r?.getComponent(Y);if(s?.active)return void this.threeContext.setActiveCamera(o)}this.threeContext.restoreFallbackCamera()}ensureTransform(e){if(!e||e.destroyed)return;let t=e.getComponent(v);if(!t)return t=new v,t.positionZ=5,void e.addComponent(t);u(t)&&(t.positionZ=5)}onDestroy(){for(const[e]of this.cameras)this.unmount(e);this.cameras.clear()}};L=e.__decorate([t.decorators.componentObserver({Camera3D:["fov","near","far","active","lookAt","lookAtX","lookAtY","lookAtZ"]})],L);var k=L;class P extends t.Component{constructor(){super(...arguments),this.type="directional",this.color=16777215,this.intensity=1,this.castShadow=!1,this.skyColor=16777215,this.groundColor=4473924,this.distance=0,this.decay=2,this.angle=Math.PI/3,this.penumbra=0}static{this.componentName="Light3D"}init(e){e&&Object.assign(this,e)}}e.__decorate([r.Field({type:"string",group:"Light3D",label:"type",description:"Light kind.",editor:"enum",enumOptions:["ambient","directional","hemisphere","point","spot"]})],P.prototype,"type",void 0),e.__decorate([r.Field({type:"number",group:"Light3D",label:"color",description:"Light color (hex).",editor:"number-stepper"})],P.prototype,"color",void 0),e.__decorate([r.Field({type:"number",step:.05,group:"Light3D",label:"intensity",description:"Light intensity.",editor:"number-stepper"})],P.prototype,"intensity",void 0),e.__decorate([r.Field({type:"boolean",group:"Light3D",label:"castShadow",description:"Whether this light casts shadows.",editor:"toggle"})],P.prototype,"castShadow",void 0),e.__decorate([r.Field({type:"number",group:"Light3D",label:"skyColor",description:"Hemisphere sky color (hex).",editor:"number-stepper"})],P.prototype,"skyColor",void 0),e.__decorate([r.Field({type:"number",group:"Light3D",label:"groundColor",description:"Hemisphere ground color (hex).",editor:"number-stepper"})],P.prototype,"groundColor",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Light3D",label:"distance",description:"Range for point and spot lights. 0 means no limit.",editor:"number-stepper"})],P.prototype,"distance",void 0),e.__decorate([r.Field({type:"number",step:.1,group:"Light3D",label:"decay",description:"Intensity falloff for point and spot lights.",editor:"number-stepper"})],P.prototype,"decay",void 0),e.__decorate([r.Field({type:"number",step:.01,group:"Light3D",label:"angle",description:"Spot light cone angle in radians.",editor:"number-stepper"})],P.prototype,"angle",void 0),e.__decorate([r.Field({type:"number",step:.01,min:0,max:1,group:"Light3D",label:"penumbra",description:"Spot light soft edge (0–1).",editor:"number-slider"})],P.prototype,"penumbra",void 0);let X=class extends _{constructor(){super(...arguments),this.name="Light3DSystem",this.lights=new Map}static{this.systemName="Light3DSystem"}init(){this.game.getSystem("Renderer3DSystem").rendererManager.register(this)}componentChanged(e){if("Light3D"!==e.componentName)return;const o=e.component;e.type===t.OBSERVER_TYPE.ADD?this.mount(e.gameObject,o):e.type===t.OBSERVER_TYPE.REMOVE?this.unmount(e.gameObject.id):"type"===e.prop?.prop?.[0]?(this.unmount(e.gameObject.id),this.mount(e.gameObject,o)):this.sync(e.gameObject.id,o)}rendererUpdate(e){}mount(e,t){this.ensureTransform(e),0===this.lights.size&&this.threeContext.removeDefaultLights();const o=this.createLight(t);this.threeContext.attachVisual(e.id,o,e),this.lights.set(e.id,o),this.sync(e.id,t)}createLight(e){switch(e.type){case"ambient":return new o.AmbientLight(e.color,e.intensity);case"hemisphere":return new o.HemisphereLight(e.skyColor,e.groundColor,e.intensity);case"point":return new o.PointLight(e.color,e.intensity,e.distance,e.decay);case"spot":return new o.SpotLight(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay);default:return new o.DirectionalLight(e.color,e.intensity)}}sync(e,t){const r=this.lights.get(e);r&&("color"in r&&r.color&&r.color.set(t.color),r.intensity=t.intensity,r instanceof o.HemisphereLight&&(r.color.set(t.skyColor),r.groundColor.set(t.groundColor)),(r instanceof o.PointLight||r instanceof o.SpotLight)&&(r.distance=t.distance,r.decay=t.decay),r instanceof o.SpotLight&&(r.angle=t.angle,r.penumbra=t.penumbra),"castShadow"in r&&(r.castShadow=!(!t.castShadow||!this.threeContext.shadows)))}unmount(e){const t=this.lights.get(e);t&&(this.threeContext.detachVisual(e,t),t.dispose?.(),this.lights.delete(e))}ensureTransform(e){e&&!e.destroyed&&(e.getComponent(v)||e.addComponent(new v))}onDestroy(){for(const[e]of this.lights)this.unmount(e);this.lights.clear()}};X=e.__decorate([t.decorators.componentObserver({Light3D:["type","color","intensity","castShadow","skyColor","groundColor","distance","decay","angle","penumbra"]})],X);var Z=X;const F=["WEBGL_compressed_texture_astc","EXT_texture_compression_bptc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_etc"];let I=null,V=null;function N(e){return F.some(t=>e.extensions.has(t))}function B(e){return I||(I=new s.KTX2Loader,I.setTranscoderPath("https://unpkg.com/three@0.172.0/examples/jsm/libs/basis/")),e&&V!==e&&(I.detectSupport(e),V=e),I}async function G(e,t){if(!N(t))return null;try{const r=await B(t).loadAsync(e),s=r;return s?.isCompressedTexture&&s.format!==o.RGBAFormat?r:(r?.dispose(),null)}catch{return null}}async function U(e){const o=String(e??"").trim();if(!o)throw new Error("resource name is required; register it with resource.addResource");const r=await t.resource.getResource(o);if(!r||!r.name)throw new Error(`Unknown resource "${o}"; register it with resource.addResource first`);return r}function z(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?e:null}async function W(e){let t=e;if("function"==typeof createImageBitmap)try{t=await createImageBitmap(e)}catch{t=e}const r=new o.Texture(t);if(r.colorSpace=o.SRGBColorSpace,r.needsUpdate=!0,"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=t,o=r.dispose.bind(r);r.dispose=()=>{o();try{e.close()}catch{}}}return r}async function H(e,o){if(!o)return null;const r=function(e){if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e)){const t=e;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}return null}(e.data?.image);if(!r)return null;const s=t.compressedTextureUrl(e.src?.image),i=URL.createObjectURL(new Blob([r]));try{const e=await G(i,o);if(e)return e}finally{URL.revokeObjectURL(i)}return s?G(s,o):null}async function $(e,o){const r=await H(e,o);if(r)return r;const s=z(e.data?.image);if(s)return W(s);const i=t.imageFallbackUrl(e.src?.image);if(i)try{return W(await(n=i,new Promise((e,t)=>{const o=new Image;o.crossOrigin="anonymous",o.onload=()=>e(o),o.onerror=()=>t(new Error(`Failed to load image ${n}`)),o.src=n})))}catch{}var n;throw new Error(`Resource "${e.name}" has no image data; use RESOURCE_TYPE.IMAGE with src.image.url`)}exports.COMBOS_GAME_OBJECT_ID=i,exports.COMBOS_TRANSFORM3D=n,exports.Camera3D=Y,exports.Camera3DSystem=k,exports.Light3D=P,exports.Light3DSystem=Z,exports.Render3D=E,exports.Render3DSystem=A,exports.Renderer3D=_,exports.Renderer3DManager=w,exports.Renderer3DSystem=O,exports.ThreeContext=C,exports.Transform3D=v,exports.Transform3DSystem=M,exports.VisualPoseBridge=class{constructor(){this.lastVisual="",this.lastRoot=""}sync(e,t){if(!t)return!0;if(""===this.lastVisual&&""===this.lastRoot)return g(e,t),this.lastVisual=l(e),this.lastRoot=l(t),!1;const o=l(e),r=l(t);return o!==this.lastVisual&&r===this.lastRoot&&m(e,t),this.lastVisual=l(e),this.lastRoot=l(t),!1}},exports.copyPose=m,exports.ensureKtx2Loader=B,exports.gameObjectIdFromIntersection=function(e){return p(e?.object)},exports.gameObjectIdFromObject3D=p,exports.has3DChildGameObjects=function(e){return(e?.children?.length??0)>0},exports.is3DSceneParent=d,exports.isIdentityPose=u,exports.isTransform3DRoot=a,exports.loadThreeKtx2=G,exports.poseKeyOf=l,exports.readPose=h,exports.rendererSupportsCompressedTexture=N,exports.requireNamedResource=U,exports.seedTransform3D=g,exports.tagObject3D=c,exports.textureFromNamedImage=async function(e,t){return $(await U(e),t)},exports.textureFromResourceImage=function(e){const t=z(e.data?.image);if(!t)throw new Error(`Resource "${e.name}" has no image data; use RESOURCE_TYPE.IMAGE with src.image.url`);const r=new o.Texture(t);return r.colorSpace=o.SRGBColorSpace,r.needsUpdate=!0,r},exports.textureFromResourceImageAsync=$;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { GameObject, System, Game, PureObserverInfo, ComponentChanged, UpdateParams, Component, ResourceStruct } from '@combos-fun/engine';
|
|
2
|
-
import { Scene, PerspectiveCamera, WebGLRenderer, Clock, AnimationMixer, Group, Object3D,
|
|
1
|
+
import { PowerPreference, GameObject, System, Game, PureObserverInfo, ComponentChanged, UpdateParams, RenderQualityInput, Component, ResourceStruct } from '@combos-fun/engine';
|
|
2
|
+
import { Scene, PerspectiveCamera, WebGLRenderer, Clock, AnimationMixer, Group, Object3D, Texture, AnimationClip } from 'three';
|
|
3
|
+
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
|
|
3
4
|
|
|
4
5
|
interface PoseLike {
|
|
5
6
|
positionX?: number;
|
|
@@ -55,6 +56,11 @@ interface ThreeContextParams {
|
|
|
55
56
|
width: number;
|
|
56
57
|
height: number;
|
|
57
58
|
antialias?: boolean;
|
|
59
|
+
pixelRatio?: number;
|
|
60
|
+
powerPreference?: PowerPreference;
|
|
61
|
+
/** Force soft shadows. Omitted: soft shadows only when pixel ratio is below 2. */
|
|
62
|
+
softShadows?: boolean;
|
|
63
|
+
shadowMapSize?: number;
|
|
58
64
|
backgroundColor?: number;
|
|
59
65
|
backgroundAlpha?: number;
|
|
60
66
|
fog?: boolean | FogParams;
|
|
@@ -85,8 +91,17 @@ declare class ThreeContext {
|
|
|
85
91
|
nodes: Map<number, Object3D>;
|
|
86
92
|
shadows: boolean;
|
|
87
93
|
defaultLights: Object3D[];
|
|
94
|
+
width: number;
|
|
95
|
+
height: number;
|
|
96
|
+
pixelRatio: number;
|
|
97
|
+
anisotropy: number;
|
|
88
98
|
constructor(params: ThreeContextParams);
|
|
89
|
-
update(
|
|
99
|
+
update(options?: {
|
|
100
|
+
skipDraw?: boolean;
|
|
101
|
+
}): void;
|
|
102
|
+
setPixelRatio(pixelRatio: number): void;
|
|
103
|
+
configureTexture(texture: Texture | null | undefined): void;
|
|
104
|
+
configureObject(object: Object3D): void;
|
|
90
105
|
hasTransform3DRoot(id: number): boolean;
|
|
91
106
|
applyModelShadows(object: Object3D): void;
|
|
92
107
|
attachParsedModel(id: number, model: Group, animations?: AnimationClip[], gameObject?: GameObject): Group;
|
|
@@ -147,7 +162,7 @@ declare class Renderer3DManager {
|
|
|
147
162
|
update(gameObject: GameObject): void;
|
|
148
163
|
}
|
|
149
164
|
|
|
150
|
-
interface Renderer3DSystemParams extends Partial<ThreeContextParams
|
|
165
|
+
interface Renderer3DSystemParams extends Partial<ThreeContextParams>, RenderQualityInput {
|
|
151
166
|
canvas?: HTMLCanvasElement;
|
|
152
167
|
container?: HTMLElement;
|
|
153
168
|
width?: number;
|
|
@@ -161,11 +176,13 @@ declare class Renderer3DSystem extends System<Renderer3DSystemParams> {
|
|
|
161
176
|
name: string;
|
|
162
177
|
threeContext: ThreeContext;
|
|
163
178
|
rendererManager: Renderer3DManager;
|
|
179
|
+
private adaptive;
|
|
180
|
+
private pauseWhenHidden;
|
|
164
181
|
init(params?: Renderer3DSystemParams): void;
|
|
165
182
|
update(e?: UpdateParams): void;
|
|
166
183
|
private handleHierarchyChange;
|
|
167
184
|
private ensureTransform3D;
|
|
168
|
-
lateUpdate(): void;
|
|
185
|
+
lateUpdate(e?: UpdateParams): void;
|
|
169
186
|
resize(width: number, height: number): void;
|
|
170
187
|
onDestroy(): void;
|
|
171
188
|
}
|
|
@@ -330,11 +347,17 @@ declare function gameObjectIdFromIntersection(intersection: {
|
|
|
330
347
|
|
|
331
348
|
declare function requireNamedResource(name: string): Promise<ResourceStruct>;
|
|
332
349
|
declare function textureFromResourceImage(res: ResourceStruct): Texture;
|
|
333
|
-
declare function
|
|
350
|
+
declare function textureFromResourceImageAsync(res: ResourceStruct, renderer?: WebGLRenderer): Promise<Texture>;
|
|
351
|
+
declare function textureFromNamedImage(name: string, renderer?: WebGLRenderer): Promise<Texture>;
|
|
352
|
+
|
|
353
|
+
declare function rendererSupportsCompressedTexture(renderer: WebGLRenderer): boolean;
|
|
354
|
+
/** One Basis transcoder shared by glTF models and standalone KTX2 images. */
|
|
355
|
+
declare function ensureKtx2Loader(renderer?: WebGLRenderer): KTX2Loader;
|
|
356
|
+
declare function loadThreeKtx2(url: string, renderer: WebGLRenderer): Promise<Texture | null>;
|
|
334
357
|
|
|
335
358
|
/** True when this GameObject is a scene root (no 3D parent). */
|
|
336
359
|
declare function is3DSceneParent(gameObject: GameObject | undefined | null): boolean;
|
|
337
360
|
declare function has3DChildGameObjects(gameObject: GameObject | undefined | null): boolean;
|
|
338
361
|
|
|
339
|
-
export { COMBOS_GAME_OBJECT_ID, COMBOS_TRANSFORM3D, Camera3D, Camera3DSystem, Light3D, Light3DSystem, Render3D, Render3DSystem, Renderer3D, Renderer3DManager, Renderer3DSystem, ThreeContext, Transform3D, Transform3DSystem, VisualPoseBridge, copyPose, gameObjectIdFromIntersection, gameObjectIdFromObject3D, has3DChildGameObjects, is3DSceneParent, isIdentityPose, isTransform3DRoot, poseKeyOf, readPose, requireNamedResource, seedTransform3D, tagObject3D, textureFromNamedImage, textureFromResourceImage };
|
|
362
|
+
export { COMBOS_GAME_OBJECT_ID, COMBOS_TRANSFORM3D, Camera3D, Camera3DSystem, Light3D, Light3DSystem, Render3D, Render3DSystem, Renderer3D, Renderer3DManager, Renderer3DSystem, ThreeContext, Transform3D, Transform3DSystem, VisualPoseBridge, copyPose, ensureKtx2Loader, gameObjectIdFromIntersection, gameObjectIdFromObject3D, has3DChildGameObjects, is3DSceneParent, isIdentityPose, isTransform3DRoot, loadThreeKtx2, poseKeyOf, readPose, rendererSupportsCompressedTexture, requireNamedResource, seedTransform3D, tagObject3D, textureFromNamedImage, textureFromResourceImage, textureFromResourceImageAsync };
|
|
340
363
|
export type { Camera3DParams, FogParams, HemisphereLightParams, Light3DKind, Light3DParams, PoseLike, Render3DParams, Renderer3DSystemParams, ThreeContextParams, ToneMappingKind, Transform3DLike, Transform3DParams };
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { __decorate } from 'tslib';
|
|
2
|
-
import { OBSERVER_TYPE, Component, System, decorators, resource } from '@combos-fun/engine';
|
|
3
|
-
import { Vector3, Euler, Scene, PerspectiveCamera, WebGLRenderer, CineonToneMapping, ReinhardToneMapping, LinearToneMapping, ACESFilmicToneMapping, NoToneMapping, PCFSoftShadowMap, AmbientLight, DirectionalLight, HemisphereLight, Fog, Clock, AnimationMixer, Group, SpotLight, PointLight, Texture, SRGBColorSpace } from 'three';
|
|
2
|
+
import { OBSERVER_TYPE, Component, System, resolveRenderQuality, AdaptivePixelRatio, shouldPauseRendering, decorators, resource, imageFallbackUrl, compressedTextureUrl } from '@combos-fun/engine';
|
|
3
|
+
import { Vector3, Euler, Scene, PerspectiveCamera, WebGLRenderer, CineonToneMapping, ReinhardToneMapping, LinearToneMapping, ACESFilmicToneMapping, NoToneMapping, PCFSoftShadowMap, PCFShadowMap, AmbientLight, DirectionalLight, HemisphereLight, Fog, Clock, AnimationMixer, Group, SpotLight, PointLight, RGBAFormat, Texture, SRGBColorSpace } from 'three';
|
|
4
4
|
import { Field } from '@combos-fun/inspector-decorator';
|
|
5
|
+
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
|
|
5
6
|
|
|
6
7
|
const COMBOS_GAME_OBJECT_ID = 'combosGameObjectId';
|
|
7
8
|
const COMBOS_TRANSFORM3D = 'combosTransform3D';
|
|
@@ -137,7 +138,14 @@ class ThreeContext {
|
|
|
137
138
|
this.camera = new PerspectiveCamera(75, width / height, 0.1, 1000);
|
|
138
139
|
this.camera.position.z = 5;
|
|
139
140
|
this.fallbackCamera = this.camera;
|
|
140
|
-
const
|
|
141
|
+
const pixelRatio = params.pixelRatio ?? 1;
|
|
142
|
+
this.width = width;
|
|
143
|
+
this.height = height;
|
|
144
|
+
this.pixelRatio = pixelRatio;
|
|
145
|
+
const rendererOpts = {
|
|
146
|
+
antialias,
|
|
147
|
+
powerPreference: params.powerPreference ?? 'high-performance',
|
|
148
|
+
};
|
|
141
149
|
if (canvas) {
|
|
142
150
|
rendererOpts.canvas = canvas;
|
|
143
151
|
}
|
|
@@ -145,14 +153,17 @@ class ThreeContext {
|
|
|
145
153
|
rendererOpts.alpha = true;
|
|
146
154
|
}
|
|
147
155
|
this.renderer = new WebGLRenderer(rendererOpts);
|
|
156
|
+
this.renderer.setPixelRatio(pixelRatio);
|
|
148
157
|
this.renderer.setSize(width, height);
|
|
149
|
-
this.renderer.setPixelRatio(window.devicePixelRatio);
|
|
150
158
|
this.renderer.setClearColor(backgroundColor, backgroundAlpha);
|
|
151
159
|
this.renderer.toneMapping = TONE_MAPPING[params.toneMapping ?? 'aces'] ?? ACESFilmicToneMapping;
|
|
152
160
|
this.renderer.toneMappingExposure = params.toneMappingExposure ?? 1;
|
|
161
|
+
this.anisotropy = readAnisotropy(this.renderer);
|
|
162
|
+
const softShadows = params.softShadows ?? pixelRatio < 2;
|
|
163
|
+
const shadowMapSize = params.shadowMapSize ?? (softShadows ? 1024 : 512);
|
|
153
164
|
if (this.shadows) {
|
|
154
165
|
this.renderer.shadowMap.enabled = true;
|
|
155
|
-
this.renderer.shadowMap.type = PCFSoftShadowMap;
|
|
166
|
+
this.renderer.shadowMap.type = softShadows ? PCFSoftShadowMap : PCFShadowMap;
|
|
156
167
|
}
|
|
157
168
|
if (!canvas && container) {
|
|
158
169
|
container.appendChild(this.renderer.domElement);
|
|
@@ -164,7 +175,7 @@ class ThreeContext {
|
|
|
164
175
|
directionalLight.position.set(5, 10, 7.5);
|
|
165
176
|
if (this.shadows) {
|
|
166
177
|
directionalLight.castShadow = true;
|
|
167
|
-
directionalLight.shadow.mapSize.set(
|
|
178
|
+
directionalLight.shadow.mapSize.set(shadowMapSize, shadowMapSize);
|
|
168
179
|
}
|
|
169
180
|
this.scene.add(directionalLight);
|
|
170
181
|
this.defaultLights.push(directionalLight);
|
|
@@ -180,13 +191,43 @@ class ThreeContext {
|
|
|
180
191
|
}
|
|
181
192
|
this.clock = new Clock();
|
|
182
193
|
}
|
|
183
|
-
update() {
|
|
194
|
+
update(options) {
|
|
184
195
|
const delta = this.clock.getDelta();
|
|
196
|
+
if (options?.skipDraw)
|
|
197
|
+
return;
|
|
185
198
|
for (const mixer of this.mixers.values()) {
|
|
186
199
|
mixer.update(delta);
|
|
187
200
|
}
|
|
188
201
|
this.renderer.render(this.scene, this.camera);
|
|
189
202
|
}
|
|
203
|
+
setPixelRatio(pixelRatio) {
|
|
204
|
+
if (!(pixelRatio > 0) || pixelRatio === this.pixelRatio)
|
|
205
|
+
return;
|
|
206
|
+
this.pixelRatio = pixelRatio;
|
|
207
|
+
this.renderer.setPixelRatio(pixelRatio);
|
|
208
|
+
this.renderer.setSize(this.width, this.height);
|
|
209
|
+
}
|
|
210
|
+
configureTexture(texture) {
|
|
211
|
+
if (!texture?.isTexture || this.anisotropy <= 1)
|
|
212
|
+
return;
|
|
213
|
+
if (texture.anisotropy === this.anisotropy)
|
|
214
|
+
return;
|
|
215
|
+
texture.anisotropy = this.anisotropy;
|
|
216
|
+
texture.needsUpdate = true;
|
|
217
|
+
}
|
|
218
|
+
configureObject(object) {
|
|
219
|
+
if (!object || this.anisotropy <= 1)
|
|
220
|
+
return;
|
|
221
|
+
object.traverse((child) => {
|
|
222
|
+
const mesh = child;
|
|
223
|
+
if (!mesh.isMesh || !mesh.material)
|
|
224
|
+
return;
|
|
225
|
+
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
|
|
226
|
+
for (const material of materials) {
|
|
227
|
+
configureMaterialTextures(material, (texture) => this.configureTexture(texture));
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
}
|
|
190
231
|
hasTransform3DRoot(id) {
|
|
191
232
|
return isTransform3DRoot(this.nodes.get(id));
|
|
192
233
|
}
|
|
@@ -238,6 +279,7 @@ class ThreeContext {
|
|
|
238
279
|
*/
|
|
239
280
|
attachVisual(id, object, gameObject) {
|
|
240
281
|
tagObject3D(object, id);
|
|
282
|
+
this.configureObject(object);
|
|
241
283
|
const root = this.nodes.get(id);
|
|
242
284
|
if (isTransform3DRoot(root) && root !== object) {
|
|
243
285
|
if (object.parent !== root) {
|
|
@@ -434,6 +476,8 @@ class ThreeContext {
|
|
|
434
476
|
}
|
|
435
477
|
}
|
|
436
478
|
resize(width, height) {
|
|
479
|
+
this.width = width;
|
|
480
|
+
this.height = height;
|
|
437
481
|
this.camera.aspect = width / height;
|
|
438
482
|
this.camera.updateProjectionMatrix();
|
|
439
483
|
if (this.fallbackCamera !== this.camera) {
|
|
@@ -457,6 +501,33 @@ class ThreeContext {
|
|
|
457
501
|
this.clock = null;
|
|
458
502
|
}
|
|
459
503
|
}
|
|
504
|
+
const MATERIAL_MAPS = [
|
|
505
|
+
'map',
|
|
506
|
+
'alphaMap',
|
|
507
|
+
'aoMap',
|
|
508
|
+
'bumpMap',
|
|
509
|
+
'displacementMap',
|
|
510
|
+
'emissiveMap',
|
|
511
|
+
'lightMap',
|
|
512
|
+
'metalnessMap',
|
|
513
|
+
'normalMap',
|
|
514
|
+
'roughnessMap',
|
|
515
|
+
];
|
|
516
|
+
function configureMaterialTextures(material, apply) {
|
|
517
|
+
const record = material;
|
|
518
|
+
for (const key of MATERIAL_MAPS) {
|
|
519
|
+
const texture = record[key];
|
|
520
|
+
if (texture?.isTexture)
|
|
521
|
+
apply(texture);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
function readAnisotropy(renderer) {
|
|
525
|
+
const capabilities = renderer.capabilities;
|
|
526
|
+
const max = capabilities?.getMaxAnisotropy?.() ?? 0;
|
|
527
|
+
if (!(max > 1))
|
|
528
|
+
return 1;
|
|
529
|
+
return Math.min(8, max);
|
|
530
|
+
}
|
|
460
531
|
function isIdentityPoseObject(transform) {
|
|
461
532
|
const pose = readPose(transform);
|
|
462
533
|
return pose.positionX === 0 && pose.positionY === 0 && pose.positionZ === 0
|
|
@@ -649,18 +720,31 @@ let Renderer3DSystem = class Renderer3DSystem extends System {
|
|
|
649
720
|
constructor() {
|
|
650
721
|
super(...arguments);
|
|
651
722
|
this.name = 'Renderer3DSystem';
|
|
723
|
+
this.adaptive = null;
|
|
724
|
+
this.pauseWhenHidden = true;
|
|
652
725
|
}
|
|
653
726
|
static { this.systemName = 'Renderer3DSystem'; }
|
|
654
727
|
init(params) {
|
|
655
728
|
const opts = params || {};
|
|
656
729
|
const width = opts.width || 750;
|
|
657
730
|
const height = opts.height || 1334;
|
|
731
|
+
const quality = resolveRenderQuality(opts, { adaptivePixelRatio: true });
|
|
732
|
+
this.pauseWhenHidden = quality.pauseWhenHidden;
|
|
733
|
+
this.adaptive = new AdaptivePixelRatio({
|
|
734
|
+
pixelRatio: quality.pixelRatio,
|
|
735
|
+
ceiling: quality.pixelRatioCeiling,
|
|
736
|
+
enabled: quality.adaptivePixelRatio,
|
|
737
|
+
});
|
|
658
738
|
this.threeContext = new ThreeContext({
|
|
659
739
|
canvas: opts.canvas,
|
|
660
740
|
container: opts.container,
|
|
661
741
|
width,
|
|
662
742
|
height,
|
|
663
|
-
antialias:
|
|
743
|
+
antialias: quality.antialias,
|
|
744
|
+
pixelRatio: quality.pixelRatio,
|
|
745
|
+
powerPreference: quality.powerPreference,
|
|
746
|
+
softShadows: opts.softShadows,
|
|
747
|
+
shadowMapSize: opts.shadowMapSize,
|
|
664
748
|
backgroundColor: opts.backgroundColor,
|
|
665
749
|
backgroundAlpha: opts.backgroundAlpha,
|
|
666
750
|
fog: opts.fog,
|
|
@@ -711,8 +795,17 @@ let Renderer3DSystem = class Renderer3DSystem extends System {
|
|
|
711
795
|
}
|
|
712
796
|
this.threeContext?.ensureTransformRoot(gameObject, transform);
|
|
713
797
|
}
|
|
714
|
-
lateUpdate() {
|
|
715
|
-
this.threeContext
|
|
798
|
+
lateUpdate(e) {
|
|
799
|
+
if (!this.threeContext)
|
|
800
|
+
return;
|
|
801
|
+
if (shouldPauseRendering(this.pauseWhenHidden)) {
|
|
802
|
+
this.threeContext.update({ skipDraw: true });
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
const next = this.adaptive?.sample(e?.deltaTime ?? 0);
|
|
806
|
+
if (next != null)
|
|
807
|
+
this.threeContext.setPixelRatio(next);
|
|
808
|
+
this.threeContext.update();
|
|
716
809
|
}
|
|
717
810
|
resize(width, height) {
|
|
718
811
|
this.threeContext?.resize(width, height);
|
|
@@ -732,7 +825,7 @@ var Renderer3DSystem$1 = Renderer3DSystem;
|
|
|
732
825
|
/** Auto-generated by scripts/build-package.mjs — do not edit. */
|
|
733
826
|
Object.assign(Renderer3DSystem$1, {
|
|
734
827
|
packageName: "@combos-fun/plugin-renderer-3d",
|
|
735
|
-
packageVersion: "0.1.
|
|
828
|
+
packageVersion: "0.1.14-beta.1",
|
|
736
829
|
});
|
|
737
830
|
|
|
738
831
|
class Renderer3D extends System {
|
|
@@ -1393,6 +1486,47 @@ Light3DSystem = __decorate([
|
|
|
1393
1486
|
], Light3DSystem);
|
|
1394
1487
|
var Light3DSystem_default = Light3DSystem;
|
|
1395
1488
|
|
|
1489
|
+
const BASIS_TRANSCODER_PATH = 'https://unpkg.com/three@0.172.0/examples/jsm/libs/basis/';
|
|
1490
|
+
const COMPRESSED_EXTENSIONS = [
|
|
1491
|
+
'WEBGL_compressed_texture_astc',
|
|
1492
|
+
'EXT_texture_compression_bptc',
|
|
1493
|
+
'WEBGL_compressed_texture_s3tc',
|
|
1494
|
+
'WEBGL_compressed_texture_etc',
|
|
1495
|
+
];
|
|
1496
|
+
let sharedKtx2 = null;
|
|
1497
|
+
let detectedFor = null;
|
|
1498
|
+
function rendererSupportsCompressedTexture(renderer) {
|
|
1499
|
+
return COMPRESSED_EXTENSIONS.some((name) => renderer.extensions.has(name));
|
|
1500
|
+
}
|
|
1501
|
+
/** One Basis transcoder shared by glTF models and standalone KTX2 images. */
|
|
1502
|
+
function ensureKtx2Loader(renderer) {
|
|
1503
|
+
if (!sharedKtx2) {
|
|
1504
|
+
sharedKtx2 = new KTX2Loader();
|
|
1505
|
+
sharedKtx2.setTranscoderPath(BASIS_TRANSCODER_PATH);
|
|
1506
|
+
}
|
|
1507
|
+
if (renderer && detectedFor !== renderer) {
|
|
1508
|
+
sharedKtx2.detectSupport(renderer);
|
|
1509
|
+
detectedFor = renderer;
|
|
1510
|
+
}
|
|
1511
|
+
return sharedKtx2;
|
|
1512
|
+
}
|
|
1513
|
+
async function loadThreeKtx2(url, renderer) {
|
|
1514
|
+
if (!rendererSupportsCompressedTexture(renderer))
|
|
1515
|
+
return null;
|
|
1516
|
+
try {
|
|
1517
|
+
const texture = await ensureKtx2Loader(renderer).loadAsync(url);
|
|
1518
|
+
const compressed = texture;
|
|
1519
|
+
if (compressed?.isCompressedTexture && compressed.format !== RGBAFormat) {
|
|
1520
|
+
return texture;
|
|
1521
|
+
}
|
|
1522
|
+
texture?.dispose();
|
|
1523
|
+
return null;
|
|
1524
|
+
}
|
|
1525
|
+
catch {
|
|
1526
|
+
return null;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1396
1530
|
async function requireNamedResource(name) {
|
|
1397
1531
|
const trimmed = String(name ?? '').trim();
|
|
1398
1532
|
if (!trimmed) {
|
|
@@ -1404,8 +1538,79 @@ async function requireNamedResource(name) {
|
|
|
1404
1538
|
}
|
|
1405
1539
|
return res;
|
|
1406
1540
|
}
|
|
1541
|
+
function htmlImage(data) {
|
|
1542
|
+
if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement)
|
|
1543
|
+
return data;
|
|
1544
|
+
return null;
|
|
1545
|
+
}
|
|
1546
|
+
function asArrayBuffer(data) {
|
|
1547
|
+
if (data instanceof ArrayBuffer)
|
|
1548
|
+
return data;
|
|
1549
|
+
if (ArrayBuffer.isView(data)) {
|
|
1550
|
+
const view = data;
|
|
1551
|
+
return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
|
|
1552
|
+
}
|
|
1553
|
+
return null;
|
|
1554
|
+
}
|
|
1555
|
+
function loadHtmlImage(url) {
|
|
1556
|
+
return new Promise((resolve, reject) => {
|
|
1557
|
+
const image = new Image();
|
|
1558
|
+
image.crossOrigin = 'anonymous';
|
|
1559
|
+
image.onload = () => resolve(image);
|
|
1560
|
+
image.onerror = () => reject(new Error(`Failed to load image ${url}`));
|
|
1561
|
+
image.src = url;
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
async function textureFromImageElement(image) {
|
|
1565
|
+
let source = image;
|
|
1566
|
+
if (typeof createImageBitmap === 'function') {
|
|
1567
|
+
try {
|
|
1568
|
+
source = await createImageBitmap(image);
|
|
1569
|
+
}
|
|
1570
|
+
catch {
|
|
1571
|
+
source = image;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
const texture = new Texture(source);
|
|
1575
|
+
texture.colorSpace = SRGBColorSpace;
|
|
1576
|
+
texture.needsUpdate = true;
|
|
1577
|
+
if (typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap) {
|
|
1578
|
+
const bitmap = source;
|
|
1579
|
+
const dispose = texture.dispose.bind(texture);
|
|
1580
|
+
texture.dispose = () => {
|
|
1581
|
+
dispose();
|
|
1582
|
+
try {
|
|
1583
|
+
bitmap.close();
|
|
1584
|
+
}
|
|
1585
|
+
catch {
|
|
1586
|
+
// Already closed.
|
|
1587
|
+
}
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
return texture;
|
|
1591
|
+
}
|
|
1592
|
+
async function loadCompressed(res, renderer) {
|
|
1593
|
+
if (!renderer)
|
|
1594
|
+
return null;
|
|
1595
|
+
const buffer = asArrayBuffer(res.data?.image);
|
|
1596
|
+
if (!buffer)
|
|
1597
|
+
return null;
|
|
1598
|
+
const url = compressedTextureUrl(res.src?.image);
|
|
1599
|
+
const blobUrl = URL.createObjectURL(new Blob([buffer]));
|
|
1600
|
+
try {
|
|
1601
|
+
const texture = await loadThreeKtx2(blobUrl, renderer);
|
|
1602
|
+
if (texture)
|
|
1603
|
+
return texture;
|
|
1604
|
+
}
|
|
1605
|
+
finally {
|
|
1606
|
+
URL.revokeObjectURL(blobUrl);
|
|
1607
|
+
}
|
|
1608
|
+
if (!url)
|
|
1609
|
+
return null;
|
|
1610
|
+
return loadThreeKtx2(url, renderer);
|
|
1611
|
+
}
|
|
1407
1612
|
function textureFromResourceImage(res) {
|
|
1408
|
-
const image = res.data?.image;
|
|
1613
|
+
const image = htmlImage(res.data?.image);
|
|
1409
1614
|
if (!image) {
|
|
1410
1615
|
throw new Error(`Resource "${res.name}" has no image data; use RESOURCE_TYPE.IMAGE with src.image.url`);
|
|
1411
1616
|
}
|
|
@@ -1414,11 +1619,29 @@ function textureFromResourceImage(res) {
|
|
|
1414
1619
|
texture.needsUpdate = true;
|
|
1415
1620
|
return texture;
|
|
1416
1621
|
}
|
|
1417
|
-
async function
|
|
1622
|
+
async function textureFromResourceImageAsync(res, renderer) {
|
|
1623
|
+
const compressed = await loadCompressed(res, renderer);
|
|
1624
|
+
if (compressed)
|
|
1625
|
+
return compressed;
|
|
1626
|
+
const image = htmlImage(res.data?.image);
|
|
1627
|
+
if (image)
|
|
1628
|
+
return textureFromImageElement(image);
|
|
1629
|
+
const fallback = imageFallbackUrl(res.src?.image);
|
|
1630
|
+
if (fallback) {
|
|
1631
|
+
try {
|
|
1632
|
+
return textureFromImageElement(await loadHtmlImage(fallback));
|
|
1633
|
+
}
|
|
1634
|
+
catch {
|
|
1635
|
+
// The message below reports the missing image.
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
throw new Error(`Resource "${res.name}" has no image data; use RESOURCE_TYPE.IMAGE with src.image.url`);
|
|
1639
|
+
}
|
|
1640
|
+
async function textureFromNamedImage(name, renderer) {
|
|
1418
1641
|
// Always build a Three.Texture from data.image so 2D Pixi
|
|
1419
1642
|
// registerInstance(IMAGE) is never overwritten or reused.
|
|
1420
|
-
return
|
|
1643
|
+
return textureFromResourceImageAsync(await requireNamedResource(name), renderer);
|
|
1421
1644
|
}
|
|
1422
1645
|
|
|
1423
|
-
export { COMBOS_GAME_OBJECT_ID, COMBOS_TRANSFORM3D, Camera3D, Camera3DSystem_default as Camera3DSystem, Light3D, Light3DSystem_default as Light3DSystem, Render3D, Render3DSystem_default as Render3DSystem, Renderer3D, Renderer3DManager, Renderer3DSystem$1 as Renderer3DSystem, ThreeContext, Transform3D, Transform3DSystem_default as Transform3DSystem, VisualPoseBridge, copyPose, gameObjectIdFromIntersection, gameObjectIdFromObject3D, has3DChildGameObjects, is3DSceneParent, isIdentityPose, isTransform3DRoot, poseKeyOf, readPose, requireNamedResource, seedTransform3D, tagObject3D, textureFromNamedImage, textureFromResourceImage };
|
|
1646
|
+
export { COMBOS_GAME_OBJECT_ID, COMBOS_TRANSFORM3D, Camera3D, Camera3DSystem_default as Camera3DSystem, Light3D, Light3DSystem_default as Light3DSystem, Render3D, Render3DSystem_default as Render3DSystem, Renderer3D, Renderer3DManager, Renderer3DSystem$1 as Renderer3DSystem, ThreeContext, Transform3D, Transform3DSystem_default as Transform3DSystem, VisualPoseBridge, copyPose, ensureKtx2Loader, gameObjectIdFromIntersection, gameObjectIdFromObject3D, has3DChildGameObjects, is3DSceneParent, isIdentityPose, isTransform3DRoot, loadThreeKtx2, poseKeyOf, readPose, rendererSupportsCompressedTexture, requireNamedResource, seedTransform3D, tagObject3D, textureFromNamedImage, textureFromResourceImage, textureFromResourceImageAsync };
|
|
1424
1647
|
//# sourceMappingURL=plugin-renderer-3d.esm.js.map
|