@vvfx/sdk 0.0.0-alpha.5 → 0.0.0-alpha.6

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/index.js CHANGED
@@ -1 +1 @@
1
- var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=t=>{throw TypeError(t)},a=(e,i)=>{for(var s in i)t(e,s,{get:i[s],enumerable:!0})},n=(r,a,n,o)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let h of i(a))s.call(r,h)||h===n||t(r,h,{get:()=>a[h],enumerable:!(o=e(a,h))||o.enumerable});return r},o=(t,e,i)=>(n(t,e,"default"),i&&n(i,e,"default")),h=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),c=(t,e,i)=>e.has(t)||r("Cannot "+i),l=(t,e,i)=>(c(t,e,"read from private field"),i?i.call(t):e.get(t)),p=(t,e,i)=>e.has(t)?r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),m=(t,e,i,s)=>(c(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i);import d from"jszip";var u={};a(u,{Composition:()=>P,EventEmitter:()=>v,Player:()=>w,SpriteComponent:()=>b,TextComponent:()=>S,VFXItem:()=>f,assertExist:()=>D,math:()=>x,spec:()=>g});var y={};a(y,{Composition:()=>P,EventEmitter:()=>v,Player:()=>w,SpriteComponent:()=>b,TextComponent:()=>S,VFXItem:()=>f,assertExist:()=>D,math:()=>x,spec:()=>g}),o(y,I);import{spec as g,VFXItem as f,Player as w,math as x,Composition as P,EventEmitter as v,assertExist as D,SpriteComponent as b,TextComponent as S}from"@galacean/effects";import*as I from"@galacean/effects-plugin-rich-text";o(u,y);import{Application as T}from"@pixi/app";var E=class{constructor(){h(this,"interactive"),h(this,"type"),h(this,"active"),this.type="null",this.active=!1,this.interactive=!1}},A=1e-6;function C(t,e,i){const s=isNaN(e)?-1/0:e,r=isNaN(i)?1/0:i,a=Math.min(s,r),n=Math.max(s,r);return Math.min(Math.max(t,a),n)}var M=Math.PI/180,k=180/Math.PI;function V(t){return Math.atan2(-t.y,-t.x)+Math.PI}function z(t,e){return Math.abs(t-e)<A||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function _(t){return isNaN(t)||Math.abs(t)<A}var F=class t extends x.Vector2{subtract(t){return this.x-=t.x,this.y-=t.y,this}toViewCoordinate(t,e){return this.x=(this.x+1)/2*t,this.y=(1-(this.y+1)/2)*e,this}clone(){return new t(this.x,this.y)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}scaleByCenter(e,i=new t){const s=(new t).subtractVectors(i,this).multiply(e);return(new t).subtractVectors(i,s)}round(t=0){const e=Math.pow(10,t);return this.x=Math.round(this.x*e)/e,this.y=Math.round(this.y*e)/e,this}},R=class t{constructor(t=new F,e=new F){h(this,"start",new F),h(this,"end",new F),this.start.copyFrom(t),this.end.copyFrom(e)}set(t,e){return this.start.copyFrom(t),this.end.copyFrom(e),this}copyFrom(t){return this.start.copyFrom(t.start),this.end.copyFrom(t.end),this}direction(){return(new F).subtractVectors(this.end,this.start).normalize()}getCenter(t=new F){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new F){return t.subtractVectors(this.end,this.start)}distanceSq(){return this.start.distanceSquared(this.end)}distance(){return this.start.distance(this.end)}at(t,e=new F){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new F,s=new F;i.subtractVectors(t,this.start),s.subtractVectors(this.end,this.start);const r=s.dot(s);let a=s.dot(i)/r;return e&&(a=C(a,0,1)),a}closestPointToPoint(t,e,i=new F){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiply(s).add(this.start)}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new t).copyFrom(this)}length(){return(new F).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new F).subtractVectors(t.start,this.start),r=(new F).subtractVectors(t.end,this.start),a=(new F).subtractVectors(this.start,t.start),n=(new F).subtractVectors(this.end,t.start),o=s.cross(e),h=r.cross(e),c=a.cross(i),l=n.cross(i);return o*h<0&&c*l<0}},K=class t{constructor(t=new F(1/0,1/0),e=new F(-1/0,-1/0)){h(this,"corners",[]),h(this,"min",new F(1/0,1/0)),h(this,"max",new F(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[t.clone(),new F(e.x,t.y),e.clone(),new F(t.x,e.y)]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[t.clone(),new F(e.x,t.y),e.clone(),new F(t.x,e.y)],this}setFromVec2Array(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min.min(t),this.max.max(t),this.corners.push(t.clone())}),this}setFromVec2ArrayWithOutCorners(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new F(this.min.x,this.min.y)),this.corners.push(new F(this.min.x,this.max.y)),this.corners.push(new F(this.max.x,this.max.y)),this.corners.push(new F(this.max.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new F).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[this.min.clone(),new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y)],this}clone(){return(new t).copyFrom(this)}copyFrom(t){return this.corners=[],this.min.copyFrom(t.min),this.max.copyFrom(t.max),t.corners.forEach(t=>{this.corners.push(t.clone())}),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this.corners=[],this}isEmpty(){return this.max.x<=this.min.x||this.max.y<=this.min.y}getCorners(){const t=[];return this.corners.forEach(e=>{t.push(e.clone())}),t}getCenter(t=new F){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new F){return this.isEmpty()?t.set(0,0):t.subtractVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.subtract(t),this.max.add(t),this}expandByScalar(t){return this.min.add(-t),this.max.add(t),this}containsPoint(t,e=!0){if(e)return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y);if(this.isEmpty())return!1;for(let e=0;e<this.corners.length;e++){const i=this.corners[e],s=this.corners[(e+1)%4],r=new F(s.x-i.x,s.y-i.y),a=new F(t.x-i.x,t.y-i.y);if(r.cross(a)<0)return!1}return!0}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e=new F){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}clampPoint(t,e=new F){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new F).copyFrom(t).clamp(this.min,this.max).subtract(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.min.x>this.max.x||this.min.y>this.max.y?this.makeEmpty():this}union(t){return this.min.min(t.min),this.max.max(t.max),this.corners=[this.min.clone(),new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y)],this}translate(t){return this.min.add(t),this.max.add(t),this.corners.forEach(e=>{e.add(t)}),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}intersectsBox(t,e=!0){if(e)return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y);if(!this.isEmpty())for(let e=0;e<this.corners.length;e++){const i=new R(this.corners[e],this.corners[(e+1)%4]);if(t.containsPoint(this.corners[e],!1))return!0;for(let e=0;e<t.corners.length;e++){const s=new R(t.corners[e],t.corners[(e+1)%4]);if(this.containsPoint(t.corners[e],!1))return!0;if(i.crossWithLine(s))return!0}}for(let e=0;e<t.corners.length;e++){const i=this.containsPoint(t.corners[e],!1),s=t.containsPoint(this.corners[e],!1);if(i||s)return!0}return!1}},U=class t{constructor(t=new F,e=0){h(this,"center"),h(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new F).copyFrom(t),this.radius=e,this}clone(){return(new t).copy(this)}copy(t){return this.center.copyFrom(t.center),this.radius=t.radius,this}makeEmpty(){return this.center=new F,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new F){return t.copyFrom(this.center),t}getRadius(){return this.radius}expandByPoint(t){return this.radius=this.center.distanceTo(t),this}expandByScalar(t){return this.radius+=t,this}containsPoint(t){return this.center.distanceTo(t)<this.radius}containsBox(t){for(let e=0;e<4;e++)if(!this.containsPoint(t.corners[e]))return!1;return!0}intersectsBox(t){for(let e=0;e<4;e++)if(this.containsPoint(t.corners[e]))return!0;return!1}distanceToPoint(t){return this.center.distanceTo(t)-this.radius}},B=class extends x.Quaternion{},W=class t extends x.Vector3{clone(){return new t(this.x,this.y,this.z)}setFromMatrixColumn(t,e){return this.set(...t.elements.slice(4*e))}applyEuler(t,e){return this.applyQuaternion((new B).setFromEuler(t))}applyQuaternion(e,i=new t){const{x:s,y:r,z:a,w:n}=e,{x:o,y:h,z:c}=this.subtract(i),l=n*o+r*c-a*h,p=n*h+a*o-s*c,m=n*c+s*h-r*o,d=-s*o-r*h-a*c;return this.x=l*n+d*-s+p*-a-m*-r+i.x,this.y=p*n+d*-r+m*-s-l*-a+i.y,this.z=m*n+d*-a+l*-r-p*-s+i.z,this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}applyMatrix(e,i=new t){const s=e.elements,{x:r,y:a,z:n}=this.subtract(i);let o=1/(s[3]*r+s[7]*a+s[11]*n+s[15]);return o=isNaN(o)?1:o,this.x=(s[0]*r+s[4]*a+s[8]*n+s[12])*o+i.x,this.y=(s[1]*r+s[5]*a+s[9]*n+s[13])*o+i.y,this.z=(s[2]*r+s[6]*a+s[10]*n+s[14])*o+i.z,this}},G=class t extends x.Matrix4{static fromArray(e,i=0){return(new t).setFromArray(e,i)}clone(){const e=this.elements;return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}compose(t,e,i,s=W.ZERO){const r=this.elements,{x:a,y:n,z:o,w:h}=e,c=-s.x,l=-s.y,p=-s.z,m=a+a,d=n+n,u=o+o,y=a*m,g=a*d,f=a*u,w=n*d,x=n*u,P=o*u,v=h*m,D=h*d,b=h*u,{x:S,y:I,z:T}=i;return r[0]=(1-(w+P))*S,r[1]=(g+b)*S,r[2]=(f-D)*S,r[3]=0,r[4]=(g-b)*I,r[5]=(1-(y+P))*I,r[6]=(x+v)*I,r[7]=0,r[8]=(f+D)*T,r[9]=(x-v)*T,r[10]=(1-(y+w))*T,r[11]=0,r[12]=c*r[0]+l*r[4]+p*r[8]-c+t.x,r[13]=c*r[1]+l*r[5]+p*r[9]-l+t.y,r[14]=c*r[2]+l*r[6]+p*r[10]-p+t.z,this}extractRotation(t){const e=new W,i=t.elements,s=this.elements,r=1/e.setFromMatrixColumn(t,0).length(),a=1/e.setFromMatrixColumn(t,1).length(),n=1/e.setFromMatrixColumn(t,2).length();return s[0]=i[0]*r,s[1]=i[1]*r,s[2]=i[2]*r,s[3]=0,s[4]=i[4]*a,s[5]=i[5]*a,s[6]=i[6]*a,s[7]=0,s[8]=i[8]*n,s[9]=i[9]*n,s[10]=i[10]*n,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,a=Math.cos(i),n=Math.sin(i),o=Math.cos(s),h=Math.sin(s),c=Math.cos(r),l=Math.sin(r);if(t.order===x.EulerOrder.XYZ){const t=a*c,i=a*l,s=n*c,r=n*l;e[0]=o*c,e[4]=-o*l,e[8]=h,e[1]=i+s*h,e[5]=t-r*h,e[9]=-n*o,e[2]=r-t*h,e[6]=s+i*h,e[10]=a*o}else if(t.order===x.EulerOrder.YXZ){const t=o*c,i=o*l,s=h*c,r=h*l;e[0]=t+r*n,e[4]=s*n-i,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-n,e[2]=i*n-s,e[6]=r+t*n,e[10]=a*o}else if(t.order===x.EulerOrder.ZXY){const t=o*c,i=o*l,s=h*c,r=h*l;e[0]=t-r*n,e[4]=-a*l,e[8]=s+i*n,e[1]=i+s*n,e[5]=a*c,e[9]=r-t*n,e[2]=-a*h,e[6]=n,e[10]=a*o}else if(t.order===x.EulerOrder.ZYX){const t=a*c,i=a*l,s=n*c,r=n*l;e[0]=o*c,e[4]=s*h-i,e[8]=t*h+r,e[1]=o*l,e[5]=r*h+t,e[9]=i*h-s,e[2]=-h,e[6]=n*o,e[10]=a*o}else if(t.order===x.EulerOrder.YZX){const t=a*o,i=a*h,s=n*o,r=n*h;e[0]=o*c,e[4]=r-t*l,e[8]=s*l+i,e[1]=l,e[5]=a*c,e[9]=-n*c,e[2]=-h*c,e[6]=i*l+s,e[10]=t-r*l}else if(t.order===x.EulerOrder.XZY){const t=a*o,i=a*h,s=n*o,r=n*h;e[0]=o*c,e[4]=-l,e[8]=h*c,e[1]=t*l+r,e[5]=a*c,e[9]=i*l-s,e[2]=s*l-i,e[6]=n*c,e[10]=r*l+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setPosition(t){return this.elements[12]=t.x,this.elements[13]=t.y,this.elements[14]=t.z,this}},N=class extends x.Euler{constructor(t=0,e=0,i=0,s=x.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new G).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*k,this.y*k,this.z*k):new W(this.x*k,this.y*k,this.z*k)}setFromDegreeVector3(t,e){return this.set(t.x*M,t.y*M,t.z*M,e??this.order)}},O=class{constructor(t=new W,e=new W){h(this,"start"),h(this,"end"),this.start=t.clone(),this.end=e.clone()}closestPointToPointParameter(t,e=!1){const i=(new W).subtractVectors(t,this.start),s=(new W).subtractVectors(this.end,this.start),r=s.dot(s);let a=s.dot(i)/r;return e&&(a=C(a,0,1)),a}closestPointToPoint(t,e=!1){const i=this.closestPointToPointParameter(t,e);return this.delta().multiply(i).add(this.start)}delta(){return(new W).subtractVectors(this.end,this.start)}},L=class t{constructor(t=0,e=new W(0,0,1)){h(this,"distance"),h(this,"normal");const i=e.length();0===i&&(this.normal=new W(0,0,1)),this.distance=t/(i??1),this.normal=e.normalize()}static set(e,i){return new t(e,i)}set(t,e){const i=e.length();return 0===i&&(this.normal=new W(0,0,1)),this.distance=t/i,this.normal=e.normalize(),this}static copy(e){return new t(e.distance,e.normal.clone())}copy(t){return this.distance=t.distance,this.normal.copyFrom(t.normal),this}static setFromNormalAndCoplanarPoint(e,i){const s=-e.dot(i);return new t(s,i)}setFromNormalAndCoplanarPoint(t,e){return this.normal.copyFrom(e),this.distance=-t.dot(this.normal),this}clone(){return new t(this.distance,this.normal.clone())}distanceToPoint(t){return this.normal.dot(t)+this.distance}},j=class t extends x.Ray{constructor(t=new W,e=new W(1,0,0)){super(t,e),h(this,"origin"),h(this,"direction"),this.origin=t.clone(),this.direction=e.clone()}clone(){return new t(this.origin,this.direction)}rayCastPlane(t,e){const i=this.distanceToPlane(t);return isNaN(i)||this.at(i),i}at(t){return this.direction.clone().normalize().multiply(t).add(this.origin)}distanceToPlane(t){const e=t.normal.dot(this.direction);if(_(e))return _(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},H=class{constructor(t=new j){h(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new W(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new W,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},Y=.01,$=2,X=37375,J=6,q=3,Z=15425024,Q=16777215,tt=.17,et=16777215,it=.78,st=1,rt=16711680,at=1,nt=1.5,ot=16777215,ht=0,ct=1,lt=.3,pt=4,mt=8,dt=16711680,ut=1,yt=0,gt=.17,ft=16711680,wt=.15,xt=class extends E{constructor(t){super(),h(this,"defaultInteractive",!0),h(this,"interactive",!0),h(this,"lastPoint",new F),h(this,"SDKUtils"),this.SDKUtils=t,this.type="control"}initialize(){}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(){}action(t){const{metaKey:e,ctrlKey:i,shiftKey:s}=t;if(0===t.buttons){const{deltaX:r,deltaY:a}=t,n=new F(r,a);e||i?(n.y=C(n.y,-10,10),this.dolly(n.y)):(n.x=s&&0!==n.y?Math.sqrt(n.x**2+n.y**2)*n.y/Math.abs(n.y):n.x,n.y=s?0:n.y,this.pan(n.multiply(-1)))}}endAction(){}interruption(){return this.type}actionKey(){}endActionKey(){}dolly(t){const e=-t*Y;this.SDKUtils.pageZoom(e)}pan(t){this.SDKUtils.pageMove(t)}getRenderObjects(){return[]}};import{Graphics as Pt}from"@pixi/graphics";var vt=class extends E{constructor(t){super(),h(this,"interactive",!0),h(this,"result",{type:"null",box:new K}),h(this,"selectedItemIds",[]),h(this,"cursorPoint",new F),h(this,"startPoint",new F),h(this,"graphics",new Pt),h(this,"SDKUtils"),h(this,"clearResult",!1),h(this,"type"),this.SDKUtils=t,this.type="selector"}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return this.clearResult?(this.result={type:"null",box:new K},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics])}cancelPreparation(){this.result.type="null",this.SDKUtils.clearPreSelectedItem()}preparationAction(t){this.result.box=new K;const e=new F(t.offsetX,t.offsetY);this.selectedItemIds=this.hitTest(e);const i=this.selectedItemIds[0]??"";return i.length&&!this.SDKUtils.isItemSelected(i)?this.SDKUtils.addPreSelectedItem(i):this.SDKUtils.clearPreSelectedItem(),this.type}preAction(t){if(this.SDKUtils.clearPreSelectedItem(),1===t.buttons)return t.shiftKey||this.SDKUtils.clearSelectedItems(),0===this.selectedItemIds.length?(this.startPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),this.active=!0,this.type):(this.SDKUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0,"transform")}action(t){const e=(new F).addVectors(this.cursorPoint,(new F).subtractVectors(new F(t.clientX,t.clientY),this.startPoint)),i=(new F).subtractVectors(this.cursorPoint,e),s=(new F).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new K).setFromCenterAndSize(s,i);this.result.type="region",this.result.box=r,this.SDKUtils.clearSelectedItems();const a=this.SDKUtils.getPageData().items?.filter(t=>this.SDKUtils.getItemEditEnable(t.id)),n=[];a?.forEach(t=>{r.intersectsBox(this.SDKUtils.getViewBoxById(t.id),!1)&&n.push(t.id)}),this.SDKUtils.addSelectedItems(n)}endAction(){this.active=!1,this.result.type="null"}interruption(){this.active=!1,this.result.type="null"}hitTest(t){const e=this.SDKUtils.getCurrentComposition();if(!e||null===e.items)return[];const{x:i,y:s}=this.SDKUtils.getViewportByViewPoint(t),r={ray:new j,regions:[]};try{r.regions=e.hitTest(i,s,!0),r.ray=e.getHitTestRay(i,s)}catch(t){console.warn(t)}return this.reorderHitTestResult(r,e).filter(t=>"extra-camera"!==t&&this.SDKUtils.getItemEditEnable(t))}reorderHitTestResult(t,e){if(0===t.regions.length||!e)return[];const{ray:i}=t,s=t.regions.reverse(),r=[];return s.forEach(t=>{let s;const a=(t,e)=>{for(const i of t){if(i.id===e&&(s=i),s)return;a(i.children,e)}};if(a(e.items,t.id),void 0===s)return;const n="rootItem"===t.compContent?.name?s.id:t.compContent.id,o=i.origin.clone().distance(t.position.clone());if((s.type===g.ItemType.mesh||s.content&&"renderer"in s.content&&s.content.renderer&&"occlusion"in s.content.renderer&&s.content.renderer.occlusion)&&r.length>0){let t=!0;r.forEach((e,i)=>{if(t)return o<=e[1]?(r.splice(i,0,[n,o]),void(t=!1)):void(i===r.length-1&&r.push([n,o]))})}else r.push([n,o])}),r.map(t=>t[0])}refreshResults(){const{box:t}=this.result;this.graphics.clear();const e=this.SDKUtils.getPreSelectedItem(),i=this.SDKUtils.getViewBoxById(e?.id??"");if(i?.isEmpty()||(this.graphics.lineStyle(q,Z),this.graphics.drawBox(i)),!t.isEmpty()&&"region"===this.result.type)this.graphics.lineStyle(st,et,it),this.graphics.drawBox(t),this.graphics.beginFill(Q,tt),this.graphics.fillBox(t),this.graphics.endFill()}};import{Graphics as Dt}from"@pixi/graphics";import{assertExist as bt}from"@galacean/effects";var St=class extends E{constructor(t,e){super(),h(this,"type"),h(this,"interactive",!0),h(this,"wireframe"),h(this,"cursorResult",{type:"normal",angle:0}),h(this,"cursorPoint",new F),h(this,"lastPoint",new F),h(this,"rotationAngle",0),h(this,"active",!1),h(this,"enableAdsorption",!0),h(this,"scaleParam"),h(this,"activeType","null"),h(this,"lastWorldPosition",new W),h(this,"SDKUtils"),h(this,"adsorptionGizmo"),h(this,"graphics",new Dt),this.type="transform",this.SDKUtils=t,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new F,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,box:new K,totalBox:new K,childrenBoxes:[],activeType:"null",interactiveDirection:new F,scaleCorner:new F,scaleEdgeCorners:[]}}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return this.refreshRenderObject(),[this.graphics]}cancelPreparation(){this.active=!1,this.wireframe.activeType="null"}preAction(t,e=!1){if(this.active=1===t.buttons,this.lastPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),1===t.buttons)return this.active=!0,"null"===this.wireframe.activeType&&(this.wireframe.activeType="translation"),this.initInteractionPlane(this.cursorPoint),this.lastWorldPosition=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint)??new W,this.activeType=e?"null":this.activeType,this.type}preparationAction(t){const e=new F(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;return this.refreshCursorResult(this.activeType,V(s)),this.active="null"!==this.activeType,this.active?this.type:void 0}action(t){this.active||(this.active=!0,this.refreshWireframeBySelectedItems(),this.wireframe.activeType="translation",this.lastPoint.set(t.clientX,t.clientY),this.cursorPoint.set(t.offsetX,t.offsetY),this.initInteractionPlane(this.cursorPoint),this.lastWorldPosition=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint)??new W);const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);if(!this.wireframe.interactive)return;const s=this.SDKUtils.getSelectedItems(),{anchor:r,activeType:a,interactiveDirection:n}=this.wireframe,o=this.SDKUtils.getPageData();bt(o);let h=0;switch(a){case"rotation":{const t=r.clone(),e=new W,a=function(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}(function(t,e){const i=Math.min(Math.max(t.dot(e)/t.length()/e.length(),-1),1);let s=Math.acos(i);return s=t.x*e.y-t.y*e.x>0?s:-s,s}((new F).subtractVectors(this.cursorPoint,t),(new F).subtractVectors(this.cursorPoint.add(i),t))*k,3);e.z=a,this.rotationAngle+=a,h=V(n)+this.rotationAngle*M,s.forEach(t=>{this.SDKUtils.rotateItem(t.id,e)});break}case"translation":{const t=i.clone();if(this.enableAdsorption){const e=o.items.map(t=>!s.find(e=>e.id===t.id)&&0===s.filter(e=>t.parentId&&t.parentId===e.id).length&&this.SDKUtils.getItemEditEnable(t.id)?this.SDKUtils.getViewBoxById(t.id):new K).filter(t=>!t.isEmpty()),i=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);t.add(i).subtract(r)}const e=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(t));if(e){const t=e.clone().subtract(this.lastWorldPosition).divide(o.property.zoom);s.forEach(e=>{e.type!==g.ItemType.camera&&this.SDKUtils.moveItem(e.id,t)}),this.lastWorldPosition.copyFrom(e)}break}case"scale":{this.cursorPoint.add(i);const t=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint);if(i.length()&&t&&this.scaleParam){const{corner:e,center:i,shift:r,lastScalar:n}=this.scaleParam,o=this.SDKUtils.getSelectedItems()[0]??void 0,h=this.SDKUtils.getItemTransformById(o?.id??""),c=(new G).extractRotation(h.matrix).invert(),l=(new W).subtractVectors(e,i).applyMatrix(c),p=l.clone().multiply(n),m=t.subtract(r).subtract(i).applyMatrix(c),d=new W(1,1,1);if("scale"===a){const t=function(t){let e,i=0;return t.forEach((t,s)=>{if(0===s)e=Math.abs(t);else{const r=Math.abs(t);e<r&&(e=r,i=s)}}),i}([z(l.x,0)?1:Math.abs(m.x/l.x),z(l.y,0)?1:Math.abs(m.y/l.y)]),e=m.toArray()[t],i=p.toArray()[t];if(z(n.x,n.y)&&z(n.z,n.x)){const t=z(i,0)?1:Math.abs(e/i);d.set(t,t,t)}else if(0===t){d.x=z(i,0)?1:Math.abs(e/i);const t=l.y*e/l.x;d.y=z(p.y,0)?1:t/p.y;const s=l.z*e/l.x;d.z=z(p.z,0)?1:s/p.z}else if(1===t){d.y=z(i,0)?1:Math.abs(e/i);const t=l.x*e/l.y;d.x=z(p.x,0)?1:t/p.x;const s=l.z*e/l.y;d.z=z(p.z,0)?1:s/p.z}else{d.z=z(i,0)?1:Math.abs(e/i);const t=l.x*e/l.z;d.x=z(p.x,0)?1:t/p.x;const s=l.y*e/l.z;d.y=z(p.y,0)?1:s/p.y}}this.scaleParam.lastScalar.multiply(d),s.forEach(t=>{this.SDKUtils.scaleItem(t.id,d)})}h=V(n);break}}this.refreshCursorResult(a,h),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);this.cursorPoint.add(i);const s=this.wireframe;this.refreshTransformType(this.cursorPoint);const{activeType:r,interactiveDirection:a}=s;this.refreshCursorResult(r,V(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new F,this.lastPoint=new F}interruption(){this.active=!1,this.cursorResult.type="normal",this.adsorptionGizmo.clearAbsorptionResult()}refreshCursorResult(t,e=0){switch(t){case"scale":this.cursorResult={type:"scale",angle:(e+Math.PI/4)*k};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*k};break;case"translation":case"null":this.cursorResult={type:"normal",angle:0}}}refreshResults(){const t=this.wireframe.activeType;this.refreshWireframeBySelectedItems(),t!==this.wireframe.activeType&&this.refreshCursorResult(this.wireframe.activeType),this.wireframe.box.isEmpty()&&this.adsorptionGizmo.clearAbsorptionResult()}initInteractionPlane(t){const e=this.SDKUtils.getSelectedItems();switch(this.wireframe.activeType){case"scale":{const i=1==e.length?e[0]:void 0;let s,r;if(i){const t=this.SDKUtils.getItemTransformById(i.id);s=(new W).setFromMatrixPosition(t.matrix),r=(new N).setFromQuaternion((new B).setFromRotationMatrix(t.matrix))}if(this.SDKUtils.interactionUtils.initInteractionPlane(s,r),["scale"].includes(this.wireframe.activeType)){if(this.scaleParam={shift:new W,center:new W,corner:new W,lastScalar:new W(1,1,1)},this.scaleParam.center=s,["scale"].includes(this.wireframe.activeType)&&this.wireframe.scaleCorner)this.scaleParam.corner=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.wireframe.scaleCorner)??new W;else if(this.wireframe.scaleEdgeCorners){const t=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.wireframe.scaleEdgeCorners[0])??new W,e=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.wireframe.scaleEdgeCorners[1])??new W,i=t.applyEuler(r??new N,this.scaleParam.center),s=e.applyEuler(r??new N,this.scaleParam.center),a=new O(i,s).closestPointToPoint(this.scaleParam.center);this.scaleParam.corner=a.applyMatrix((r??new N).getInvertMatrixByEuler(),this.scaleParam.center)}this.scaleParam.shift=(this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(t)??new W).subtract(this.scaleParam.corner)}break}case"translation":case"rotation":this.SDKUtils.interactionUtils.initInteractionPlane()}}refreshRenderObject(){if(this.graphics.clear(),!this.wireframe.box.isEmpty()){this.graphics.lineStyle(nt,rt,at),this.wireframe.edges.forEach(t=>{this.graphics.drawLine(t)});const t=t=>{t.corners.forEach((e,i)=>{const s=new R(e,t.corners[(i+1)%4]);this.graphics.drawLine(s)})};this.wireframe.childrenBoxes.forEach(e=>{t(e)}),this.wireframe.cornerEnable&&(this.graphics.beginFill(ot),this.graphics.lineStyle(ct,ht,lt),this.wireframe.scaleCorners.forEach(t=>{this.graphics.drawCircle(t.center.x,t.center.y,t.radius)}),this.graphics.endFill())}}refreshTransformType(t){this.activeType="null";let e=!0;if(this.wireframe.interactiveDirection=new F,this.wireframe.scaleCorner=void 0,this.wireframe.scaleEdgeCorners=void 0,this.wireframe.cornerEnable&&e&&this.wireframe.totalBox.containsPoint(t)){for(let i=0;i<4;i++){if(this.wireframe.scaleCorners[i].containsPoint(t)){e=!1,this.activeType="scale",this.wireframe.activeType="scale",this.wireframe.scaleCorner=this.wireframe.scaleCorners[i].center.clone(),this.wireframe.interactiveDirection.copyFrom(this.wireframe.scaleCorners[i].center).subtract(this.wireframe.box.getCenter());break}}e&&this.wireframe.box.containsPoint(t,!1)&&(e=!1,this.activeType="translation",this.wireframe.activeType="translation");for(let i=0;i<4;i++){if(this.wireframe.rotationCorners[i].containsPoint(t)&&e){e=!1,this.activeType="rotation",this.wireframe.activeType="rotation",this.wireframe.interactiveDirection.copyFrom(this.wireframe.rotationCorners[i].center).subtract(this.wireframe.box.getCenter());break}}}}refreshWireframeBySelectedItems(){const t=this.SDKUtils.getSelectedItems(),e=new K;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],t.length>1)t.forEach(t=>{if(this.SDKUtils.getItemShow(t.id)){const i=this.SDKUtils.getViewBoxById(t.id);e.union(i),this.wireframe.childrenBoxes.push((new K).copyFrom(i).expandByScalar(1))}}),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=!0;else if(1===t.length){const i=t[0];if(this.SDKUtils.getItemShow(i.id)){const t=this.SDKUtils.getViewBoxById(i.id);e.copyFrom(t),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=i.type!==g.ItemType.mesh&&this.SDKUtils.getItemEditEnable(i.id)}}const i=e.isEmpty(),s=i?0:1,r=i?0:16;this.wireframe.activeType=t.length?this.wireframe.activeType:"null",this.wireframe.box.copyFrom(e).expandByScalar(s),this.wireframe.totalBox.copyFrom(e).expandByScalar(r);const a=this.wireframe.box.corners;a.forEach((t,e)=>{this.wireframe.edges.push(new R((new F).copyFrom(t),(new F).copyFrom(a[(e+1)%4])))}),this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new U(t,pt));const e=(new F).subtractVectors(t,this.wireframe.box.getCenter()),i=(new F).copyFrom(this.wireframe.box.getCenter()).add((new F).copyFrom(e).normalize().multiply(e.length()+mt-pt));this.wireframe.rotationCorners.push(new U(i,mt))})}setAdsorptionEnabled(t){this.enableAdsorption=t}};import{Graphics as It}from"@pixi/graphics";var Tt=class extends E{constructor(){super(),h(this,"interactive",!1),h(this,"results",[]),h(this,"graphics",new It),h(this,"absorptionResult",{}),this.type="adsorption"}initialize(){}preparationAction(){}getCursorState(){}preAction(){}action(){}cancelPreparation(){}actionKey(){}endActionKey(){}endAction(){}interruption(){}boxTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],e.isEmpty())return;const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),n=e.clone().translate(a),o=n.getCenter();this.absorptionResult={},i.forEach(t=>{if(t.isEmpty())return;t.corners.forEach(t=>{n.corners.forEach(e=>{this.getPointAbsorption(e,t,s,r)}),this.getPointAbsorption(o,t,s,r)});const e=t.getCenter();this.getPointAbsorption(o,e,s,r),n.corners.forEach(t=>{this.getPointAbsorption(t,e,s,r)})})}pointTranslationAdsorption(t,e,i,s=!0,r=!0){this.results=[];const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),n=e.clone().add(a);this.absorptionResult={},i.forEach(t=>{this.getPointAbsorption(n,t,s,r)})}getPointAbsorption(t,e,i=!0,s=!0){i&&Math.abs(t.x-e.x)<J&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<J&&this.refreshPointAbsorptionResult(t,e,"y")}refreshPointAbsorptionResult(t,e,i){const s=t[i]-e[i],r="x"===i?"xPoints":"yPoints";if(this.absorptionResult&&void 0===this.absorptionResult[i])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else if(Math.abs(s)-Math.abs(this.absorptionResult[i]??0)<=.005)if(Math.abs(Math.abs(s)-Math.abs(this.absorptionResult[i]??0))<.05&&s*(this.absorptionResult[i]??0)>0)if(void 0===this.absorptionResult[r])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else{const i=this.absorptionResult[r].filter(e=>e.point.equals(t));void 0===i||0===i.length?this.absorptionResult[r]?.push({point:t,targets:[e]}):i[0]?.targets.push(e)}else this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}]}refreshResults(){if(void 0===this.absorptionResult)return;const{x:t,y:e,xPoints:i,yPoints:s}=this.absorptionResult,r=new F(t??0,e??0);void 0!==t&&void 0!==i&&i.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.x=t.x,i.y=Math.min(i.y,t.y),s.x=t.x,s.y=Math.max(s.y,t.y)}),this.results.push(new R(i,s))}),void 0!==e&&void 0!==s&&s.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.y=t.y,i.x=Math.min(i.x,t.x),s.y=t.y,s.x=Math.max(s.x,t.x)}),this.results.push(new R(i,s))})}refreshRenderObject(){this.graphics.clear(),this.results.forEach(t=>{this.graphics.lineStyle($,X),this.graphics.drawLine(t)})}getRenderObjects(){return this.refreshResults(),this.refreshRenderObject(),[this.graphics]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},Et={};a(Et,{Application:()=>kt,utils:()=>Ct});var At={};a(At,{Application:()=>kt,utils:()=>Ct}),o(At,Rt),o(At,Kt),o(At,Ut),o(At,Bt),o(At,Wt),o(At,Gt),o(At,Nt),o(At,Ot),o(At,Lt),o(At,jt),o(At,Ht),o(At,Yt);import"@pixi/polyfill";import*as Ct from"@pixi/utils";import{InteractionManager as Mt}from"@pixi/interaction";import{Application as kt}from"@pixi/app";import{Renderer as Vt,BatchRenderer as zt}from"@pixi/core";import{AppLoaderPlugin as _t}from"@pixi/loaders";import{TickerPlugin as Ft}from"@pixi/ticker";import*as Rt from"@pixi/constants";import*as Kt from"@pixi/core";import*as Ut from"@pixi/display";import*as Bt from"@pixi/graphics";import*as Wt from"@pixi/loaders";import*as Gt from"@pixi/interaction";import*as Nt from"@pixi/math";import*as Ot from"@pixi/runner";import*as Lt from"@pixi/sprite";import*as jt from"@pixi/text";import*as Ht from"@pixi/ticker";import*as Yt from"@pixi/settings";Ct.skipHello(),Vt.registerPlugin("interaction",Mt),Vt.registerPlugin("batch",zt),kt.registerPlugin(Ft),kt.registerPlugin(_t),At.Graphics.prototype.drawBox=function(t){const e=t.getCorners();this.beginFill();for(let t=0;t<4;t++)this.moveTo(e[t].x,e[t].y),this.lineTo(e[(t+1)%4].x,e[(t+1)%4].y);this.endFill()},At.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},At.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof R)this.moveTo(t.start.x,t.start.y),this.lineTo(t.end.x,t.end.y);else for(let e=0;e<t.length-1;e++)this.moveTo(t[e].x,t[e].y),this.lineTo(t[e+1].x,t[e+1].y);this.endFill()},o(Et,At);var $t=class extends E{constructor(t){super(),h(this,"safeAreaPreview",!1),h(this,"interactive",!1),h(this,"box",new K),h(this,"graphics",new Et.Graphics),h(this,"SDKUtils"),this.SDKUtils=t,this.type="preference"}initialize(){throw new Error("Method not implemented.")}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){this.box=new K;const t=this.SDKUtils.getPageData();D(t);const{container:e}=this.SDKUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new F(s,r).multiply(i),n=this.SDKUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new K).setFromCenterAndSize(n,a)}}setSafeAreaPreviewEnabled(t){this.safeAreaPreview=t}refreshRenderObjects(){this.graphics=new Et.Graphics;const{offsetWidth:t,offsetHeight:e}=this.SDKUtils.container.parentElement,i=new K(new F(0,0),new F(t,this.box.min.y)),s=new K(new F(0,this.box.min.y),new F(this.box.min.x,e)),r=new K(new F(this.box.min.x,this.box.max.y),new F(t,e)),a=new K(new F(this.box.max.x,this.box.min.y),new F(t,this.box.max.y));if(this.graphics.beginFill(yt,gt),this.graphics.fillBox(i),this.graphics.fillBox(s),this.graphics.fillBox(r),this.graphics.fillBox(a),this.graphics.endFill(),this.safeAreaPreview){const t=this.SDKUtils.getPageData();D(t,"You must call SDK#run() first");const{viewProperties:e,activeData:i}=t,s=e[i.view??-1];if(s){const{size:t,safeArea:e}=s,[i,r,a,n]=e.size,o=this.box.getSize(),h=i/t[1]*o.y,c=a/t[0]*o.x,l=n/t[0]*o.x,p=r/t[1]*o.y,{min:m,max:d}=this.box;this.graphics.beginFill(ft,wt);const u=new K(m,new F(d.x,m.y+h)),y=new K(new F(m.x,m.y+h),new F(m.x+c,d.y)),g=new K(new F(d.x-l,m.y+h),new F(d.x,d.y)),f=new K(new F(m.x+c,d.y-p),new F(d.x-l,d.y));this.graphics.fillBox(u),this.graphics.fillBox(y),this.graphics.fillBox(g),this.graphics.fillBox(f),this.graphics.endFill()}}this.graphics.lineStyle(ut,dt),this.graphics.drawBox(this.box)}getRenderObjects(){return this.refreshRenderObjects(),[this.graphics]}},Xt=class{constructor(t){h(this,"wireframeApplication"),h(this,"gizmos",[]),h(this,"activeGizmo"),h(this,"selectorGizmo"),h(this,"transformGizmo"),h(this,"controlGizmo"),h(this,"preferenceGizmo"),h(this,"spaceClickTime"),h(this,"spaceEmit",!1),h(this,"isPlaying",!1),h(this,"clickButtons",0),h(this,"container"),h(this,"clickTime",0),h(this,"firstClick",!0),h(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new T({backgroundAlpha:0,width:e,height:i,resolution:1,antialias:!0}),this.container=t,this.wireframeApplication.view.style.position="absolute",this.wireframeApplication.view.id="wireframeApplicationCanvas",t.appendChild(this.wireframeApplication.view),this.wireframeApplication.stage.sortableChildren=!0,this.registerViewEvent()}resize(){this.wireframeApplication&&(this.wireframeApplication.resizeTo=this.container,this.render())}refresh(){this.gizmos.forEach(t=>{t.refreshResults()})}render(){this.refresh(),this.wireframeApplication.stage.removeChildren();const t=(this.isPlaying?[this.preferenceGizmo]:this.gizmos).flatMap(t=>t.getRenderObjects());this.wireframeApplication.stage.addChild(...t),this.wireframeApplication.render()}init(t){this.gizmos=[],this.controlGizmo=new xt(t),this.selectorGizmo=new vt(t);const e=new Tt;this.transformGizmo=new St(t,e),this.preferenceGizmo=new $t(t),this.gizmos.push(this.transformGizmo,this.selectorGizmo,this.controlGizmo,this.preferenceGizmo,e),this.initEvents()}initEvents(){this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp)}registerViewEvent(){this.wireframeApplication.view.onmousedown=t=>{this.onMouseDown(t)},this.wireframeApplication.view.onmousemove=t=>{0===t.buttons&&this.onMouseMove(t)},this.wireframeApplication.view.onmouseout=()=>{this.selectorGizmo?.cancelPreparation(),this.render()},this.wireframeApplication.view.onwheel=t=>{this.onWheel(t)}}onMouseDown(t){if(this.clickButtons=t.buttons,this.firstClick=!!this.firstClick&&Date.now()-this.clickTime<this.dblclickTimeSpan,this.firstClick){this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.activeGizmo=void 0;const e=this.selectorGizmo?.preAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null")),this.firstClick=!1}else{void 0===this.activeGizmo&&this.gizmos.forEach(e=>{if(!e.interactive||this.activeGizmo)return;const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)});const e=this.activeGizmo?.preAction(t);"selector"!==e&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===e),this.clickTime=Date.now(),this.firstClick=!0}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}onMouseMove(t){0!==t.buttons?this.activeGizmo?.action(t):this.spaceEmit||(this.activeGizmo=void 0,this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);"selector"!==i&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()})),this.render()}onWheel(t){t.preventDefault(),this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.controlGizmo?.action(t)}onMouseUp(t){const e=this.activeGizmo?.endAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===e),void 0===this.activeGizmo&&1===this.clickButtons&&this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.clickButtons=0,this.render(),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}onKeyDown(t){if("space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active)this.gizmos.forEach(e=>{e.actionKey(t)});else{if(this.spaceEmit)return;void 0===this.spaceClickTime?this.spaceClickTime=Date.now():Date.now()-this.spaceClickTime>300&&(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.activeGizmo?.actionKey(t))}this.render()}onKeyUp(t){this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceClickTime=void 0,this.spaceEmit=!1),this.render()}setAdsorptionEnabled(t){this.transformGizmo?.setAdsorptionEnabled(t)}setSafeAreaPreviewEnabled(t){this.preferenceGizmo?.setSafeAreaPreviewEnabled(t)}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}};import{assertExist as Jt}from"@galacean/effects";var qt=class{constructor(t){h(this,"plane",new L),h(this,"ray",new j),h(this,"viewportParam",{width:0,height:0,viewWidth:0,viewHeight:0,panelWidth:0,panelHeight:0,scale:1,ratio:1,translation:new F,rulerWidth:0}),h(this,"cameraParam",{position:new W,rotation:new W,focusPosition:new W,focusRotation:new W,viewProjectionMatrix:new G,inverseViewProjectionMatrix:new G}),h(this,"SDKUtils"),this.SDKUtils=t}refreshViewParam(){const t=this.SDKUtils.getPageData();Jt(t,"You must run SDK first");const e=new F(this.SDKUtils.container.offsetWidth,this.SDKUtils.container.offsetHeight),{zoom:i,translation:s}=t.property;this.viewportParam.width=e.x,this.viewportParam.height=e.y,this.viewportParam.viewWidth=e.x,this.viewportParam.viewHeight=e.y,this.viewportParam.panelWidth=e.x,this.viewportParam.panelHeight=e.y,this.viewportParam.scale=i,this.viewportParam.ratio=1,this.viewportParam.translation=new F(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.SDKUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=G.fromArray(e.getViewProjectionMatrix().toArray()),i=G.fromArray(e.getViewMatrix().toArray()).invert(),s=new B;i.decompose(this.cameraParam.position,s,new W),this.cameraParam.rotation=(new N).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new W(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new N).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new N).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=G.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new N).setFromDegreeVector3(this.cameraParam.rotation));const i=new W(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new N).setFromDegreeVector3(this.cameraParam.rotation):(new N).setFromQuaternion((new B).setFromRotationMatrix(this.SDKUtils.getItemTransformById(i.id).matrix)),r=i?(new W).setFromMatrixPosition(this.SDKUtils.getItemTransformById(i.id).matrix):this.cameraParam.focusPosition,a=this.projectPoint(r.clone()),n=this.getWorldPositionByViewPoint(a.add(t));if(!n)return console.warn("size is out of bounds."),new W(0,0,0);const o=(new N).setFromQuaternion((new B).setFromEuler(s).invert());return(e||!i?n.applyEuler(o,r):n).subtract(r)}projectPoint(t){const{panelWidth:e,panelHeight:i,scale:s}=this.viewportParam,r=this.SDKUtils.getViewportLeftTopPosition();return(new F).copyFrom(t.applyMatrix(this.cameraParam.viewProjectionMatrix).toVector2()).toViewCoordinate(e*s,i*s).add(r)}getWorldPositionByViewPoint(t){const{position:e,inverseViewProjectionMatrix:i}=this.cameraParam,s=this.getViewPositionByScreenPosition(t),r=(new H).setFromCamera(s,{position:e,inverseViewProjectMatrix:i}).rayCastPlane(this.plane);return r?.point}getViewPositionByScreenPosition(t){const{panelWidth:e,panelHeight:i,rulerWidth:s}=this.viewportParam;return new F((t.x-s)/e*2-1,-(t.y-s)/i*2+1)}getScreenSizeByPixelSize(t){const e=this.viewportParam.width/this.viewportParam.viewWidth,i=t.clone();return i.multiply(e||1),i}getPixelSizeByScreenSize(t){const e=this.viewportParam.viewWidth/this.viewportParam.width,i=t.clone();return i.multiply(e||1),i}};import{Texture as Zt}from"@galacean/effects";var Qt=class{constructor(t,e,i,s){h(this,"sdk"),h(this,"player"),h(this,"container"),h(this,"emitter"),h(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new qt(this)}getPageData(){return this.sdk.pageData}getCurrentComposition(){return this.player.getCompositions()[0]}isItemSelected(t){return!!this.sdk.pageData?.activeData.selectedItems?.find(e=>e===t)}getItemEditEnable(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart)}getItemShow(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart||a===g.EndBehavior.freeze)}addSelectedItems(t){var e;D(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.activeData).selectedItems??(e.selectedItems=[]),t.forEach(t=>{var e,i;e=this.sdk.pageData?.activeData.selectedItems??[],i=t,e.includes(i)||e.push(i)}),this.emitter.emit("selectedItemChange",t)}clearSelectedItems(){this.sdk.pageData&&(this.sdk.pageData.activeData.selectedItems=[],this.emitter.emit("selectedItemChange",[]))}getSelectedItems(){const t=this.sdk.pageData?.activeData.selectedItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}addPreSelectedItem(t){D(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){D(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=void 0,this.emitter.emit("preSelectedItemChange",void 0)}getPreSelectedItem(){const t=this.getPageData();D(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}getViewItemById(t){return this.sdk.pageData?.items.find(e=>e.id===t)}getPlayerSizeByParent(t,e){const[i,s]=t,[r,a]=e;let n=s,o=n/a*r;return o>i&&(n=i/o*s,o=i),[o,n]}async loadScene(t){this.player.destroyCurrentCompositions();const e=this.sdk.pageData?.viewProperties[t];if(!e||!this.sdk.pageData)return void console.warn(`This page does not have ${t} view property.`);const{scene:i,size:s}=e,r=this.container.parentElement?.offsetWidth??300,a=this.container.parentElement?.offsetHeight??300,[n,o]=this.getPlayerSizeByParent([r,a],s);this.container.style.width=`${n}px`,this.container.style.height=`${o}px`,this.sdk.pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},this.player.resize();const h=JSON.parse(JSON.stringify(i)),c=await this.player.loadScene(h,{autoplay:!1});this.player.gotoAndStop(this.sdk.pageData.time),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,c.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshPageTime(t){D(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t){var e;D(this.sdk.pageData,"You must call SDK#run() first");const{zoom:i}=this.sdk.pageData.property;(e=this.sdk.pageData.property).zoom??(e.zoom=1);const s=C(t,-.1,.1),r=C(i+s,.3,10);this.sdk.pageData.property.zoom=r,this.container.style.scale=`${r}`,this.emitter.emit("zoomChange",r)}setPageZoom(t){D(this.sdk.pageData,"You must call SDK#run() first");const e=C(t,.3,10);this.sdk.pageData.property.zoom=e,this.container.style.scale=`${e}`,this.emitter.emit("zoomChange",t)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){var e;D(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.property).translation??(e.translation=[0,0]);const i=this.sdk.pageData.property.translation[0]+t.x,s=this.sdk.pageData.property.translation[1]+t.y;this.refreshInteractionParam(),this.container.style.translate=`${i}px ${s}px`,this.emitter.emit("pageDataChange",this.sdk.pageData)}rotateItem(t,e){const i=this.getPlayerItemById(t);i&&(console.log("translation is ",e.toArray()),console.log("playerItem is ",i),i.rotate(...e.toArray()),this.transformSceneItem(t,"rotation",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"rotation"}))}moveItem(t,e){const i=this.getPlayerItemById(t);if(i){const s=(new G).copyFrom(i.transform.getParentMatrix()??new G);s.setPosition(new W);const r=e.clone().applyMatrix(s.invert());console.log("translation is ",r.toArray()),console.log("playerItem is ",i),i.translate(...r.toArray()),this.transformSceneItem(t,"position",r.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"translation"})}}scaleItem(t,e){const i=this.getPlayerItemById(t);i&&(i.scale(...e.toArray()),this.transformSceneItem(t,"scale",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"scale"}))}getItemTransformById(t){const e={matrix:new G,parentMatrix:new G},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=G.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(G.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(G.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new G).toArray()))}return e}addViewItemsByItems(t,e,i){const s=e=>{e.forEach(e=>{t.find(t=>t.id===e.id)||t.push(this.createViewItemByPlayerItem(e,i))})};for(const i of e)s([i]),this.addViewItemsByItems(t,i.children,i.id)}createViewItemByPlayerItem(t,e){D(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s}=t;i.updateLocalMatrix();const r=(new G).copyFrom(s?.transform.getWorldMatrix()??(new G).identity()).invert().multiply(i.getWorldMatrix()),a=new W,n=new B,o=new W;r.decompose(a,n,o);const h=(new N).setFromQuaternion(n).toDegreeVector3();h.x=Number.isNaN(h.x)?0:h.x,h.y=Number.isNaN(h.y)?0:h.y,h.z=Number.isNaN(h.z)?0:h.z;const c={position:a.toArray(),rotation:h.toArray(),scale:o.toArray(),keyPropertyEditing:!1};switch(t.type){case g.ItemType.sprite:{const e=this.getActiveScene()?.scene;if(e){e.components.filter(e=>e.item.id===t.id).forEach(t=>{if(c.keyPropertyEditing||!("renderer"in t)||!("texture"in t.renderer)||!t.renderer.texture)return;const i=e.textures?.find(e=>e.id===t.renderer.texture.id);if(i&&"source"in i&&i.source){const t=e?.images.find(t=>t.id===i.source.id);c.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(c,{image:s})}})}break}case g.ItemType.text:case g.ItemType.richtext:{const e=this.getActiveScene()?.scene;if(c.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.id).forEach(t=>{if(![g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:a}=t.options;Object.assign(c,{alignment:e,color:i,weight:r,text:s,font:a})})}break}}return{id:t.id,name:t.name,parentId:t.parentId??e,children:[],type:t.type,duration:t.duration,delay:t.start,endBehavior:t.endBehavior,property:c}}getViewBoxById(t){const e=new K,i=this.getPlayerItemById(t),s=this.player.getCompositions()[0]?.items.filter(e=>e.parentId===t);return i&&s?this.getViewBoxByPlayerItem(i,s):e}getViewBoxByPlayerItem(t,e){const i=new K;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,n=(new G).copyFrom(r?.transform.getWorldMatrix()??new G).invert().multiply(s.getWorldMatrix()),{x:o,y:h}=a.clone().divide(2),c=new W(o,h,0).applyMatrix(n),l=new W(o,-h,0).applyMatrix(n),p=new W(-o,-h,0).applyMatrix(n),m=new W(-o,h,0).applyMatrix(n),d=this.interactionUtils.projectPoint(c).round(2),u=this.interactionUtils.projectPoint(l).round(2),y=this.interactionUtils.projectPoint(p).round(2),g=this.interactionUtils.projectPoint(m).round(2);i.setFromVec2Array([d,u,y,g]);const f=e?.map(t=>this.getViewBoxById(t.id));f&&f.map(t=>i.union(t));break}case g.ItemType.null:{const t=e?.map(t=>this.getViewBoxById(t.id));t&&t.map(t=>i.union(t));break}}return i}getViewBoxByHeadlessPlayerItem(t,e,i){const s=new K,{transform:r,composition:a}=t;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{r.updateLocalMatrix();const{size:t}=r,n=(new G).copyFrom(a?.transform.getWorldMatrix()??new G).invert().multiply(r.getWorldMatrix()),{x:o,y:h}=t.clone().divide(2),c=new W(o,h,0).applyMatrix(n),l=new W(o,-h,0).applyMatrix(n),p=new W(-o,-h,0).applyMatrix(n),m=new W(-o,h,0).applyMatrix(n),d=i(c).round(2),u=i(l).round(2),y=i(p).round(2),g=i(m).round(2);s.setFromVec2Array([d,u,y,g]);const f=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.id)??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});f&&f.map(t=>s.union(t));break}case g.ItemType.null:{const t=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.id)??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});t&&t.map(t=>s.union(t));break}}return s}getViewportLeftTopPosition(){if(!this.sdk.pageData)return new F;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,n=new F(i,s),o=new F(r,a).multiply(t);return n.clone().divide(2).subtract(o.clone().divide(2)).add(e)}getContainerPosition(){const{offsetWidth:t,offsetHeight:e}=this.container.parentElement;return new F(t/2,e/2).add(new F(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container,r=new F(i,s).multiply(e),a=this.getViewportLeftTopPosition(),n=t.clone().subtract(a);return new F(n.x/r.x*2-1,1-n.y/r.y*2)}getActiveScene(){return this.sdk.pageData?.viewProperties[this.sdk.pageData?.activeData.view??-1]}async changeItemProperty(t){D(this.sdk.pageData,"You must call SDK#run() first");const e=this.getViewItemById(t.itemId),i=this.getPlayerItemById(t.itemId);if(e&&i)if(t.propertyName in e.property){switch(t.propertyName){case"alignment":[g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(S).setTextAlign(t.propertyValue);break;case"color":Array.isArray(t.propertyValue)&&4===t.propertyValue.length&&i.getComponent(S).setColor(t.propertyValue);break;case"font":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0],r=this.player.getAssetManager()[0];await r.processFontURL([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(S).setFontFamily(s)}break;case"text":"string"==typeof t.propertyValue&&i.getComponent(S).setText(t.propertyValue);break;case"weight":[g.TextWeight.normal,g.TextWeight.bold,g.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(S).setFontWeight(t.propertyValue);break;case"image":"string"==typeof t.propertyValue&&i.getComponent(b).setTexture(await Zt.fromImage(t.propertyValue,this.player.renderer.engine));break;case"position":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.position[i]??0));this.moveItem(t.itemId,new W(...i))}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.rotation[i]??0));this.rotateItem(t.itemId,new W(...i))}break;case"scale":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const s=t.propertyValue.map(t=>0===t||null===t?1:t),r=e.property.scale.map(t=>t||1),a=s.map((t,e)=>t/r[e]);i.scale(...a),i.transform.updateLocalMatrix()}}["position","rotation","scale"].includes(t.propertyName)||(this.changeViewItemProperty(t),this.player.gotoAndStop(this.sdk.pageData.time),this.refreshViewItem(t.itemId))}else console.warn(`Item does not have property ${t.propertyName}.`);else console.warn(`Id ${t.itemId} is not a item id.`)}changeViewItemProperty(t){D(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((e,i)=>{if(!this.sdk.pageData?.property.sync&&i!==this.sdk.pageData?.activeData.view)return;const{scene:s}=e;switch(t.propertyName){case"position":case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;case"scale":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t/(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;default:this.changeSceneItemProperty(s,t)}}),console.log(this.sdk.pageData)}changeSceneItemProperty(t,e){switch(e.propertyName){case"alignment":if([g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&"textAlign"in i.options&&(i.options.textAlign=e.propertyValue)}break;case"color":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.textColor=[...e.propertyValue])}break;case"font":if("string"==typeof e.propertyValue){const i=e.propertyValue.split("/"),s=i[i.length-1]?.split(".")[0],r=t.fonts?.find(t=>"family"in t&&t.family===s||"fontFamily"in t&&t.fontFamily===s);!r&&t.fonts&&s&&t.fonts.push({fontFamily:s,fontURL:e.propertyValue});const a=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));a?.options&&(a.options.fontFamily=s)}break;case"text":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.text=e.propertyValue)}break;case"weight":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontWeight=e.propertyValue)}break;case"image":if("string"==typeof e.propertyValue){t.components.filter(t=>t.item.id===e.itemId).forEach(i=>{if(!("renderer"in i))return;const s=t.textures?.find(t=>t.id===i.renderer.texture.id);if(s&&"source"in s&&s.source){const i=t?.images.find(t=>t.id===s.source.id);i?.url&&i?.webp&&(i.url=e.propertyValue,i.webp=e.propertyValue),i&&"template"in i&&i.template.background&&(i.template.background.url=e.propertyValue)}})}break;case"position":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.position.x+=e.propertyValue[0],i.transform.position.y+=e.propertyValue[1],i.transform.position.z+=e.propertyValue[2])}break;case"rotation":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.eulerHint.x+=e.propertyValue[0],i.transform.eulerHint.y+=e.propertyValue[1],i.transform.eulerHint.z+=e.propertyValue[2])}break;case"scale":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.scale.x*=e.propertyValue[0],i.transform.scale.y*=e.propertyValue[1],i.transform.scale.z*=e.propertyValue[2])}}}transformSceneItem(t,e,i){D(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((s,r)=>{if(!this.sdk.pageData?.property.sync&&r!==this.sdk.pageData?.activeData.view)return;const{scene:a}=s;switch(e){case"position":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.position.x+=i[0],e.transform.position.y+=i[1],e.transform.position.z+=i[2])}break;case"rotation":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.eulerHint.x+=i[0],e.transform.eulerHint.y+=i[1],e.transform.eulerHint.z+=i[2])}break;case"scale":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.scale.x*=i[0],e.transform.scale.y*=i[1],e.transform.scale.z*=i[2])}}})}refreshViewItem(t){const e=this.sdk.pageData;D(e,"You must call SDK#run() first");const i=e.items.findIndex(e=>e.id===t);if(i<0)return void console.log(`item ${t} is not existed.`);const s=e.items[i],r=this.getPlayerItemById(t);r&&s&&(e.items[i]=this.createViewItemByPlayerItem(r,s.parentId))}getPlayerItemById(t){return this.player.getCompositions()[0]?.items.find(e=>e.id===t)}async keepSceneSafe(t,e,i,s,r){const a=JSON.parse(JSON.stringify(e));await t.loadScene(a,{reusable:!0,autoplay:!1}),t.gotoAndStop(i);const n=t.getCompositions()[0];if(n){const t=(t,e,i)=>{const{z:s}=i.transform.getWorldPosition(),{x:r,y:a}=n.camera.getInverseVPRatio(s);i.transform.translate(2*t*r/m,-2*e*a/d,0)},i=t=>{const e=(new G).copyFrom(n.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(...s)},[a,o]=s,{size:[h,c,l,p]}=r,m=a-l-p,d=o-h-c,u=[m/a,d/o],y=[(l-p)/2,(h-c)/2],g=n.items.filter(t=>t.name.includes("k-")),f=(new K).setFromCenterAndSize(new F(a,o).divide(2).add(new F(...y)),new F(m,d));g.forEach(s=>{const r=n.items.filter(t=>t.parentId===s.id),a=s.transform.position.clone(),o=s.transform.scale.clone();s.scale(...u,1),t(...y,s),s.transform.updateLocalMatrix();const h=this.getViewBoxByHeadlessPlayerItem(s,r,i);if(!f.containsBox(h)){const{min:e,max:i}=h,{min:r,max:a}=f,n=[0,0];n[0]+=e.x<r.x?r.x-e.x:0,n[0]+=i.x>a.x?a.x-i.x:0,n[1]+=e.y<r.y?r.y-e.y:0,n[1]+=i.y>a.y?a.y-i.y:0,t(...n,s),s.transform.updateLocalMatrix()}const c=s.transform.position.clone(),l=s.transform.scale.clone(),p=c.subtract(a).toArray(),m=l.divide(o).toArray(),d=m[0]>m[1]?[m[1],m[1],1]:[m[0],m[0],1];this.changeSceneItemProperty(e,{itemId:s.id,type:s.type,propertyName:"position",propertyValue:p}),this.changeSceneItemProperty(e,{itemId:s.id,type:s.type,propertyName:"scale",propertyValue:d})})}return e}};import te from"jszip";function ee(t,e="asserts failed"){if(!t)throw new Error(e)}function ie(t,e,...i){const s=e.reduce((t,e)=>t?`${t} ${e}`:e,""),r="color: #108ee9;";switch(t){case"error":console.error(`%c[${s}]`,r,...i);break;case"info":console.info(`%c[${s}]`,r,...i);break;case"debug":console.debug(`%c[${s}]`,r,...i);break;case"warn":console.warn(`%c[${s}]`,r,...i);break;default:console.log(`%c[${s}]`,r,...i)}}var se="ready",re="executable",ae="dispose",ne={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},oe="idle",he="convertImage",ce="transcoding",le="audio",pe="jpeg",me="webp",de="png",ue=(ne.MP4,ne.WebP,ne.APNG,ne.GIF,ne.AlphaMaskVideo,ne.Images,ne.MP4,ne.WebP,ne.APNG,ne.GIF,ne.AlphaMaskVideo,ne.Images,class{constructor(t){h(this,"sampleRate"),h(this,"duration"),h(this,"channels");const{sampleRate:e=44100,duration:i=1,channels:s=2}=t??{};this.sampleRate=e,this.duration=i,this.channels=s}getBuffer(){const t=this.sampleRate*this.duration*this.channels*2,e=44+t,i=new ArrayBuffer(e),s=new DataView(i);let r=0;const a=t=>{for(let e=0;e<t.length;e++)s.setUint8(r++,t.charCodeAt(e))},n=t=>{s.setUint32(r,t,!0),r+=4},o=t=>{s.setUint16(r,t,!0),r+=2};a("RIFF"),n(e-8),a("WAVE"),a("fmt "),n(16),o(1),o(this.channels),n(this.sampleRate),n(this.sampleRate*this.channels*2),o(2*this.channels),o(16),a("data"),n(t);for(let e=0;e<t;e++)s.setUint8(r++,0);return new Uint8Array(i)}});import{FFmpeg as ye}from"@ffmpeg/ffmpeg";import{toBlobURL as ge}from"@ffmpeg/util";var fe={SCRIPT:"https://gw.alipayobjects.com/os/gltf-asset/99531561844014/img2webp.js",WASM:"https://mdn.alipayobjects.com/mars/uri/file/as/0.0.4/wasm/img2webp/img2webp.wasm"},we={CLASSWORKER:"https://mdn.alipayobjects.com/rms/uri/file/as/ffmpeg/core/0.12.10/dist/worker.js",DEFAULT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.wasm"},MT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.wasm",WORKER:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.worker.js"}};function xe(t,e,i,s){const r=e.getContext("2d");ee(r),r.clearRect(0,0,e.width,e.height),i&&(r.save(),r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.restore()),s&&r.drawImage(s,0,0,s.width,s.height,0,0,e.width,e.height),r.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height)}async function Pe(){return new Promise(async(t,e)=>{try{await function(t,e={}){return new Promise((i,s)=>{const r=document.querySelector(`script[src="${t}"]`);if(r)return"true"===r.dataset.loaded?void i(r):(r.addEventListener("load",()=>{i(r)}),void r.addEventListener("error",()=>{s(new Error(`Script already failed: ${t}`))}));const a=document.createElement("script");a.src=t,a.async=!0,Object.keys(e).forEach(t=>{a.setAttribute(t,e[t]??"")}),a.onload=()=>{a.dataset.loaded="true",i(a)},a.onerror=()=>{s(new Error(`Failed to load script: ${t}`))},document.head.appendChild(a)})}(fe.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?fe.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}var ve,De,be,Se,Ie,Te,Ee,Ae,Ce,Me,ke,Ve,ze,_e,Fe,Re,Ke,Ue,Be=["@vvfx/sdk","ExportVideo"],We=class extends v{constructor(t){super(),h(this,"status",se),h(this,"stage",oe),h(this,"mediaType"),h(this,"loggerInTranscoding"),h(this,"multiThreading"),h(this,"extraCanvas"),h(this,"player"),p(this,ve,0),p(this,De),p(this,be),p(this,Se),p(this,Ie),p(this,Te,[]),p(this,Ee),p(this,Ae),p(this,Ce,[]),p(this,Me,0),p(this,ke),p(this,Ve,[]),p(this,ze,0),p(this,_e,0),p(this,Fe,0),p(this,Re,0),p(this,Ke,[]),p(this,Ue,!0);const{mediaType:e,extraCanvas:i,loggerInTranscoding:s,multiThreading:r}=t;this.mediaType=e,this.loggerInTranscoding=s??!1,this.multiThreading=r??!1,this.extraCanvas=i??void 0,this.onInit()}get canceled(){return this.status===ae}get config(){const t=this.player?.getCompositions()??[],e=t?.[0],i=e?.name??(new Date).getTime().toString(),s=e?.getDuration()??0,r=e?.startTime??0,a=l(this,ke)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:l(this,ke)?.fps??30,backgroundColor:l(this,ke)?.backgroundColor??"#000000",loop:l(this,ke)?.loop??!0,audioEnable:l(this,ke)?.audioEnable??!1}}get progress(){const t=l(this,_e)||1,e=l(this,Fe)||1,i=Math.min(t/e,1),s=Math.min(l(this,ze),t)/t*.4,r=Math.min(l(this,Re),t)/t*.6,a=Math.min(s+r,1);l(this,Ve)[l(this,Me)]=i;const n=l(this,Ve).reduce((t,e,i)=>i<l(this,Me)?t+(e||0):t,0)+a*i;return Math.min((o=n,Math.round(100*o)/100),1);var o}get transImageType(){return this.mediaType===ne.MP4?pe:this.mediaType===ne.WebP?me:de}async onInit(){try{ie("log",[...Be,"ready"],"starting"),this.status=se,await this.loadHelper(this.mediaType),this.status=re,ie("log",[...Be,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=ae,this.onError(t)}finally{return this.status}}onReset(){this.stage=oe,window.cancelAnimationFrame(l(this,ve)),m(this,ve,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){ie("log",[...Be,"error"],t),this.onFinish(!1),this.emit("error",t),this.dispose()}onFinish(t,e){ie("log",[...Be,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("done",!!t),this.emit("finish",t,e)}async loadHelper(t){const e="WebP"===t&&!l(this,Se),i=[ne.MP4,ne.APNG,ne.GIF,ne.AlphaMaskVideo].includes(t)&&!l(this,be);e&&m(this,Se,await Pe()),i&&(m(this,be,await async function(t){const{multiThreading:e}=t??{},i=new ye,s=!!e,r={classWorkerURL:await ge(we.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await ge(we.MT.CORE,"text/javascript"),r.wasmURL=await ge(we.MT.WASM,"application/wasm"),r.workerURL=await ge(we.MT.WORKER,"text/javascript")):(r.coreURL=await ge(we.DEFAULT.CORE,"text/javascript"),r.wasmURL=await ge(we.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),l(this,be).on("log",({message:t})=>{if(this.loggerInTranscoding&&ie("log",[...Be,"transcoding log"],t),this.canceled||this.stage!==ce)return;const e=/frame=\s*(\d+)/.exec(t);if(e?.[1]){const t=Number(e[1]);this.setProgress({currentTaskInTranscodingFrameIndex:t})}}))}getAllTaskFrames(t){return t.reduce((t,e)=>{const{scene:i}=e,s=i.compositions?.[0]?.duration??0;return t+Math.round(s*this.config.fps)},0)}setProgress(t){void 0!==t?.completedTaskPercentArray&&m(this,Ve,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&m(this,ze,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&m(this,_e,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&m(this,Re,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&m(this,Fe,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){D(this.player);const{oldTotalTime:i,startTime:s}=this.config;D(i);const r=1e3*i-1e3*i%15;return t=Math.min(t,r/1e3),e?this.player.gotoAndPlay(t-s):this.player.gotoAndStop(t-s),t}getWavAudio(t){m(this,Ee,new ue),l(this,be)?l(this,be).writeFile(t,l(this,Ee).getBuffer()):ie("log",[...Be,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new te,s=i.folder(t);return D(s),l(this,Ce).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){D(l(this,Se));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${l(this,Ce).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=l(this,Se).cwrap("main","string",["number","number"]),[r,a]=function(t,e){const i=t._malloc(e.length*Uint32Array.BYTES_PER_ELEMENT);return e.forEach((e,s)=>{const r=t._malloc(e.length+1);t.writeAsciiToMemory(e,r),t.setValue(i+Uint32Array.BYTES_PER_ELEMENT*s,r,"i32")}),[e.length,i]}(l(this,Se),i);ee(r&&a,"getWebP has error"),s(r,a);const n=l(this,Se).FS.readFile(e);return l(this,Ce).forEach(t=>{l(this,Se)?.FS.unlink(t)}),n}async getAPNG(){D(l(this,be));this.stage=ce;const t="export.apng";return await l(this,be).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-plays",this.config.loop?"0":"1","-y",t]),t}async getGIF(){D(l(this,be));this.stage=ce;const t="export.gif";return await l(this,be).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-loop",this.config.loop?"0":"-1","-vf","scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse","-y",t]),t}async getMP4(t,e){D(l(this,be));this.stage=ce;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;return this.config.audioEnable&&!l(this,Ee)&&(m(this,Ae,"audio.wav"),this.getWavAudio(l(this,Ae))),await l(this,be).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${r}`,"-y",i]),l(this,Ae)&&l(this,Ee)&&(this.stage=le,s="export-with-audio.mp4",await l(this,be).exec(["-i",i,"-i",l(this,Ae),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s])),s&&l(this,be).deleteFile(i).catch(()=>{ie("log",[...Be,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){D(l(this,be));this.stage=ce;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await l(this,be).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${s}`,"-y",i]),i}async getVideoByType(t,e){D(l(this,be));const i=this.mediaType===ne.APNG,s=this.mediaType===ne.GIF,r=this.mediaType===ne.AlphaMaskVideo,a=this.mediaType===ne.MP4;let n="";try{i&&(n=await this.getAPNG()),s&&(n=await this.getGIF()),a&&(n=await this.getMP4(t,e)),r&&(n=await this.getAlphaMaskVideo(t,e)),this.stage=oe}catch(t){throw t}finally{for(const t of l(this,Ce))t&&l(this,be).deleteFile(t)}let o=null;try{D(n);const t=await l(this,be).readFile(n);o="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{l(this,be).deleteFile(n).catch(()=>{ie("log",[...Be,"ffmpeg delete file error"])})}return o}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});m(this,Ie,e),l(this,Ie).start(0);const i=[];l(this,Ie).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},m(this,Te,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o}=t;D(this.player),D(l(this,De));const h=l(this,ze)+1;this.stage=he,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:h}),this.loggerInTranscoding&&ie("log",[...Be,"converting log"],`converting ${h} frame image`),h>1&&this.forwardPlayerTime(h/this.config.fps+a),xe(l(this,De),s,this.config.backgroundColor);let c=s;this.mediaType===ne.AlphaMaskVideo&&(D(this.extraCanvas),function(t,e){e.width=2*t.width,e.height=t.height;const i=t.getContext("2d");if(!i)throw new Error("inputCtx is null");const s=e.getContext("2d");if(!s)throw new Error("ctx is null");s.clearRect(0,0,e.width,e.height);const r=i.getImageData(0,0,t.width,t.height),a=i.getImageData(0,0,t.width,t.height),n=r.data;for(let t=0;t<n.length;t+=4){const e=Math.max(0,(n[t+3]??0)-5)/250*255;e<=0?(n[t]=0,n[t+1]=0,n[t+2]=0,n[t+3]=255):(n[t]=(n[t]??0)*e/255,n[t+1]=(n[t+1]??0)*e/255,n[t+2]=(n[t+2]??0)*e/255,n[t+3]=255)}s.putImageData(r,0,0);const o=a.data;for(let t=0;t<o.length;t+=4){const e=Math.max(0,(o[t+3]??0)-5)/250*255;o[t]=e,o[t+1]=e,o[t+2]=e,o[t+3]=255}s.putImageData(a,t.width,0)}(s,this.extraCanvas),c=this.extraCanvas);const p=await async function(t,e,i){return new Promise((s,r)=>{t.toBlob(t=>{t?s(t.arrayBuffer()):r("toBlob failed")},e,i)})}(c,`image/${this.transImageType}`,1),d=`image-${e=h,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===ne.Images?r.push(p):this.mediaType===ne.WebP?(D(l(this,Se)),l(this,Se).FS.writeFile(d,new Uint8Array(p))):(D(l(this,be)),await l(this,be).writeFile(d,new Uint8Array(p))),l(this,Ce).push(d);if(h===l(this,_e)){this.player?.pause(),await new Promise(t=>{window.requestAnimationFrame(t)});let t=null;"Images"===this.mediaType?t=await this.getImagesZip(this.config.name,r):"WebP"===this.mediaType?t=this.getWebP():[ne.MP4,ne.APNG,ne.GIF,ne.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(n,o)??null),t&&(ie("log",[...Be,"done"],"success"),this.emit("done",!0,t))}else m(this,ve,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o})}))}catch(t){this.onError(t)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;D(this.player),D(l(this,De));const e=l(this,ze)+1;if(this.stage=he,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&ie("log",[...Be,"converting log"],`converting ${e} frame image`),xe(l(this,De),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<l(this,_e))m(this,ve,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),l(this,Ie)?.stop();const t=new Blob(l(this,Te),{type:"video/webm"}),e=await t.arrayBuffer();ie("log",[...Be,"done"],"success"),this.emit("done",!0,e)}}catch(t){ie("log",[...Be,"done"],"failed",t),this.emit("done",!1)}}async runTask(t){try{if(this.canceled)return;D(this.player),D(l(this,De));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[n,o]=e;if(l(this,De).width=n,l(this,De).height=o,s.width=n,s.height=o,this.player.resize(),m(this,Ce,[]),[ne.MP4,ne.APNG,ne.Images,ne.WebP,ne.GIF,ne.AlphaMaskVideo].includes(this.mediaType)){const t={canvas:s,imageBuffers:[],startTime:i,oldTotalTime:r,newTotalTime:a};await this.onExportImageFrame(t)}else"WebM"===this.mediaType&&await this.onExportWebMFrame(s)}catch(t){ie("log",[...Be,"run task error"],t),this.emit("done",!1)}}clearTaskInfo(){m(this,Me,0),m(this,ke,void 0),m(this,Ve,[]),m(this,ze,0),m(this,_e,0),m(this,Fe,0),m(this,Re,0),m(this,Ke,[]),m(this,Ue,!0)}clearFFMpegCore(){if(l(this,be)){for(const t of l(this,Ce))t&&l(this,be).deleteFile(t);m(this,Ce,[]),l(this,be).terminate(),m(this,be,void 0)}}clearImage2WebPCore(){l(this,Se)&&(l(this,Se).FS.quit(),m(this,Se,void 0))}clearMediaRecorder(){l(this,Ie)&&(l(this,Ie).stop(),m(this,Ie,void 0)),m(this,Te,[])}clearAllListeners(){for(const t of this.getListeners("ready"))this.off("ready",t);for(const t of this.getListeners("progress"))this.off("progress",t);for(const t of this.getListeners("done"))this.off("done",t);for(const t of this.getListeners("finish"))this.off("finish",t);for(const t of this.getListeners("error"))this.off("error",t)}onCancel(){this.canceled||(this.onFinish(!1),this.status=ae,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),ie("log",Be,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===se)return ie("log",[...Be],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===ae){if(await this.onInit()===ae)throw new Error("init environment failed")}if(this.clearTaskInfo(),!l(this,De)){const t=document.createElement("canvas");t.dataset.key="player-canvas",m(this,De,t)}this.player||(this.player=new w({canvas:l(this,De),pixelRatio:1,transparentBackground:!0,renderOptions:{willCaptureImage:!0}}),this.player.on("rendererror",t=>{this.onError(t)}),this.player.on("webglcontextlost",t=>{this.onError(t)}));let e=null;e??(e=document.querySelector('canvas[data-key="container-canvas"]')),e??(e=document.createElement("canvas")),e.dataset.key="container-canvas",e.style.display="none",this.setProgress({allTaskFrames:this.getAllTaskFrames(t)});const i=[];let s=!0;for(const[r,a]of t.entries()){if(this.canceled){s=!1;break}m(this,Me,r),m(this,ke,a);const{size:t,scene:n}=a;await new Promise(async o=>{try{if(!this.player)throw new Error("player not found");ie("log",[...Be,"export"],"start",a),this.player.destroyCurrentCompositions(),await this.player.loadScene(n,{env:"editor",autoplay:!1});const h=this.config.oldTotalTime,c=0;this.player.pause(),this.setProgress({currentTaskFrameIndex:0,currentTaskTotalFrames:Math.round(h*this.config.fps)});const l=(t,e)=>{this.off("done",l),t&&e?i[r]=e:s=!1,o()};this.on("done",l);const p={size:t,startTime:c,containerCanvas:e};await this.runTask(p)}catch(t){ie("log",[...Be,"export error"],t),s=!1,o()}})}m(this,Ke,i),m(this,Ue,s)}catch(t){this.onError(t),m(this,Ue,!1)}e>1&&l(this,Ue)?this.onFinish(!0,l(this,Ke)):this.onFinish(!1)}dispose(){this.status=ae,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,l(this,De)?.remove(),m(this,De,void 0),m(this,Ae,void 0),m(this,Ee,void 0)}};async function Ge(t,e,i,s){const[r,a]=e,n=JSON.parse(JSON.stringify(i));await t.loadScene(n,{reusable:!0,autoplay:!1}),t.gotoAndStop(s);const o=document.createElement("canvas");o.width=r,o.height=a;const h=o.getContext("2d");h&&(h.fillStyle="rgba(255, 255, 255, 1)",h.fillRect(0,0,r,a),function(t,e,i,s,r,a,n,o,h){2===arguments.length&&(i=s=0,r=t.canvas.width,a=t.canvas.height);n="number"==typeof n?C(n,0,1):.5,o="number"==typeof o?C(o,0,1):.5,h??(h={left:0,top:0,width:e instanceof HTMLVideoElement?e.videoWidth:e.width,height:e instanceof HTMLVideoElement?e.videoHeight:e.height});const c=h.width,l=h.height,p=Math.min(r/c,a/l);let m=c*p,d=l*p,u=1;m<r&&(u=r/m);Math.abs(u-1)<1e-14&&d<a&&(u=a/d);m*=u,d*=u;const y=Math.max(c/(m/r),0),g=Math.max(l/(d/a),0),f=Math.min((c-y)*n,c),w=Math.min((l-g)*o,l);t.drawImage(e,f+h.left,w+h.top,y,g,i,s,r,a)}(h,t.canvas,0,0,r,a,.5,.5));return o.toDataURL("image/png")}ve=new WeakMap,De=new WeakMap,be=new WeakMap,Se=new WeakMap,Ie=new WeakMap,Te=new WeakMap,Ee=new WeakMap,Ae=new WeakMap,Ce=new WeakMap,Me=new WeakMap,ke=new WeakMap,Ve=new WeakMap,ze=new WeakMap,_e=new WeakMap,Fe=new WeakMap,Re=new WeakMap,Ke=new WeakMap,Ue=new WeakMap;var Ne={DEFAULT:"default",EXPORTING:"exporting",SUCCESS:"success",ERROR:"error"},Oe=class{constructor(t){h(this,"_eventEmitter",new v),h(this,"_pageData"),h(this,"_screenShotContainer"),h(this,"_screenShotPlayer"),h(this,"_SDKUtils"),h(this,"_ExportVideo"),h(this,"_gestureHandler"),h(this,"_playerContainer"),h(this,"_exportStatus",Ne.DEFAULT),h(this,"disposables",[]),h(this,"player"),h(this,"on",this._eventEmitter.on);const[e,i]=[t.offsetWidth,t.offsetHeight],s=document.createElement("div");s.id="player-container",s.style.width=`${e}px`,s.style.height=`${i}px`,s.style.position="absolute",s.style.backgroundRepeat="no-repeat",s.style.backgroundPosition="center center",t.appendChild(s),this._playerContainer=s,this.player=new w({container:s,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this._gestureHandler=new Xt(t),this._gestureHandler.registerViewEvent(),this.player.on("update",()=>{D(this._pageData,"You must call SDK#run() first");const t=this.player.getCompositions()[0]?.time;if(this._pageData.playing)if(void 0!==t)this._pageData.time===t&&this.player.pause(),this._pageData.time=t,this._SDKUtils.refreshPageTime(t);else{this._pageData.playing=!1,this.setPlayProgress(100);const t=this._pageData.viewProperties[this._pageData.activeData.view??0]?.scene,e=t?.compositions.find(e=>e.id===t.compositionId);this._pageData.time=e?.duration??2,this._SDKUtils.refreshPageTime(this._pageData.time)}this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}),this._screenShotContainer=document.createElement("canvas"),this._screenShotPlayer=new w({canvas:this._screenShotContainer,manualRender:!0,renderOptions:{willCaptureImage:!0}}),this._eventEmitter.on("pageDataChange",t=>{this._pageData=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("zoomChange",t=>{D(this._pageData,"You must call SDK#run() first"),this._pageData.property.zoom=t,this._SDKUtils.refreshInteractionParam(),this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{D(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{D(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._SDKUtils=new Qt(this.player,s,this._eventEmitter,this),this._ExportVideo=new We({mediaType:"MP4"});const r=new ResizeObserver(()=>{const e=[t.offsetWidth,t.offsetHeight],i=this._pageData?.viewProperties[this._pageData.activeData.view??0];D(i);const{size:s}=i,[r,a]=this._SDKUtils.getPlayerSizeByParent(e,s);this._playerContainer.style.width=`${r}px`,this._playerContainer.style.height=`${a}px`,this.player.resize(),this._gestureHandler.resize()});r.observe(t),this.disposables.push(()=>{r.disconnect()})}get pageData(){return this._pageData}get exportStatus(){return this._exportStatus}get exportOptions(){return this.pageData?this.pageData.viewProperties.map(t=>{const{size:e,scene:i,export:{time:s,audioEnable:r}}=t;return{size:e,scene:JSON.parse(JSON.stringify(i)),time:s,audioEnable:r}}):[]}dispose(){this.player?.dispose(),this._screenShotPlayer?.dispose(),this._pageData=void 0,this._playerContainer.remove(),this._ExportVideo.dispose(),this._gestureHandler.dispose(),this.disposables.forEach(t=>{t()})}async getInitParam(t){const e=JSON.parse(JSON.stringify(t));if("string"==typeof e.scene)try{const t=await fetch(e.scene,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);const i=await t.json();return{...e,scene:i}}catch(t){throw new Error(`Failed to fetch scene data from ${e.scene}: ${t instanceof Error?t.message:String(t)}`)}return{...e,scene:e.scene}}async initSDK(t){const{scene:e,viewParams:i,options:s}=t,r=[];for(let s=0;s<i.length;s++){const a=i[s];if(!a)continue;let n=JSON.parse(JSON.stringify(e));const o=n.compositions.find(t=>t.id===n.compositionId)??n.compositions[0];D(o);const[h,c]=a.size;o.previewSize=[h,c];const l=o.duration??0;this._screenShotContainer.width=h,this._screenShotContainer.height=c,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize();const p=await Ge(this._screenShotPlayer,a.size,n,l);t.keepSafe&&(this._screenShotContainer.width=h,this._screenShotContainer.height=c,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize(),n=await this._SDKUtils.keepSceneSafe(this._screenShotPlayer,n,l,[h,c],a.safeArea)),r.push({...a,id:s,scene:n,thumbnail:p})}const a=r[0]?.scene;if(!a)return void console.warn("SDK need a view property at least.");const n=a.compositions.find(t=>t.id===a.compositionId)??a.compositions[0],o={...s,zoom:1,translation:[0,0],sync:!1},h=(n?.duration??0)-.1;this._pageData={time:h,property:o,activeData:{selectedItems:[]},items:[],viewProperties:r,playing:!1},this._SDKUtils.init(),this._gestureHandler.init(this._SDKUtils),await this._SDKUtils.loadScene(0),this._SDKUtils.refreshPageTime(h)}async run(t){const e=await this.getInitParam(t);await this.initSDK(e),this._eventEmitter.emit("pageDataChange",this.getPageData())}getPageData(){return JSON.parse(JSON.stringify(this._pageData))}getActiveItems(){return D(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){D(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return D(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem??""}setSelectedItems(t){this._SDKUtils.clearPreSelectedItem(),this._SDKUtils.clearSelectedItems(),this._SDKUtils.addSelectedItems([...t])}getItemProperty(t){D(this._pageData,"You must call SDK#run() first");const e=this._pageData.items.find(e=>e.id===t.itemId);if(e&&e.type===t.type)return{type:e.type,property:e.property}}getItemPropertyValue(t){D(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){D(this._pageData,"You must call SDK#run() first"),await this._SDKUtils.changeItemProperty(t)}async generateScreenShot(t){D(this._pageData,"You must call SDK#run() first");const e=this.pageData?.viewProperties?.[t];if(!e)return"";const{scene:i,size:[s,r]}=e,a=i.compositionId,n=i.compositions.find(t=>t.id===a),o=n?.duration??0;this._screenShotContainer.width=s,this._screenShotContainer.height=r,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize();const h=JSON.parse(JSON.stringify(i));return await Ge(this._screenShotPlayer,[300,400],h,o)}async switchScene(t){if(D(this._pageData,"You must call SDK#run() first"),t===this._pageData.activeData.view)return;this._pageData.viewProperties[t]?(this._pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},await this._SDKUtils.loadScene(t)):console.warn("target scene does not exist."),this._eventEmitter.emit("pageDataChange",this.getPageData())}getConfig(){return D(this._pageData,"You must call SDK#run() first"),{safeAreaPreview:this._pageData.property.safeAreaPreview,zoom:this._pageData.property.zoom,adsorption:this._pageData.property.adsorption}}setConfig(t){D(this._pageData,"You must call SDK#run() first");const{adsorption:e,safeAreaPreview:i,zoom:s}=this._pageData.property;this._pageData.property={...this._pageData.property,...t},this._pageData.property.zoom!==s&&this._SDKUtils.setPageZoom(this._pageData.property.zoom),e!==t.adsorption&&this._gestureHandler.setAdsorptionEnabled(t.adsorption),i!==t.safeAreaPreview&&this._gestureHandler.setSafeAreaPreviewEnabled(t.safeAreaPreview),this._gestureHandler.refresh(),this._gestureHandler.render()}async setPlayProgress(t){D(this._pageData,"You must call SDK#run() first");const e=(this.player.getCompositions()[0]?.getDuration()??2)*t/100;this._pageData.time=e;!this.player.getCompositions().length&&(this.player.destroyCurrentCompositions(),await this._SDKUtils.loadScene(this._pageData.activeData.view??0)),this._pageData.playing?this.player.gotoAndPlay(e):this.player.gotoAndStop(e),this._SDKUtils.refreshPageTime(e)}getViewItems(){return this.getPageData()?.items??[]}setPlayState(t){D(this._pageData,"You must call SDK#run() first");const e="play"===t;this._pageData.playing!==e&&(this._pageData.playing=e,this._gestureHandler.isPlaying=e,e?this.player.gotoAndPlay(this._pageData.time):this.player.gotoAndStop(this._pageData.time),this._gestureHandler.refresh(),this._gestureHandler.render())}getViewThumbnail(){return D(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:t.thumbnail}))}onExportProgress(t){this._eventEmitter.emit("exportProgress",t)}onExportFinish(t,e){this._exportStatus=t?Ne.SUCCESS:Ne.ERROR,this._eventEmitter.emit("exportComplete",t);const i=this.exportOptions[0]?.scene?.compositions?.[0]?.name??"videos";if(e&&e.length>0){const t=new d;e.forEach((e,s)=>{const{size:r}=this.exportOptions[s]??{},a=r?.[0]&&r?.[1]?`(${s+1})_${r[0]}×${r[1]}`:`(${s+1})`,n=`${i}${a}.mp4`;t.file(n,e)}),t.generateAsync({type:"blob"}).then(t=>{!function(t,e,i="application/octet-stream"){const s=new Blob(Array.isArray(t)?t:[t],{type:i}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}(t,`${i}.zip`,"application/zip")}).catch(t=>{ie("error",["@vvfx/sdk"],"exportAllVideos is error",t)})}}onExportError(t){this._exportStatus=Ne.ERROR,ie("error",["@vvfx/sdk"],"exportAllVideos is error",t)}exportAllVideos(){D(this.pageData,"You must call SDK#run() first"),this._exportStatus=Ne.EXPORTING,this._ExportVideo.onExport(this.exportOptions),this._ExportVideo.on("progress",this.onExportProgress.bind(this)),this._ExportVideo.once("finish",this.onExportFinish.bind(this)),this._ExportVideo.on("error",this.onExportError.bind(this))}cancelExportAllVideos(){this._exportStatus=Ne.ERROR,this._ExportVideo.onCancel(),this._eventEmitter.emit("exportComplete",!1)}async loadPageData(t){D(this._pageData,"You must call SDK#run() first"),this._pageData.activeData={view:this._pageData.viewProperties.length,selectedItems:[],preSelectedItem:void 0},this._pageData.viewProperties.push(...t.viewProperties),this._SDKUtils.init(),this._gestureHandler.init(this._SDKUtils),await this._SDKUtils.loadScene(this.pageData?.activeData.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}async runByPageData(t){const e=JSON.parse(JSON.stringify(t));e.property.zoom=1,e.property.translation=[0,0],this._pageData=e,this._SDKUtils.init(),this._gestureHandler.init(this._SDKUtils),await this._SDKUtils.loadScene(this.pageData?.activeData.view??0),this._SDKUtils.refreshPageTime(this._pageData.time),this._eventEmitter.emit("pageDataChange",this.getPageData())}};export{Ne as ExportStatusMap,Oe as SDK,g as spec};
1
+ var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=t=>{throw TypeError(t)},a=(e,i)=>{for(var s in i)t(e,s,{get:i[s],enumerable:!0})},o=(r,a,o,n)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let h of i(a))s.call(r,h)||h===o||t(r,h,{get:()=>a[h],enumerable:!(n=e(a,h))||n.enumerable});return r},n=(t,e,i)=>(o(t,e,"default"),i&&o(i,e,"default")),h=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),c=(t,e,i)=>e.has(t)||r("Cannot "+i),l=(t,e,i)=>(c(t,e,"read from private field"),i?i.call(t):e.get(t)),p=(t,e,i)=>e.has(t)?r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),m=(t,e,i,s)=>(c(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i);import d from"jszip";var u={};a(u,{Composition:()=>P,EventEmitter:()=>v,Player:()=>w,SpriteComponent:()=>D,TextComponent:()=>b,VFXItem:()=>f,assertExist:()=>S,math:()=>x,spec:()=>g});var y={};a(y,{Composition:()=>P,EventEmitter:()=>v,Player:()=>w,SpriteComponent:()=>D,TextComponent:()=>b,VFXItem:()=>f,assertExist:()=>S,math:()=>x,spec:()=>g}),n(y,I);import{spec as g,VFXItem as f,Player as w,math as x,Composition as P,EventEmitter as v,assertExist as S,SpriteComponent as D,TextComponent as b}from"@galacean/effects";import*as I from"@galacean/effects-plugin-rich-text";n(u,y);import{Application as T}from"@pixi/app";var A=class{constructor(){h(this,"interactive"),h(this,"type"),h(this,"active"),this.type="null",this.active=!1,this.interactive=!1}},E=1e-6;function C(t,e,i){const s=isNaN(e)?-1/0:e,r=isNaN(i)?1/0:i,a=Math.min(s,r),o=Math.max(s,r);return Math.min(Math.max(t,a),o)}var V=Math.PI/180,M=180/Math.PI;function z(t){return Math.atan2(-t.y,-t.x)+Math.PI}function k(t,e){return Math.abs(t-e)<E||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function _(t){return isNaN(t)||Math.abs(t)<E}var F=class t extends x.Vector2{subtract(t){return this.x-=t.x,this.y-=t.y,this}toViewCoordinate(t,e){return this.x=(this.x+1)/2*t,this.y=(1-(this.y+1)/2)*e,this}clone(){return new t(this.x,this.y)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}scaleByCenter(e,i=new t){const s=(new t).subtractVectors(i,this).multiply(e);return(new t).subtractVectors(i,s)}round(t=0){const e=Math.pow(10,t);return this.x=Math.round(this.x*e)/e,this.y=Math.round(this.y*e)/e,this}},R=class t{constructor(t=new F,e=new F){h(this,"start",new F),h(this,"end",new F),this.start.copyFrom(t),this.end.copyFrom(e)}set(t,e){return this.start.copyFrom(t),this.end.copyFrom(e),this}copyFrom(t){return this.start.copyFrom(t.start),this.end.copyFrom(t.end),this}direction(){return(new F).subtractVectors(this.end,this.start).normalize()}getCenter(t=new F){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new F){return t.subtractVectors(this.end,this.start)}distanceSq(){return this.start.distanceSquared(this.end)}distance(){return this.start.distance(this.end)}at(t,e=new F){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new F,s=new F;i.subtractVectors(t,this.start),s.subtractVectors(this.end,this.start);const r=s.dot(s);let a=s.dot(i)/r;return e&&(a=C(a,0,1)),a}closestPointToPoint(t,e,i=new F){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiply(s).add(this.start)}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new t).copyFrom(this)}length(){return(new F).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new F).subtractVectors(t.start,this.start),r=(new F).subtractVectors(t.end,this.start),a=(new F).subtractVectors(this.start,t.start),o=(new F).subtractVectors(this.end,t.start),n=s.cross(e),h=r.cross(e),c=a.cross(i),l=o.cross(i);return n*h<0&&c*l<0}},B=class t{constructor(t=new F(1/0,1/0),e=new F(-1/0,-1/0)){h(this,"corners",[]),h(this,"min",new F(1/0,1/0)),h(this,"max",new F(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[t.clone(),new F(e.x,t.y),e.clone(),new F(t.x,e.y)]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[t.clone(),new F(e.x,t.y),e.clone(),new F(t.x,e.y)],this}setFromVec2Array(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min.min(t),this.max.max(t),this.corners.push(t.clone())}),this}setFromVec2ArrayWithOutCorners(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new F(this.min.x,this.min.y)),this.corners.push(new F(this.min.x,this.max.y)),this.corners.push(new F(this.max.x,this.max.y)),this.corners.push(new F(this.max.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new F).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[this.min.clone(),new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y)],this}clone(){return(new t).copyFrom(this)}copyFrom(t){return this.corners=[],this.min.copyFrom(t.min),this.max.copyFrom(t.max),t.corners.forEach(t=>{this.corners.push(t.clone())}),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this.corners=[],this}isEmpty(){return this.max.x<=this.min.x||this.max.y<=this.min.y}getCorners(){const t=[];return this.corners.forEach(e=>{t.push(e.clone())}),t}getCenter(t=new F){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new F){return this.isEmpty()?t.set(0,0):t.subtractVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.subtract(t),this.max.add(t),this}expandByScalar(t){return this.min.add(-t),this.max.add(t),this}containsPoint(t,e=!0){if(e)return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y);if(this.isEmpty())return!1;for(let e=0;e<this.corners.length;e++){const i=this.corners[e],s=this.corners[(e+1)%4],r=new F(s.x-i.x,s.y-i.y),a=new F(t.x-i.x,t.y-i.y);if(r.cross(a)<0)return!1}return!0}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e=new F){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}clampPoint(t,e=new F){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new F).copyFrom(t).clamp(this.min,this.max).subtract(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.min.x>this.max.x||this.min.y>this.max.y?this.makeEmpty():this}union(t){return this.min.min(t.min),this.max.max(t.max),this.corners=[this.min.clone(),new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y)],this}translate(t){return this.min.add(t),this.max.add(t),this.corners.forEach(e=>{e.add(t)}),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}intersectsBox(t,e=!0){if(e)return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y);if(!this.isEmpty())for(let e=0;e<this.corners.length;e++){const i=new R(this.corners[e],this.corners[(e+1)%4]);if(t.containsPoint(this.corners[e],!1))return!0;for(let e=0;e<t.corners.length;e++){const s=new R(t.corners[e],t.corners[(e+1)%4]);if(this.containsPoint(t.corners[e],!1))return!0;if(i.crossWithLine(s))return!0}}for(let e=0;e<t.corners.length;e++){const i=this.containsPoint(t.corners[e],!1),s=t.containsPoint(this.corners[e],!1);if(i||s)return!0}return!1}},K=class t{constructor(t=new F,e=0){h(this,"center"),h(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new F).copyFrom(t),this.radius=e,this}clone(){return(new t).copy(this)}copy(t){return this.center.copyFrom(t.center),this.radius=t.radius,this}makeEmpty(){return this.center=new F,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new F){return t.copyFrom(this.center),t}getRadius(){return this.radius}expandByPoint(t){return this.radius=this.center.distanceTo(t),this}expandByScalar(t){return this.radius+=t,this}containsPoint(t){return this.center.distanceTo(t)<this.radius}containsBox(t){for(let e=0;e<4;e++)if(!this.containsPoint(t.corners[e]))return!1;return!0}intersectsBox(t){for(let e=0;e<4;e++)if(this.containsPoint(t.corners[e]))return!0;return!1}distanceToPoint(t){return this.center.distanceTo(t)-this.radius}},U=class extends x.Quaternion{},W=class t extends x.Vector3{clone(){return new t(this.x,this.y,this.z)}setFromMatrixColumn(t,e){return this.set(...t.elements.slice(4*e))}applyEuler(t,e){return this.applyQuaternion((new U).setFromEuler(t))}applyQuaternion(e,i=new t){const{x:s,y:r,z:a,w:o}=e,{x:n,y:h,z:c}=this.subtract(i),l=o*n+r*c-a*h,p=o*h+a*n-s*c,m=o*c+s*h-r*n,d=-s*n-r*h-a*c;return this.x=l*o+d*-s+p*-a-m*-r+i.x,this.y=p*o+d*-r+m*-s-l*-a+i.y,this.z=m*o+d*-a+l*-r-p*-s+i.z,this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}applyMatrix(e,i=new t){const s=e.elements,{x:r,y:a,z:o}=this.subtract(i);let n=1/(s[3]*r+s[7]*a+s[11]*o+s[15]);return n=isNaN(n)?1:n,this.x=(s[0]*r+s[4]*a+s[8]*o+s[12])*n+i.x,this.y=(s[1]*r+s[5]*a+s[9]*o+s[13])*n+i.y,this.z=(s[2]*r+s[6]*a+s[10]*o+s[14])*n+i.z,this}},G=class t extends x.Matrix4{static fromArray(e,i=0){return(new t).setFromArray(e,i)}clone(){const e=this.elements;return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}compose(t,e,i,s=W.ZERO){const r=this.elements,{x:a,y:o,z:n,w:h}=e,c=-s.x,l=-s.y,p=-s.z,m=a+a,d=o+o,u=n+n,y=a*m,g=a*d,f=a*u,w=o*d,x=o*u,P=n*u,v=h*m,S=h*d,D=h*u,{x:b,y:I,z:T}=i;return r[0]=(1-(w+P))*b,r[1]=(g+D)*b,r[2]=(f-S)*b,r[3]=0,r[4]=(g-D)*I,r[5]=(1-(y+P))*I,r[6]=(x+v)*I,r[7]=0,r[8]=(f+S)*T,r[9]=(x-v)*T,r[10]=(1-(y+w))*T,r[11]=0,r[12]=c*r[0]+l*r[4]+p*r[8]-c+t.x,r[13]=c*r[1]+l*r[5]+p*r[9]-l+t.y,r[14]=c*r[2]+l*r[6]+p*r[10]-p+t.z,this}extractRotation(t){const e=new W,i=t.elements,s=this.elements,r=1/e.setFromMatrixColumn(t,0).length(),a=1/e.setFromMatrixColumn(t,1).length(),o=1/e.setFromMatrixColumn(t,2).length();return s[0]=i[0]*r,s[1]=i[1]*r,s[2]=i[2]*r,s[3]=0,s[4]=i[4]*a,s[5]=i[5]*a,s[6]=i[6]*a,s[7]=0,s[8]=i[8]*o,s[9]=i[9]*o,s[10]=i[10]*o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,a=Math.cos(i),o=Math.sin(i),n=Math.cos(s),h=Math.sin(s),c=Math.cos(r),l=Math.sin(r);if(t.order===x.EulerOrder.XYZ){const t=a*c,i=a*l,s=o*c,r=o*l;e[0]=n*c,e[4]=-n*l,e[8]=h,e[1]=i+s*h,e[5]=t-r*h,e[9]=-o*n,e[2]=r-t*h,e[6]=s+i*h,e[10]=a*n}else if(t.order===x.EulerOrder.YXZ){const t=n*c,i=n*l,s=h*c,r=h*l;e[0]=t+r*o,e[4]=s*o-i,e[8]=a*h,e[1]=a*l,e[5]=a*c,e[9]=-o,e[2]=i*o-s,e[6]=r+t*o,e[10]=a*n}else if(t.order===x.EulerOrder.ZXY){const t=n*c,i=n*l,s=h*c,r=h*l;e[0]=t-r*o,e[4]=-a*l,e[8]=s+i*o,e[1]=i+s*o,e[5]=a*c,e[9]=r-t*o,e[2]=-a*h,e[6]=o,e[10]=a*n}else if(t.order===x.EulerOrder.ZYX){const t=a*c,i=a*l,s=o*c,r=o*l;e[0]=n*c,e[4]=s*h-i,e[8]=t*h+r,e[1]=n*l,e[5]=r*h+t,e[9]=i*h-s,e[2]=-h,e[6]=o*n,e[10]=a*n}else if(t.order===x.EulerOrder.YZX){const t=a*n,i=a*h,s=o*n,r=o*h;e[0]=n*c,e[4]=r-t*l,e[8]=s*l+i,e[1]=l,e[5]=a*c,e[9]=-o*c,e[2]=-h*c,e[6]=i*l+s,e[10]=t-r*l}else if(t.order===x.EulerOrder.XZY){const t=a*n,i=a*h,s=o*n,r=o*h;e[0]=n*c,e[4]=-l,e[8]=h*c,e[1]=t*l+r,e[5]=a*c,e[9]=i*l-s,e[2]=s*l-i,e[6]=o*c,e[10]=r*l+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setPosition(t){return this.elements[12]=t.x,this.elements[13]=t.y,this.elements[14]=t.z,this}},N=class extends x.Euler{constructor(t=0,e=0,i=0,s=x.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new G).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*M,this.y*M,this.z*M):new W(this.x*M,this.y*M,this.z*M)}setFromDegreeVector3(t,e){return this.set(t.x*V,t.y*V,t.z*V,e??this.order)}},O=class{constructor(t=new W,e=new W){h(this,"start"),h(this,"end"),this.start=t.clone(),this.end=e.clone()}closestPointToPointParameter(t,e=!1){const i=(new W).subtractVectors(t,this.start),s=(new W).subtractVectors(this.end,this.start),r=s.dot(s);let a=s.dot(i)/r;return e&&(a=C(a,0,1)),a}closestPointToPoint(t,e=!1){const i=this.closestPointToPointParameter(t,e);return this.delta().multiply(i).add(this.start)}delta(){return(new W).subtractVectors(this.end,this.start)}},H=class t{constructor(t=0,e=new W(0,0,1)){h(this,"distance"),h(this,"normal");const i=e.length();0===i&&(this.normal=new W(0,0,1)),this.distance=t/(i??1),this.normal=e.normalize()}static set(e,i){return new t(e,i)}set(t,e){const i=e.length();return 0===i&&(this.normal=new W(0,0,1)),this.distance=t/i,this.normal=e.normalize(),this}static copy(e){return new t(e.distance,e.normal.clone())}copy(t){return this.distance=t.distance,this.normal.copyFrom(t.normal),this}static setFromNormalAndCoplanarPoint(e,i){const s=-e.dot(i);return new t(s,i)}setFromNormalAndCoplanarPoint(t,e){return this.normal.copyFrom(e),this.distance=-t.dot(this.normal),this}clone(){return new t(this.distance,this.normal.clone())}distanceToPoint(t){return this.normal.dot(t)+this.distance}},L=class t extends x.Ray{constructor(t=new W,e=new W(1,0,0)){super(t,e),h(this,"origin"),h(this,"direction"),this.origin=t.clone(),this.direction=e.clone()}clone(){return new t(this.origin,this.direction)}rayCastPlane(t,e){const i=this.distanceToPlane(t);return isNaN(i)||this.at(i),i}at(t){return this.direction.clone().normalize().multiply(t).add(this.origin)}distanceToPlane(t){const e=t.normal.dot(this.direction);if(_(e))return _(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},j=class{constructor(t=new L){h(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new W(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new W,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},Y=.01,$=2,X=37375,J=6,q=3,Z=15425024,Q=16777215,tt=.17,et=16777215,it=.78,st=1,rt=16711680,at=1,ot=1.5,nt=16777215,ht=0,ct=1,lt=.3,pt=4,mt=8,dt=16711680,ut=1,yt=0,gt=.17,ft=65280,wt=.3,xt=class extends A{constructor(t){super(),h(this,"defaultInteractive",!0),h(this,"interactive",!0),h(this,"lastPoint",new F),h(this,"SDKUtils"),this.SDKUtils=t,this.type="control"}initialize(){}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(){}action(t){const{metaKey:e,ctrlKey:i,shiftKey:s}=t;if(0===t.buttons){const{deltaX:r,deltaY:a}=t,o=new F(r,a);e||i?(o.y=C(o.y,-10,10),this.dolly(o.y)):(o.x=s&&0!==o.y?Math.sqrt(o.x**2+o.y**2)*o.y/Math.abs(o.y):o.x,o.y=s?0:o.y,this.pan(o.multiply(-1)))}}endAction(){}interruption(){return this.type}actionKey(){}endActionKey(){}dolly(t){const e=-t*Y;this.SDKUtils.pageZoom(e)}pan(t){this.SDKUtils.pageMove(t)}getRenderObjects(){return[]}};import{Graphics as Pt}from"@pixi/graphics";var vt=class extends A{constructor(t){super(),h(this,"interactive",!0),h(this,"result",{type:"null",box:new B}),h(this,"selectedItemIds",[]),h(this,"cursorPoint",new F),h(this,"startPoint",new F),h(this,"graphics",new Pt),h(this,"SDKUtils"),h(this,"clearResult",!1),h(this,"type"),this.SDKUtils=t,this.type="selector"}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return this.clearResult?(this.result={type:"null",box:new B},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics])}cancelPreparation(){this.result.type="null",this.SDKUtils.clearPreSelectedItem()}preparationAction(t){this.result.box=new B;const e=new F(t.offsetX,t.offsetY);this.selectedItemIds=this.hitTest(e);const i=this.selectedItemIds[0]??"";return i.length&&!this.SDKUtils.isItemSelected(i)?this.SDKUtils.addPreSelectedItem(i):this.SDKUtils.clearPreSelectedItem(),this.type}preAction(t){if(this.SDKUtils.clearPreSelectedItem(),1===t.buttons)return t.shiftKey||this.SDKUtils.clearSelectedItems(),0===this.selectedItemIds.length?(this.startPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),this.active=!0,this.type):(this.SDKUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0,"transform")}action(t){const e=(new F).addVectors(this.cursorPoint,(new F).subtractVectors(new F(t.clientX,t.clientY),this.startPoint)),i=(new F).subtractVectors(this.cursorPoint,e),s=(new F).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new B).setFromCenterAndSize(s,i);this.result.type="region",this.result.box=r,this.SDKUtils.clearSelectedItems();const a=this.SDKUtils.getPageData().items?.filter(t=>this.SDKUtils.getItemEditEnable(t.id)),o=[];a?.forEach(t=>{r.intersectsBox(this.SDKUtils.getViewBoxById(t.id),!1)&&o.push(t.id)}),this.SDKUtils.addSelectedItems(o)}endAction(){this.active=!1,this.result.type="null"}interruption(){this.active=!1,this.result.type="null"}hitTest(t){const e=this.SDKUtils.getCurrentComposition();if(!e||null===e.items)return[];const{x:i,y:s}=this.SDKUtils.getViewportByViewPoint(t),r={ray:new L,regions:[]};try{r.regions=e.hitTest(i,s,!0),r.ray=e.getHitTestRay(i,s)}catch(t){console.warn(t)}return this.reorderHitTestResult(r,e).filter(t=>"extra-camera"!==t&&this.SDKUtils.getItemEditEnable(t))}reorderHitTestResult(t,e){if(0===t.regions.length||!e)return[];const{ray:i}=t,s=t.regions.reverse(),r=[];return s.forEach(t=>{let s;const a=(t,e)=>{for(const i of t){if(i.id===e&&(s=i),s)return;a(i.children,e)}};if(a(e.items,t.id),void 0===s)return;const o="rootItem"===t.compContent?.name?s.id:t.compContent.id,n=i.origin.clone().distance(t.position.clone());if((s.type===g.ItemType.mesh||s.content&&"renderer"in s.content&&s.content.renderer&&"occlusion"in s.content.renderer&&s.content.renderer.occlusion)&&r.length>0){let t=!0;r.forEach((e,i)=>{if(t)return n<=e[1]?(r.splice(i,0,[o,n]),void(t=!1)):void(i===r.length-1&&r.push([o,n]))})}else r.push([o,n])}),r.map(t=>t[0])}refreshResults(){const{box:t}=this.result;this.graphics.clear();const e=this.SDKUtils.getPreSelectedItem(),i=this.SDKUtils.getViewBoxById(e?.id??"");if(i?.isEmpty()||(this.graphics.lineStyle(q,Z),this.graphics.drawBox(i)),!t.isEmpty()&&"region"===this.result.type)this.graphics.lineStyle(st,et,it),this.graphics.drawBox(t),this.graphics.beginFill(Q,tt),this.graphics.fillBox(t),this.graphics.endFill()}};import{Graphics as St}from"@pixi/graphics";import{assertExist as Dt}from"@galacean/effects";var bt=class extends A{constructor(t,e){super(),h(this,"type"),h(this,"interactive",!0),h(this,"wireframe"),h(this,"cursorResult",{type:"normal",angle:0}),h(this,"cursorPoint",new F),h(this,"lastPoint",new F),h(this,"rotationAngle",0),h(this,"active",!1),h(this,"enableAdsorption",!0),h(this,"scaleParam"),h(this,"activeType","null"),h(this,"lastWorldPosition",new W),h(this,"SDKUtils"),h(this,"adsorptionGizmo"),h(this,"graphics",new St),this.type="transform",this.SDKUtils=t,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new F,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,box:new B,totalBox:new B,childrenBoxes:[],activeType:"null",interactiveDirection:new F,scaleCorner:new F,scaleEdgeCorners:[]}}initialize(){}actionKey(){}endActionKey(){}getRenderObjects(){return this.refreshRenderObject(),[this.graphics]}cancelPreparation(){this.active=!1,this.wireframe.activeType="null"}preAction(t,e=!1){if(this.active=1===t.buttons,this.lastPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),1===t.buttons)return this.active=!0,"null"===this.wireframe.activeType&&(this.wireframe.activeType="translation"),this.initInteractionPlane(this.cursorPoint),this.lastWorldPosition=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint)??new W,this.activeType=e?"null":this.activeType,this.type}preparationAction(t){const e=new F(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;return this.refreshCursorResult(this.activeType,z(s)),this.active="null"!==this.activeType,this.active?this.type:void 0}action(t){this.active||(this.active=!0,this.refreshWireframeBySelectedItems(),this.wireframe.activeType="translation",this.lastPoint.set(t.clientX,t.clientY),this.cursorPoint.set(t.offsetX,t.offsetY),this.initInteractionPlane(this.cursorPoint),this.lastWorldPosition=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint)??new W);const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);if(!this.wireframe.interactive)return;const s=this.SDKUtils.getSelectedItems(),{anchor:r,activeType:a,interactiveDirection:o}=this.wireframe,n=this.SDKUtils.getPageData();Dt(n);let h=0;switch(a){case"rotation":{const t=r.clone(),e=new W,a=function(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}(function(t,e){const i=Math.min(Math.max(t.dot(e)/t.length()/e.length(),-1),1);let s=Math.acos(i);return s=t.x*e.y-t.y*e.x>0?s:-s,s}((new F).subtractVectors(this.cursorPoint,t),(new F).subtractVectors(this.cursorPoint.add(i),t))*M,3);e.z=a,this.rotationAngle+=a,h=z(o)+this.rotationAngle*V,s.forEach(t=>{this.SDKUtils.rotateItem(t.id,e)});break}case"translation":{const t=i.clone();if(this.enableAdsorption){const e=n.items.map(t=>!s.find(e=>e.id===t.id)&&0===s.filter(e=>t.parentId&&t.parentId===e.id).length&&this.SDKUtils.getItemEditEnable(t.id)?this.SDKUtils.getViewBoxById(t.id):new B).filter(t=>!t.isEmpty()),i=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);t.add(i).subtract(r)}const e=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(t));if(e){const t=e.clone().subtract(this.lastWorldPosition).divide(n.property.zoom);s.forEach(e=>{e.type!==g.ItemType.camera&&this.SDKUtils.moveItem(e.id,t)}),this.lastWorldPosition.copyFrom(e)}break}case"scale":{this.cursorPoint.add(i);const t=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint);if(i.length()&&t&&this.scaleParam){const{corner:e,center:i,shift:r,lastScalar:o}=this.scaleParam,n=this.SDKUtils.getSelectedItems()[0]??void 0,h=this.SDKUtils.getItemTransformById(n?.id??""),c=(new G).extractRotation(h.matrix).invert(),l=(new W).subtractVectors(e,i).applyMatrix(c),p=l.clone().multiply(o),m=t.subtract(r).subtract(i).applyMatrix(c),d=new W(1,1,1);if("scale"===a){const t=function(t){let e,i=0;return t.forEach((t,s)=>{if(0===s)e=Math.abs(t);else{const r=Math.abs(t);e<r&&(e=r,i=s)}}),i}([k(l.x,0)?1:Math.abs(m.x/l.x),k(l.y,0)?1:Math.abs(m.y/l.y)]),e=m.toArray()[t],i=p.toArray()[t];if(k(o.x,o.y)&&k(o.z,o.x)){const t=k(i,0)?1:Math.abs(e/i);d.set(t,t,t)}else if(0===t){d.x=k(i,0)?1:Math.abs(e/i);const t=l.y*e/l.x;d.y=k(p.y,0)?1:t/p.y;const s=l.z*e/l.x;d.z=k(p.z,0)?1:s/p.z}else if(1===t){d.y=k(i,0)?1:Math.abs(e/i);const t=l.x*e/l.y;d.x=k(p.x,0)?1:t/p.x;const s=l.z*e/l.y;d.z=k(p.z,0)?1:s/p.z}else{d.z=k(i,0)?1:Math.abs(e/i);const t=l.x*e/l.z;d.x=k(p.x,0)?1:t/p.x;const s=l.y*e/l.z;d.y=k(p.y,0)?1:s/p.y}}this.scaleParam.lastScalar.multiply(d),s.forEach(t=>{this.SDKUtils.scaleItem(t.id,d)})}h=z(o);break}}this.refreshCursorResult(a,h),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);this.cursorPoint.add(i);const s=this.wireframe;this.refreshTransformType(this.cursorPoint);const{activeType:r,interactiveDirection:a}=s;this.refreshCursorResult(r,z(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new F,this.lastPoint=new F}interruption(){this.active=!1,this.cursorResult.type="normal",this.adsorptionGizmo.clearAbsorptionResult()}refreshCursorResult(t,e=0){switch(t){case"scale":this.cursorResult={type:"scale",angle:(e+Math.PI/4)*M};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*M};break;case"translation":case"null":this.cursorResult={type:"normal",angle:0}}}refreshResults(){const t=this.wireframe.activeType;this.refreshWireframeBySelectedItems(),t!==this.wireframe.activeType&&this.refreshCursorResult(this.wireframe.activeType),this.wireframe.box.isEmpty()&&this.adsorptionGizmo.clearAbsorptionResult()}initInteractionPlane(t){const e=this.SDKUtils.getSelectedItems();switch(this.wireframe.activeType){case"scale":{const i=1==e.length?e[0]:void 0;let s,r;if(i){const t=this.SDKUtils.getItemTransformById(i.id);s=(new W).setFromMatrixPosition(t.matrix),r=(new N).setFromQuaternion((new U).setFromRotationMatrix(t.matrix))}if(this.SDKUtils.interactionUtils.initInteractionPlane(s,r),["scale"].includes(this.wireframe.activeType)){if(this.scaleParam={shift:new W,center:new W,corner:new W,lastScalar:new W(1,1,1)},this.scaleParam.center=s,["scale"].includes(this.wireframe.activeType)&&this.wireframe.scaleCorner)this.scaleParam.corner=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.wireframe.scaleCorner)??new W;else if(this.wireframe.scaleEdgeCorners){const t=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.wireframe.scaleEdgeCorners[0])??new W,e=this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(this.wireframe.scaleEdgeCorners[1])??new W,i=t.applyEuler(r??new N,this.scaleParam.center),s=e.applyEuler(r??new N,this.scaleParam.center),a=new O(i,s).closestPointToPoint(this.scaleParam.center);this.scaleParam.corner=a.applyMatrix((r??new N).getInvertMatrixByEuler(),this.scaleParam.center)}this.scaleParam.shift=(this.SDKUtils.interactionUtils.getWorldPositionByViewPoint(t)??new W).subtract(this.scaleParam.corner)}break}case"translation":case"rotation":this.SDKUtils.interactionUtils.initInteractionPlane()}}refreshRenderObject(){if(this.graphics.clear(),!this.wireframe.box.isEmpty()){this.graphics.lineStyle(ot,rt,at),this.wireframe.edges.forEach(t=>{this.graphics.drawLine(t)});const t=t=>{t.corners.forEach((e,i)=>{const s=new R(e,t.corners[(i+1)%4]);this.graphics.drawLine(s)})};this.wireframe.childrenBoxes.forEach(e=>{t(e)}),this.wireframe.cornerEnable&&(this.graphics.beginFill(nt),this.graphics.lineStyle(ct,ht,lt),this.wireframe.scaleCorners.forEach(t=>{this.graphics.drawCircle(t.center.x,t.center.y,t.radius)}),this.graphics.endFill())}}refreshTransformType(t){this.activeType="null";let e=!0;if(this.wireframe.interactiveDirection=new F,this.wireframe.scaleCorner=void 0,this.wireframe.scaleEdgeCorners=void 0,this.wireframe.cornerEnable&&e&&this.wireframe.totalBox.containsPoint(t)){for(let i=0;i<4;i++){if(this.wireframe.scaleCorners[i].containsPoint(t)){e=!1,this.activeType="scale",this.wireframe.activeType="scale",this.wireframe.scaleCorner=this.wireframe.scaleCorners[i].center.clone(),this.wireframe.interactiveDirection.copyFrom(this.wireframe.scaleCorners[i].center).subtract(this.wireframe.box.getCenter());break}}e&&this.wireframe.box.containsPoint(t,!1)&&(e=!1,this.activeType="translation",this.wireframe.activeType="translation");for(let i=0;i<4;i++){if(this.wireframe.rotationCorners[i].containsPoint(t)&&e){e=!1,this.activeType="rotation",this.wireframe.activeType="rotation",this.wireframe.interactiveDirection.copyFrom(this.wireframe.rotationCorners[i].center).subtract(this.wireframe.box.getCenter());break}}}}refreshWireframeBySelectedItems(){const t=this.SDKUtils.getSelectedItems(),e=new B;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],t.length>1)t.forEach(t=>{if(this.SDKUtils.getItemShow(t.id)){const i=this.SDKUtils.getViewBoxById(t.id);e.union(i),this.wireframe.childrenBoxes.push((new B).copyFrom(i).expandByScalar(1))}}),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=!0;else if(1===t.length){const i=t[0];if(this.SDKUtils.getItemShow(i.id)){const t=this.SDKUtils.getViewBoxById(i.id);e.copyFrom(t),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=i.type!==g.ItemType.mesh&&this.SDKUtils.getItemEditEnable(i.id)}}const i=e.isEmpty(),s=i?0:1,r=i?0:16;this.wireframe.activeType=t.length?this.wireframe.activeType:"null",this.wireframe.box.copyFrom(e).expandByScalar(s),this.wireframe.totalBox.copyFrom(e).expandByScalar(r);const a=this.wireframe.box.corners;a.forEach((t,e)=>{this.wireframe.edges.push(new R((new F).copyFrom(t),(new F).copyFrom(a[(e+1)%4])))}),this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new K(t,pt));const e=(new F).subtractVectors(t,this.wireframe.box.getCenter()),i=(new F).copyFrom(this.wireframe.box.getCenter()).add((new F).copyFrom(e).normalize().multiply(e.length()+mt-pt));this.wireframe.rotationCorners.push(new K(i,mt))})}setAdsorptionEnabled(t){this.enableAdsorption=t}};import{Graphics as It}from"@pixi/graphics";var Tt=class extends A{constructor(){super(),h(this,"interactive",!1),h(this,"results",[]),h(this,"graphics",new It),h(this,"absorptionResult",{}),this.type="adsorption"}initialize(){}preparationAction(){}getCursorState(){}preAction(){}action(){}cancelPreparation(){}actionKey(){}endActionKey(){}endAction(){}interruption(){}boxTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],e.isEmpty())return;const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),o=e.clone().translate(a),n=o.getCenter();this.absorptionResult={},i.forEach(t=>{if(t.isEmpty())return;t.corners.forEach(t=>{o.corners.forEach(e=>{this.getPointAbsorption(e,t,s,r)}),this.getPointAbsorption(n,t,s,r)});const e=t.getCenter();this.getPointAbsorption(n,e,s,r),o.corners.forEach(t=>{this.getPointAbsorption(t,e,s,r)})})}pointTranslationAdsorption(t,e,i,s=!0,r=!0){this.results=[];const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),o=e.clone().add(a);this.absorptionResult={},i.forEach(t=>{this.getPointAbsorption(o,t,s,r)})}getPointAbsorption(t,e,i=!0,s=!0){i&&Math.abs(t.x-e.x)<J&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<J&&this.refreshPointAbsorptionResult(t,e,"y")}refreshPointAbsorptionResult(t,e,i){const s=t[i]-e[i],r="x"===i?"xPoints":"yPoints";if(this.absorptionResult&&void 0===this.absorptionResult[i])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else if(Math.abs(s)-Math.abs(this.absorptionResult[i]??0)<=.005)if(Math.abs(Math.abs(s)-Math.abs(this.absorptionResult[i]??0))<.05&&s*(this.absorptionResult[i]??0)>0)if(void 0===this.absorptionResult[r])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else{const i=this.absorptionResult[r].filter(e=>e.point.equals(t));void 0===i||0===i.length?this.absorptionResult[r]?.push({point:t,targets:[e]}):i[0]?.targets.push(e)}else this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}]}refreshResults(){if(void 0===this.absorptionResult)return;const{x:t,y:e,xPoints:i,yPoints:s}=this.absorptionResult,r=new F(t??0,e??0);void 0!==t&&void 0!==i&&i.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.x=t.x,i.y=Math.min(i.y,t.y),s.x=t.x,s.y=Math.max(s.y,t.y)}),this.results.push(new R(i,s))}),void 0!==e&&void 0!==s&&s.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.y=t.y,i.x=Math.min(i.x,t.x),s.y=t.y,s.x=Math.max(s.x,t.x)}),this.results.push(new R(i,s))})}refreshRenderObject(){this.graphics.clear(),this.results.forEach(t=>{this.graphics.lineStyle($,X),this.graphics.drawLine(t)})}getRenderObjects(){return this.refreshResults(),this.refreshRenderObject(),[this.graphics]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},At={};a(At,{Application:()=>Mt,utils:()=>Ct});var Et={};a(Et,{Application:()=>Mt,utils:()=>Ct}),n(Et,Rt),n(Et,Bt),n(Et,Kt),n(Et,Ut),n(Et,Wt),n(Et,Gt),n(Et,Nt),n(Et,Ot),n(Et,Ht),n(Et,Lt),n(Et,jt),n(Et,Yt);import"@pixi/polyfill";import*as Ct from"@pixi/utils";import{InteractionManager as Vt}from"@pixi/interaction";import{Application as Mt}from"@pixi/app";import{Renderer as zt,BatchRenderer as kt}from"@pixi/core";import{AppLoaderPlugin as _t}from"@pixi/loaders";import{TickerPlugin as Ft}from"@pixi/ticker";import*as Rt from"@pixi/constants";import*as Bt from"@pixi/core";import*as Kt from"@pixi/display";import*as Ut from"@pixi/graphics";import*as Wt from"@pixi/loaders";import*as Gt from"@pixi/interaction";import*as Nt from"@pixi/math";import*as Ot from"@pixi/runner";import*as Ht from"@pixi/sprite";import*as Lt from"@pixi/text";import*as jt from"@pixi/ticker";import*as Yt from"@pixi/settings";Ct.skipHello(),zt.registerPlugin("interaction",Vt),zt.registerPlugin("batch",kt),Mt.registerPlugin(Ft),Mt.registerPlugin(_t),Et.Graphics.prototype.drawBox=function(t){const e=t.getCorners();this.beginFill();for(let t=0;t<4;t++)this.moveTo(e[t].x,e[t].y),this.lineTo(e[(t+1)%4].x,e[(t+1)%4].y);this.endFill()},Et.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},Et.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof R)this.moveTo(t.start.x,t.start.y),this.lineTo(t.end.x,t.end.y);else for(let e=0;e<t.length-1;e++)this.moveTo(t[e].x,t[e].y),this.lineTo(t[e+1].x,t[e+1].y);this.endFill()},n(At,Et);var $t=class extends A{constructor(t){super(),h(this,"safeAreaPreview",!1),h(this,"interactive",!1),h(this,"box",new B),h(this,"graphics",new At.Graphics),h(this,"SDKUtils"),this.SDKUtils=t,this.type="preference"}initialize(){throw new Error("Method not implemented.")}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){this.box=new B;const t=this.SDKUtils.getPageData();S(t);const{container:e}=this.SDKUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new F(s,r).multiply(i),o=this.SDKUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new B).setFromCenterAndSize(o,a)}}setSafeAreaPreviewEnabled(t){this.safeAreaPreview=t}refreshRenderObjects(){this.graphics=new At.Graphics;const{offsetWidth:t,offsetHeight:e}=this.SDKUtils.container.parentElement,i=new B(new F(0,0),new F(t,this.box.min.y)),s=new B(new F(0,this.box.min.y),new F(this.box.min.x,e)),r=new B(new F(this.box.min.x,this.box.max.y),new F(t,e)),a=new B(new F(this.box.max.x,this.box.min.y),new F(t,this.box.max.y));if(this.graphics.beginFill(yt,gt),this.graphics.fillBox(i),this.graphics.fillBox(s),this.graphics.fillBox(r),this.graphics.fillBox(a),this.graphics.endFill(),this.safeAreaPreview){const t=this.SDKUtils.getPageData();S(t,"You must call SDK#run() first");const{viewProperties:e,activeData:i}=t,s=e[i.view??-1];if(s){const{size:t,safeArea:e}=s,[i,r,a,o]=e,n=this.box.getSize(),h=i/t[1]*n.y,c=a/t[0]*n.x,l=o/t[0]*n.x,p=r/t[1]*n.y,{min:m,max:d}=this.box;this.graphics.beginFill(ft,wt);const u=new B(m,new F(d.x,m.y+h)),y=new B(new F(m.x,m.y+h),new F(m.x+c,d.y)),g=new B(new F(d.x-l,m.y+h),new F(d.x,d.y)),f=new B(new F(m.x+c,d.y-p),new F(d.x-l,d.y));this.graphics.fillBox(u),this.graphics.fillBox(y),this.graphics.fillBox(g),this.graphics.fillBox(f),this.graphics.endFill()}}this.graphics.lineStyle(ut,dt),this.graphics.drawBox(this.box)}getRenderObjects(){return this.refreshRenderObjects(),[this.graphics]}},Xt=class{constructor(t){h(this,"wireframeApplication"),h(this,"gizmos",[]),h(this,"activeGizmo"),h(this,"selectorGizmo"),h(this,"transformGizmo"),h(this,"controlGizmo"),h(this,"preferenceGizmo"),h(this,"spaceClickTime"),h(this,"spaceEmit",!1),h(this,"_ignoreInteraction",!1),h(this,"clickButtons",0),h(this,"container"),h(this,"clickTime",0),h(this,"firstClick",!0),h(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new T({backgroundAlpha:0,width:e,height:i,resolution:1,antialias:!0}),this.container=t,this.wireframeApplication.view.style.position="absolute",this.wireframeApplication.view.id="wireframeApplicationCanvas",t.appendChild(this.wireframeApplication.view),this.wireframeApplication.stage.sortableChildren=!0,this.registerViewEvent()}set ignoreInteraction(t){t!==this._ignoreInteraction&&(this._ignoreInteraction=t,t&&(this.activeGizmo?.cancelPreparation(),this.activeGizmo=void 0))}get ignoreInteraction(){return this._ignoreInteraction}resize(){this.wireframeApplication&&(this.wireframeApplication.resizeTo=this.container,this.render())}refresh(){this.gizmos.forEach(t=>{t.refreshResults()})}render(){this.refresh(),this.wireframeApplication.stage.removeChildren();const t=(this.ignoreInteraction?[this.preferenceGizmo]:this.gizmos).flatMap(t=>t.getRenderObjects());this.wireframeApplication.stage.addChild(...t),this.wireframeApplication.render()}init(t){this.gizmos=[],this.controlGizmo=new xt(t),this.selectorGizmo=new vt(t);const e=new Tt;this.transformGizmo=new bt(t,e),this.preferenceGizmo=new $t(t),this.gizmos.push(this.transformGizmo,this.selectorGizmo,this.controlGizmo,this.preferenceGizmo,e),this.initEvents()}initEvents(){this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp)}registerViewEvent(){this.wireframeApplication.view.onmousedown=t=>{this.onMouseDown(t)},this.wireframeApplication.view.onmousemove=t=>{0===t.buttons&&this.onMouseMove(t)},this.wireframeApplication.view.onmouseout=()=>{this.selectorGizmo?.cancelPreparation(),this.render()},this.wireframeApplication.view.onwheel=t=>{this.onWheel(t)}}onMouseDown(t){if(!this.ignoreInteraction){if(this.clickButtons=t.buttons,this.firstClick=!!this.firstClick&&Date.now()-this.clickTime<this.dblclickTimeSpan,this.firstClick){this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.activeGizmo=void 0;const e=this.selectorGizmo?.preAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null")),this.firstClick=!1}else{void 0===this.activeGizmo&&this.gizmos.forEach(e=>{if(!e.interactive||this.activeGizmo)return;const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)});const e=this.activeGizmo?.preAction(t);"selector"!==e&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===e),this.clickTime=Date.now(),this.firstClick=!0}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}}onMouseMove(t){this.ignoreInteraction||(0!==t.buttons?this.activeGizmo?.action(t):this.spaceEmit||(this.activeGizmo=void 0,this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);"selector"!==i&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()})),this.render())}onWheel(t){this.ignoreInteraction||(t.preventDefault(),this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.controlGizmo?.action(t))}onMouseUp(t){if(this.ignoreInteraction)return;const e=this.activeGizmo?.endAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===e),void 0===this.activeGizmo&&1===this.clickButtons&&this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.clickButtons=0,this.render(),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}onKeyDown(t){if(!this.ignoreInteraction){if("space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active)this.gizmos.forEach(e=>{e.actionKey(t)});else{if(this.spaceEmit)return;void 0===this.spaceClickTime?this.spaceClickTime=Date.now():Date.now()-this.spaceClickTime>300&&(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.activeGizmo?.actionKey(t))}this.render()}}onKeyUp(t){this.ignoreInteraction||(this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceClickTime=void 0,this.spaceEmit=!1),this.render())}setAdsorptionEnabled(t){this.transformGizmo?.setAdsorptionEnabled(t)}setSafeAreaPreviewEnabled(t){this.preferenceGizmo?.setSafeAreaPreviewEnabled(t)}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}};import{assertExist as Jt}from"@galacean/effects";var qt=class{constructor(t){h(this,"plane",new H),h(this,"ray",new L),h(this,"viewportParam",{width:0,height:0,viewWidth:0,viewHeight:0,panelWidth:0,panelHeight:0,scale:1,ratio:1,translation:new F,rulerWidth:0}),h(this,"cameraParam",{position:new W,rotation:new W,focusPosition:new W,focusRotation:new W,viewProjectionMatrix:new G,inverseViewProjectionMatrix:new G}),h(this,"SDKUtils"),this.SDKUtils=t}refreshViewParam(){const t=this.SDKUtils.getPageData();Jt(t,"You must run SDK first");const e=new F(this.SDKUtils.container.offsetWidth,this.SDKUtils.container.offsetHeight),{zoom:i,translation:s}=t.property;this.viewportParam.width=e.x,this.viewportParam.height=e.y,this.viewportParam.viewWidth=e.x,this.viewportParam.viewHeight=e.y,this.viewportParam.panelWidth=e.x,this.viewportParam.panelHeight=e.y,this.viewportParam.scale=i,this.viewportParam.ratio=1,this.viewportParam.translation=new F(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.SDKUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=G.fromArray(e.getViewProjectionMatrix().toArray()),i=G.fromArray(e.getViewMatrix().toArray()).invert(),s=new U;i.decompose(this.cameraParam.position,s,new W),this.cameraParam.rotation=(new N).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new W(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new N).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new N).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=G.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new N).setFromDegreeVector3(this.cameraParam.rotation));const i=new W(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new N).setFromDegreeVector3(this.cameraParam.rotation):(new N).setFromQuaternion((new U).setFromRotationMatrix(this.SDKUtils.getItemTransformById(i.id).matrix)),r=i?(new W).setFromMatrixPosition(this.SDKUtils.getItemTransformById(i.id).matrix):this.cameraParam.focusPosition,a=this.projectPoint(r.clone()),o=this.getWorldPositionByViewPoint(a.add(t));if(!o)return console.warn("size is out of bounds."),new W(0,0,0);const n=(new N).setFromQuaternion((new U).setFromEuler(s).invert());return(e||!i?o.applyEuler(n,r):o).subtract(r)}projectPoint(t){const{panelWidth:e,panelHeight:i,scale:s}=this.viewportParam,r=this.SDKUtils.getViewportLeftTopPosition();return(new F).copyFrom(t.applyMatrix(this.cameraParam.viewProjectionMatrix).toVector2()).toViewCoordinate(e*s,i*s).add(r)}getWorldPositionByViewPoint(t){const{position:e,inverseViewProjectionMatrix:i}=this.cameraParam,s=this.getViewPositionByScreenPosition(t),r=(new j).setFromCamera(s,{position:e,inverseViewProjectMatrix:i}).rayCastPlane(this.plane);return r?.point}getViewPositionByScreenPosition(t){const{panelWidth:e,panelHeight:i,rulerWidth:s}=this.viewportParam;return new F((t.x-s)/e*2-1,-(t.y-s)/i*2+1)}getScreenSizeByPixelSize(t){const e=this.viewportParam.width/this.viewportParam.viewWidth,i=t.clone();return i.multiply(e||1),i}getPixelSizeByScreenSize(t){const e=this.viewportParam.viewWidth/this.viewportParam.width,i=t.clone();return i.multiply(e||1),i}};import{Texture as Zt}from"@galacean/effects";var Qt={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},te=class{constructor(t,e,i,s){h(this,"sdk"),h(this,"player"),h(this,"container"),h(this,"emitter"),h(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new qt(this)}getPageData(){return this.sdk.pageData}getCurrentComposition(){return this.player.getCompositions()[0]}isItemSelected(t){return!!this.sdk.pageData?.activeData.selectedItems?.find(e=>e===t)}getItemEditEnable(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart)}getItemShow(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart||a===g.EndBehavior.freeze)}addSelectedItems(t){var e;S(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.activeData).selectedItems??(e.selectedItems=[]),t.forEach(t=>{var e,i;e=this.sdk.pageData?.activeData.selectedItems??[],i=t,e.includes(i)||e.push(i)}),this.emitter.emit("selectedItemChange",t)}clearSelectedItems(){this.sdk.pageData&&(this.sdk.pageData.activeData.selectedItems=[],this.emitter.emit("selectedItemChange",[]))}getSelectedItems(){const t=this.sdk.pageData?.activeData.selectedItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}addPreSelectedItem(t){S(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){S(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=void 0,this.emitter.emit("preSelectedItemChange",void 0)}getPreSelectedItem(){const t=this.getPageData();S(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}getViewItemById(t){return this.sdk.pageData?.items.find(e=>e.id===t)}getPlayerSizeByParent(t,e){const[i,s]=t,[r,a]=e;let o=s,n=o/a*r;return n>i&&(o=i/n*s,n=i),[n,o]}async loadScene(t){this.player.destroyCurrentCompositions();const e=this.sdk.pageData?.viewProperties[t];if(!e||!this.sdk.pageData)return void console.warn(`This page does not have ${t} view property.`);const{scene:i,size:s}=e,r=this.container.parentElement?.offsetWidth??300,a=this.container.parentElement?.offsetHeight??300,[o,n]=this.getPlayerSizeByParent([r,a],s);this.container.style.width=`${o}px`,this.container.style.height=`${n}px`,this.sdk.pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},this.player.resize();const h=JSON.parse(JSON.stringify(i)),c=await this.player.loadScene(h,{autoplay:!1});this.player.gotoAndStop(this.sdk.pageData.time),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,c.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshPageTime(t){S(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t){var e;S(this.sdk.pageData,"You must call SDK#run() first");const{zoom:i}=this.sdk.pageData.property;(e=this.sdk.pageData.property).zoom??(e.zoom=1);const s=C(t,-.1,.1),r=C(i+s,.3,10);this.sdk.pageData.property.zoom=r,this.container.style.scale=`${r}`,this.emitter.emit("zoomChange",r)}setPageZoom(t){S(this.sdk.pageData,"You must call SDK#run() first");const e=C(t,.3,10);this.sdk.pageData.property.zoom=e,this.container.style.scale=`${e}`,this.emitter.emit("zoomChange",t)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){S(this.sdk.pageData,"You must call SDK#run() first");const[e,i]=this.sdk.pageData.property.translation??[0,0],s=e+t.x,r=i+t.y;this.sdk.pageData.property.translation=[s,r],this.refreshInteractionParam(),this.container.style.translate=`${s}px ${r}px`,this.emitter.emit("pageDataChange",this.sdk.pageData)}rotateItem(t,e){const i=this.getPlayerItemById(t);i&&(i.rotate(...e.toArray()),this.transformSceneItem(t,"rotation",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"rotation"}))}moveItem(t,e){const i=this.getPlayerItemById(t);if(i){const s=(new G).copyFrom(i.transform.getParentMatrix()??new G);s.setPosition(new W);const r=e.clone().applyMatrix(s.invert());i.translate(...r.toArray()),this.transformSceneItem(t,"position",r.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"translation"})}}scaleItem(t,e){const i=this.getPlayerItemById(t);i&&(i.scale(...e.toArray()),this.transformSceneItem(t,"scale",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"scale"}))}getItemTransformById(t){const e={matrix:new G,parentMatrix:new G},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=G.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(G.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(G.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new G).toArray()))}return e}addViewItemsByItems(t,e,i){const s=e=>{e.forEach(e=>{t.find(t=>t.id===e.id)||t.push(this.createViewItemByPlayerItem(e,i))})};for(const i of e)s([i]),this.addViewItemsByItems(t,i.children,i.id)}createViewItemByPlayerItem(t,e){S(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s}=t;i.updateLocalMatrix();const r=(new G).copyFrom(s?.transform.getWorldMatrix()??(new G).identity()).invert().multiply(i.getWorldMatrix()),a=new W,o=new U,n=new W;r.decompose(a,o,n);const h=(new N).setFromQuaternion(o).toDegreeVector3();h.x=Number.isNaN(h.x)?0:h.x,h.y=Number.isNaN(h.y)?0:h.y,h.z=Number.isNaN(h.z)?0:h.z;const c={position:a.toArray(),rotation:h.toArray(),scale:n.toArray(),keyPropertyEditing:!1};switch(t.type){case g.ItemType.sprite:{const e=this.getActiveScene()?.scene;if(e){e.components.filter(e=>e.item.id===t.id).forEach(t=>{if(c.keyPropertyEditing||!("renderer"in t)||!("texture"in t.renderer)||!t.renderer.texture)return;const i=e.textures?.find(e=>e.id===t.renderer.texture.id);if(i&&"source"in i&&i.source){const t=e?.images.find(t=>t.id===i.source.id);c.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(c,{image:s})}})}break}case g.ItemType.text:case g.ItemType.richtext:{const e=this.getActiveScene()?.scene;if(c.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.id).forEach(t=>{if(![g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:a}=t.options;Object.assign(c,{alignment:e,color:i,weight:r,text:s,font:a})})}break}}return{id:t.id,name:t.name,parentId:t.parentId??e,children:[],type:t.type,duration:t.duration,delay:t.start,endBehavior:t.endBehavior,property:c}}getViewBoxById(t){const e=new B,i=this.getPlayerItemById(t),s=this.player.getCompositions()[0]?.items.filter(e=>e.parentId===t);return i&&s?this.getViewBoxByPlayerItem(i,s):e}getViewBoxByPlayerItem(t,e){const i=new B;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,o=(new G).copyFrom(r?.transform.getWorldMatrix()??new G).invert().multiply(s.getWorldMatrix()),{x:n,y:h}=a.clone().divide(2),c=new W(n,h,0).applyMatrix(o),l=new W(n,-h,0).applyMatrix(o),p=new W(-n,-h,0).applyMatrix(o),m=new W(-n,h,0).applyMatrix(o),d=this.interactionUtils.projectPoint(c).round(2),u=this.interactionUtils.projectPoint(l).round(2),y=this.interactionUtils.projectPoint(p).round(2),g=this.interactionUtils.projectPoint(m).round(2);i.setFromVec2Array([d,u,y,g]);const f=e?.map(t=>this.getViewBoxById(t.id));f&&f.map(t=>i.union(t));break}case g.ItemType.null:{const t=e?.map(t=>this.getViewBoxById(t.id));t&&t.map(t=>i.union(t));break}}return i}getViewBoxByHeadlessPlayerItem(t,e,i){const s=new B,{transform:r,composition:a}=t;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{r.updateLocalMatrix();const{size:t}=r,o=(new G).copyFrom(a?.transform.getWorldMatrix()??new G).invert().multiply(r.getWorldMatrix()),{x:n,y:h}=t.clone().divide(2),c=new W(n,h,0).applyMatrix(o),l=new W(n,-h,0).applyMatrix(o),p=new W(-n,-h,0).applyMatrix(o),m=new W(-n,h,0).applyMatrix(o),d=i(c).round(2),u=i(l).round(2),y=i(p).round(2),g=i(m).round(2);s.setFromVec2Array([d,u,y,g]);const f=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.id)??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});f&&f.map(t=>s.union(t));break}case g.ItemType.null:{const t=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.id)??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});t&&t.map(t=>s.union(t));break}}return s}getViewportLeftTopPosition(){if(!this.sdk.pageData)return new F;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,o=new F(i,s),n=new F(r,a).multiply(t);return o.clone().divide(2).subtract(n.clone().divide(2)).add(e)}getContainerPosition(){const{offsetWidth:t,offsetHeight:e}=this.container.parentElement;return new F(t/2,e/2).add(new F(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container,r=new F(i,s).multiply(e),a=this.getViewportLeftTopPosition(),o=t.clone().subtract(a);return new F(o.x/r.x*2-1,1-o.y/r.y*2)}getActiveScene(){return this.sdk.pageData?.viewProperties[this.sdk.pageData?.activeData.view??-1]}async changeItemProperty(t){S(this.sdk.pageData,"You must call SDK#run() first");const e=this.getViewItemById(t.itemId),i=this.getPlayerItemById(t.itemId);if(e&&i)if(t.propertyName in e.property){switch(t.propertyName){case"alignment":[g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(b).setTextAlign(t.propertyValue);break;case"color":Array.isArray(t.propertyValue)&&4===t.propertyValue.length&&i.getComponent(b).setColor(t.propertyValue);break;case"font":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0],r=this.player.getAssetManager()[0];await r.processFontURL([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(b).setFontFamily(s)}break;case"text":"string"==typeof t.propertyValue&&i.getComponent(b).setText(t.propertyValue);break;case"weight":[g.TextWeight.normal,g.TextWeight.bold,g.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(b).setFontWeight(t.propertyValue);break;case"image":"string"==typeof t.propertyValue&&i.getComponent(D).setTexture(await Zt.fromImage(t.propertyValue,this.player.renderer.engine));break;case"position":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.position[i]??0));this.moveItem(t.itemId,new W(...i))}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.rotation[i]??0));this.rotateItem(t.itemId,new W(...i))}break;case"scale":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const s=t.propertyValue.map(t=>0===t||null===t?1:t),r=e.property.scale.map(t=>t||1),a=s.map((t,e)=>t/r[e]);i.scale(...a)}}["position","rotation","scale"].includes(t.propertyName)||this.player.gotoAndStop(this.sdk.pageData.time),this.changeViewItemProperty(t),this.refreshViewItem(t.itemId)}else console.warn(`Item does not have property ${t.propertyName}.`);else console.warn(`Id ${t.itemId} is not a item id.`)}changeViewItemProperty(t){S(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((e,i)=>{if(!this.sdk.pageData?.property.sync&&i!==this.sdk.pageData?.activeData.view)return;const{scene:s}=e;switch(t.propertyName){case"position":case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;case"scale":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),i=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t/(i?.[e]??0));this.changeSceneItemProperty(s,{...t,propertyValue:r})}break;default:this.changeSceneItemProperty(s,t)}})}changeSceneItemProperty(t,e){switch(e.propertyName){case"alignment":if([g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&"textAlign"in i.options&&(i.options.textAlign=e.propertyValue)}break;case"color":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.textColor=[...e.propertyValue])}break;case"font":if("string"==typeof e.propertyValue){const i=e.propertyValue.split("/"),s=i[i.length-1]?.split(".")[0],r=t.fonts?.find(t=>"family"in t&&t.family===s||"fontFamily"in t&&t.fontFamily===s);!r&&t.fonts&&s&&t.fonts.push({fontFamily:s,fontURL:e.propertyValue});const a=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));a?.options&&(a.options.fontFamily=s)}break;case"text":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.text=e.propertyValue)}break;case"weight":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontWeight=e.propertyValue)}break;case"image":if("string"==typeof e.propertyValue){t.components.filter(t=>t.item.id===e.itemId).forEach(i=>{if(!("renderer"in i))return;const s=t.textures?.find(t=>t.id===i.renderer.texture.id);if(s&&"source"in s&&s.source){const i=t?.images.find(t=>t.id===s.source.id);i?.url&&i?.webp&&(i.url=e.propertyValue,i.webp=e.propertyValue),i&&"template"in i&&i.template.background&&(i.template.background.url=e.propertyValue)}})}break;case"position":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.position.x+=e.propertyValue[0],i.transform.position.y+=e.propertyValue[1],i.transform.position.z+=e.propertyValue[2])}break;case"rotation":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.eulerHint.x+=e.propertyValue[0],i.transform.eulerHint.y+=e.propertyValue[1],i.transform.eulerHint.z+=e.propertyValue[2])}break;case"scale":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.scale.x*=e.propertyValue[0],i.transform.scale.y*=e.propertyValue[1],i.transform.scale.z*=e.propertyValue[2])}}}transformSceneItem(t,e,i){S(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach((s,r)=>{if(!this.sdk.pageData?.property.sync&&r!==this.sdk.pageData?.activeData.view)return;const{scene:a}=s;switch(e){case"position":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.position.x+=i[0],e.transform.position.y+=i[1],e.transform.position.z+=i[2])}break;case"rotation":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.eulerHint.x+=i[0],e.transform.eulerHint.y+=i[1],e.transform.eulerHint.z+=i[2])}break;case"scale":if(Array.isArray(i)&&3===i.length){const e=a.items.find(e=>e.id===t);e?.transform&&(e.transform.scale.x*=i[0],e.transform.scale.y*=i[1],e.transform.scale.z*=i[2])}}})}refreshViewItem(t){const e=this.sdk.pageData;S(e,"You must call SDK#run() first");const i=e.items.findIndex(e=>e.id===t);if(i<0)return void console.log(`item ${t} is not existed.`);const s=e.items[i],r=this.getPlayerItemById(t);r&&s&&(e.items[i]=this.createViewItemByPlayerItem(r,s.parentId))}getPlayerItemById(t){return this.player.getCompositions()[0]?.items.find(e=>e.id===t)}async keepSceneSafe(t,e,i,s,r,a){const o=JSON.parse(JSON.stringify(e));await t.loadScene(o,{reusable:!0,autoplay:!1}),t.gotoAndStop(i);const n=t.getCompositions()[0];if(n){const[t,i]=r,o=s[0]/s[1],h=t/i;o>h&&this.keepDistribute(e,n,h/o,r);const[c,l,p,m]=a,d=t-p-m,u=i-c-l,y=[(p-m)/2,(c-l)/2],g=(new B).setFromCenterAndSize(new F(t,i).divide(2),new F(t,i)),f=(new B).setFromCenterAndSize(new F(t,i).divide(2).add(new F(...y)),new F(d,u));this.keepAdsorption("centerAdsorption",e,n,y,g,f),this.keepAdsorption("topAdsorption",e,n,y,g,f),this.keepAdsorption("bottomAdsorption",e,n,y,g,f),this.keepAdsorption("leftAdsorption",e,n,y,g,f),this.keepAdsorption("rightAdsorption",e,n,y,g,f),this.keepDoubleAdsorption("bottomCenterAdsorption",e,n,y,g,f)}return e}keepDistribute(t,e,i,s){const r=t=>{const i=(new G).copyFrom(e.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===Qt[a]&&!t.parentId).forEach(a=>{const o=e.items.filter(t=>t.parentId===a.id),n=o.find(t=>"check-area"===t.name),h=n?this.getViewBoxByHeadlessPlayerItem(n,[],r):this.getViewBoxByHeadlessPlayerItem(a,o,r),c=a.transform.position.clone(),l=h.getCenter(),p=new F(...s.map(t=>t/2)),m=l.y-p.y;((t,i,r)=>{const{z:a}=t.transform.getWorldPosition(),{x:o,y:n}=e.camera.getInverseVPRatio(a);t.transform.translate(2*i*o/s[0],-2*r*n/s[1],0)})(a,0,m/i-m),a.transform.updateLocalMatrix();const d=a.transform.position.clone().subtract(c).toArray();this.changeSceneItemProperty(t,{itemId:a.id,type:a.type,propertyName:"position",propertyValue:d})})})}keepAdsorption(t,e,i,s,r,a){const{x:o,y:n}=r.getSize(),h=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:h}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/o,-2*s*h/n,0)},c=t=>{const e=(new G).copyFrom(i.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},l=Qt[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===l&&!t.parentId).forEach(r=>{const o=i.items.filter(t=>t.parentId===r.id),n=o.find(t=>"check-area"===t.name),l=r.transform.position.clone(),p=["leftAdsorption","rightAdsorption"].includes(t)&&0!==s[0]||["topAdsorption","bottomAdsorption"].includes(t)&&0!==s[1],m=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",d=["leftAdsorption","topAdsorption"].includes(t)?1:-1,u=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",y=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",g=3===r.name.split("-").length,f=Number(r.name.split("-")[1]),w=new F,x=new F,P=[1,1,1],v=n?this.getViewBoxByHeadlessPlayerItem(n,[],c):this.getViewBoxByHeadlessPlayerItem(r,o,c),S=Math.max(v[u][m]-a[u][m],0);h(r,...s),v.getSize().x>a.getSize().x&&(P[0]=a.getSize().x/v.getSize().x,P[1]=a.getSize().x/v.getSize().x,r.scale(...P)),r.transform.updateLocalMatrix();const D=(n?this.getViewBoxByHeadlessPlayerItem(n,[],c):this.getViewBoxByHeadlessPlayerItem(r,o,c))[u][m]-a[u][m];D!==S*P[0]&&p&&(w[m]=S*P[0]-D,h(r,...w.toArray()),r.transform.updateLocalMatrix());const b=n?this.getViewBoxByHeadlessPlayerItem(n,[],c):this.getViewBoxByHeadlessPlayerItem(r,o,c),I=new F;if(!a.containsBox(b)){const{min:t,max:e}=b,{min:i,max:s}=a;I.x+=t.x<i.x?i.x-t.x:0,I.x+=e.x>s.x?s.x-e.x:0,I.y+=t.y<i.y?i.y-t.y:0,I.y+=e.y>s.y?s.y-e.y:0,I.multiply(P[0]),h(r,...I.toArray()),r.transform.updateLocalMatrix()}if(!Number.isNaN(f)&&g)if("centerAdsorption"!==t){const t=Math.abs(b[y][m]+I[m]+w[m]-a[u][m]),e=a.getSize()[m]*f;t>e&&(x[m]=(e-t)*d,h(r,...x.toArray()),r.transform.updateLocalMatrix())}else{const t=b.getSize().y,e=a.getSize().y;if(t/e>f){const i=e*f/t;r.scale(i,i,1),P[0]*=i,P[1]*=i}}const T=r.transform.position.clone().subtract(l).toArray();this.changeSceneItemProperty(e,{itemId:r.id,type:r.type,propertyName:"position",propertyValue:T}),this.changeSceneItemProperty(e,{itemId:r.id,type:r.type,propertyName:"scale",propertyValue:P})})}keepDoubleAdsorption(t,e,i,s,r,a){const{x:o,y:n}=r.getSize(),h=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:h}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/o,-2*s*h/n,0)},c=t=>{const e=(new G).copyFrom(i.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,n)},l=Qt[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===l&&!t.parentId).forEach(t=>{const r=i.items.filter(e=>e.parentId===t.id),o=r.find(t=>"check-area"===t.name),n=t.transform.position.clone(),l=3===t.name.split("-").length,p=Number(t.name.split("-")[1]),m=[1,1,1],d=o?this.getViewBoxByHeadlessPlayerItem(o,[],c):this.getViewBoxByHeadlessPlayerItem(t,r,c);h(t,...s),d.getSize().x>a.getSize().x&&(m[0]=a.getSize().x/d.getSize().x,m[1]=a.getSize().x/d.getSize().x,t.scale(...m)),t.transform.updateLocalMatrix();const u=o?this.getViewBoxByHeadlessPlayerItem(o,[],c):this.getViewBoxByHeadlessPlayerItem(t,r,c);if(!Number.isNaN(p)&&l){const e=u.getSize().y,i=a.getSize().y;if(e/i>p){const s=i*p/e;t.scale(s,s,1),m[0]*=s,m[1]*=s}}const y=new F;if(!a.containsBox(u)){const{min:e,max:i}=u,{min:s,max:r}=a;y.x+=e.x<s.x?s.x-e.x:0,y.x+=i.x>r.x?r.x-i.x:0,y.y+=e.y<s.y?s.y-e.y:0,y.y+=i.y>r.y?r.y-i.y:0,y.multiply(m[0]),h(t,...y.toArray()),t.transform.updateLocalMatrix()}const g=t.transform.position.clone().subtract(n).toArray();this.changeSceneItemProperty(e,{itemId:t.id,type:t.type,propertyName:"position",propertyValue:g}),this.changeSceneItemProperty(e,{itemId:t.id,type:t.type,propertyName:"scale",propertyValue:m})})}};import ee from"jszip";function ie(t,e="asserts failed"){if(!t)throw new Error(e)}function se(t,e,...i){const s=e.reduce((t,e)=>t?`${t} ${e}`:e,""),r="color: #108ee9;";switch(t){case"error":console.error(`%c[${s}]`,r,...i);break;case"info":console.info(`%c[${s}]`,r,...i);break;case"debug":console.debug(`%c[${s}]`,r,...i);break;case"warn":console.warn(`%c[${s}]`,r,...i);break;default:console.log(`%c[${s}]`,r,...i)}}var re="ready",ae="executable",oe="dispose",ne={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},he="idle",ce="convertImage",le="transcoding",pe="audio",me="jpeg",de="webp",ue="png",ye=(ne.MP4,ne.WebP,ne.APNG,ne.GIF,ne.AlphaMaskVideo,ne.Images,ne.MP4,ne.WebP,ne.APNG,ne.GIF,ne.AlphaMaskVideo,ne.Images,class{constructor(t){h(this,"sampleRate"),h(this,"duration"),h(this,"channels");const{sampleRate:e=44100,duration:i=1,channels:s=2}=t??{};this.sampleRate=e,this.duration=i,this.channels=s}getBuffer(){const t=this.sampleRate*this.duration*this.channels*2,e=44+t,i=new ArrayBuffer(e),s=new DataView(i);let r=0;const a=t=>{for(let e=0;e<t.length;e++)s.setUint8(r++,t.charCodeAt(e))},o=t=>{s.setUint32(r,t,!0),r+=4},n=t=>{s.setUint16(r,t,!0),r+=2};a("RIFF"),o(e-8),a("WAVE"),a("fmt "),o(16),n(1),n(this.channels),o(this.sampleRate),o(this.sampleRate*this.channels*2),n(2*this.channels),n(16),a("data"),o(t);for(let e=0;e<t;e++)s.setUint8(r++,0);return new Uint8Array(i)}});import{FFmpeg as ge}from"@ffmpeg/ffmpeg";import{toBlobURL as fe}from"@ffmpeg/util";var we={SCRIPT:"https://gw.alipayobjects.com/os/gltf-asset/99531561844014/img2webp.js",WASM:"https://mdn.alipayobjects.com/mars/uri/file/as/0.0.4/wasm/img2webp/img2webp.wasm"},xe={CLASSWORKER:"https://mdn.alipayobjects.com/rms/uri/file/as/ffmpeg/core/0.12.10/dist/worker.js",DEFAULT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.wasm"},MT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.wasm",WORKER:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.worker.js"}};function Pe(t,e,i,s){const r=e.getContext("2d");ie(r),r.clearRect(0,0,e.width,e.height),i&&(r.save(),r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.restore()),s&&r.drawImage(s,0,0,s.width,s.height,0,0,e.width,e.height),r.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height)}async function ve(){return new Promise(async(t,e)=>{try{await function(t,e={}){return new Promise((i,s)=>{const r=document.querySelector(`script[src="${t}"]`);if(r)return"true"===r.dataset.loaded?void i(r):(r.addEventListener("load",()=>{i(r)}),void r.addEventListener("error",()=>{s(new Error(`Script already failed: ${t}`))}));const a=document.createElement("script");a.src=t,a.async=!0,Object.keys(e).forEach(t=>{a.setAttribute(t,e[t]??"")}),a.onload=()=>{a.dataset.loaded="true",i(a)},a.onerror=()=>{s(new Error(`Failed to load script: ${t}`))},document.head.appendChild(a)})}(we.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?we.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}var Se,De,be,Ie,Te,Ae,Ee,Ce,Ve,Me,ze,ke,_e,Fe,Re,Be,Ke,Ue,We=["@vvfx/sdk","ExportVideo"],Ge=class extends v{constructor(t){super(),h(this,"status",re),h(this,"stage",he),h(this,"mediaType"),h(this,"loggerInTranscoding"),h(this,"multiThreading"),h(this,"extraCanvas"),h(this,"player"),p(this,Se,0),p(this,De),p(this,be),p(this,Ie),p(this,Te),p(this,Ae,[]),p(this,Ee),p(this,Ce),p(this,Ve,[]),p(this,Me,0),p(this,ze),p(this,ke,[]),p(this,_e,0),p(this,Fe,0),p(this,Re,0),p(this,Be,0),p(this,Ke,[]),p(this,Ue,!0);const{mediaType:e,extraCanvas:i,loggerInTranscoding:s,multiThreading:r}=t;this.mediaType=e,this.loggerInTranscoding=s??!1,this.multiThreading=r??!1,this.extraCanvas=i??void 0,this.onInit()}get canceled(){return this.status===oe}get config(){const t=this.player?.getCompositions()??[],e=t?.[0],i=e?.name??(new Date).getTime().toString(),s=e?.getDuration()??0,r=e?.startTime??0,a=l(this,ze)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:l(this,ze)?.fps??30,backgroundColor:l(this,ze)?.backgroundColor??"#000000",loop:l(this,ze)?.loop??!0,audioEnable:l(this,ze)?.audioEnable??!1}}get progress(){const t=l(this,Fe)||1,e=l(this,Re)||1,i=Math.min(t/e,1),s=Math.min(l(this,_e),t)/t*.4,r=Math.min(l(this,Be),t)/t*.6,a=Math.min(s+r,1);l(this,ke)[l(this,Me)]=i;const o=l(this,ke).reduce((t,e,i)=>i<l(this,Me)?t+(e||0):t,0)+a*i;return Math.min((n=o,Math.round(100*n)/100),1);var n}get transImageType(){return this.mediaType===ne.MP4?me:this.mediaType===ne.WebP?de:ue}async onInit(){try{se("log",[...We,"ready"],"starting"),this.status=re,await this.loadHelper(this.mediaType),this.status=ae,se("log",[...We,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=oe,this.onError(t)}finally{return this.status}}onReset(){this.stage=he,window.cancelAnimationFrame(l(this,Se)),m(this,Se,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){se("log",[...We,"error"],t),this.onFinish(!1),this.emit("error",t),this.dispose()}onFinish(t,e){se("log",[...We,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("done",!!t),this.emit("finish",t,e)}async loadHelper(t){const e="WebP"===t&&!l(this,Ie),i=[ne.MP4,ne.APNG,ne.GIF,ne.AlphaMaskVideo].includes(t)&&!l(this,be);e&&m(this,Ie,await ve()),i&&(m(this,be,await async function(t){const{multiThreading:e}=t??{},i=new ge,s=!!e,r={classWorkerURL:await fe(xe.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await fe(xe.MT.CORE,"text/javascript"),r.wasmURL=await fe(xe.MT.WASM,"application/wasm"),r.workerURL=await fe(xe.MT.WORKER,"text/javascript")):(r.coreURL=await fe(xe.DEFAULT.CORE,"text/javascript"),r.wasmURL=await fe(xe.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),l(this,be).on("log",({message:t})=>{if(this.loggerInTranscoding&&se("log",[...We,"transcoding log"],t),this.canceled||this.stage!==le)return;const e=/frame=\s*(\d+)/.exec(t);if(e?.[1]){const t=Number(e[1]);this.setProgress({currentTaskInTranscodingFrameIndex:t})}}))}getAllTaskFrames(t){return t.reduce((t,e)=>{const{scene:i}=e,s=i.compositions?.[0]?.duration??0;return t+Math.round(s*this.config.fps)},0)}setProgress(t){void 0!==t?.completedTaskPercentArray&&m(this,ke,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&m(this,_e,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&m(this,Fe,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&m(this,Be,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&m(this,Re,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){S(this.player);const{oldTotalTime:i,startTime:s}=this.config;S(i);const r=1e3*i-1e3*i%15;return t=Math.min(t,r/1e3),e?this.player.gotoAndPlay(t-s):this.player.gotoAndStop(t-s),t}getWavAudio(t){m(this,Ee,new ye),l(this,be)?l(this,be).writeFile(t,l(this,Ee).getBuffer()):se("log",[...We,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new ee,s=i.folder(t);return S(s),l(this,Ve).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){S(l(this,Ie));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${l(this,Ve).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=l(this,Ie).cwrap("main","string",["number","number"]),[r,a]=function(t,e){const i=t._malloc(e.length*Uint32Array.BYTES_PER_ELEMENT);return e.forEach((e,s)=>{const r=t._malloc(e.length+1);t.writeAsciiToMemory(e,r),t.setValue(i+Uint32Array.BYTES_PER_ELEMENT*s,r,"i32")}),[e.length,i]}(l(this,Ie),i);ie(r&&a,"getWebP has error"),s(r,a);const o=l(this,Ie).FS.readFile(e);return l(this,Ve).forEach(t=>{l(this,Ie)?.FS.unlink(t)}),o}async getAPNG(){S(l(this,be));this.stage=le;const t="export.apng";return await l(this,be).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-plays",this.config.loop?"0":"1","-y",t]),t}async getGIF(){S(l(this,be));this.stage=le;const t="export.gif";return await l(this,be).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-loop",this.config.loop?"0":"-1","-vf","scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse","-y",t]),t}async getMP4(t,e){S(l(this,be));this.stage=le;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;return this.config.audioEnable&&!l(this,Ee)&&(m(this,Ce,"audio.wav"),this.getWavAudio(l(this,Ce))),await l(this,be).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${r}`,"-y",i]),l(this,Ce)&&l(this,Ee)&&(this.stage=pe,s="export-with-audio.mp4",await l(this,be).exec(["-i",i,"-i",l(this,Ce),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s])),s&&l(this,be).deleteFile(i).catch(()=>{se("log",[...We,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){S(l(this,be));this.stage=le;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await l(this,be).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${s}`,"-y",i]),i}async getVideoByType(t,e){S(l(this,be));const i=this.mediaType===ne.APNG,s=this.mediaType===ne.GIF,r=this.mediaType===ne.AlphaMaskVideo,a=this.mediaType===ne.MP4;let o="";try{i&&(o=await this.getAPNG()),s&&(o=await this.getGIF()),a&&(o=await this.getMP4(t,e)),r&&(o=await this.getAlphaMaskVideo(t,e)),this.stage=he}catch(t){throw t}finally{for(const t of l(this,Ve))t&&l(this,be).deleteFile(t)}let n=null;try{S(o);const t=await l(this,be).readFile(o);n="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{l(this,be).deleteFile(o).catch(()=>{se("log",[...We,"ffmpeg delete file error"])})}return n}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});m(this,Te,e),l(this,Te).start(0);const i=[];l(this,Te).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},m(this,Ae,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n}=t;S(this.player),S(l(this,De));const h=l(this,_e)+1;this.stage=ce,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:h}),this.loggerInTranscoding&&se("log",[...We,"converting log"],`converting ${h} frame image`),h>1&&this.forwardPlayerTime(h/this.config.fps+a),Pe(l(this,De),s,this.config.backgroundColor);let c=s;this.mediaType===ne.AlphaMaskVideo&&(S(this.extraCanvas),function(t,e){e.width=2*t.width,e.height=t.height;const i=t.getContext("2d");if(!i)throw new Error("inputCtx is null");const s=e.getContext("2d");if(!s)throw new Error("ctx is null");s.clearRect(0,0,e.width,e.height);const r=i.getImageData(0,0,t.width,t.height),a=i.getImageData(0,0,t.width,t.height),o=r.data;for(let t=0;t<o.length;t+=4){const e=Math.max(0,(o[t+3]??0)-5)/250*255;e<=0?(o[t]=0,o[t+1]=0,o[t+2]=0,o[t+3]=255):(o[t]=(o[t]??0)*e/255,o[t+1]=(o[t+1]??0)*e/255,o[t+2]=(o[t+2]??0)*e/255,o[t+3]=255)}s.putImageData(r,0,0);const n=a.data;for(let t=0;t<n.length;t+=4){const e=Math.max(0,(n[t+3]??0)-5)/250*255;n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=255}s.putImageData(a,t.width,0)}(s,this.extraCanvas),c=this.extraCanvas);const p=await async function(t,e,i){return new Promise((s,r)=>{t.toBlob(t=>{t?s(t.arrayBuffer()):r("toBlob failed")},e,i)})}(c,`image/${this.transImageType}`,1),d=`image-${e=h,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===ne.Images?r.push(p):this.mediaType===ne.WebP?(S(l(this,Ie)),l(this,Ie).FS.writeFile(d,new Uint8Array(p))):(S(l(this,be)),await l(this,be).writeFile(d,new Uint8Array(p))),l(this,Ve).push(d);if(h===l(this,Fe)){this.player?.pause(),await new Promise(t=>{window.requestAnimationFrame(t)});let t=null;"Images"===this.mediaType?t=await this.getImagesZip(this.config.name,r):"WebP"===this.mediaType?t=this.getWebP():[ne.MP4,ne.APNG,ne.GIF,ne.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(o,n)??null),t&&(se("log",[...We,"done"],"success"),this.emit("done",!0,t))}else m(this,Se,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:o,newTotalTime:n})}))}catch(t){this.onError(t)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;S(this.player),S(l(this,De));const e=l(this,_e)+1;if(this.stage=ce,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&se("log",[...We,"converting log"],`converting ${e} frame image`),Pe(l(this,De),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<l(this,Fe))m(this,Se,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),l(this,Te)?.stop();const t=new Blob(l(this,Ae),{type:"video/webm"}),e=await t.arrayBuffer();se("log",[...We,"done"],"success"),this.emit("done",!0,e)}}catch(t){se("log",[...We,"done"],"failed",t),this.emit("done",!1)}}async runTask(t){try{if(this.canceled)return;S(this.player),S(l(this,De));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[o,n]=e;if(l(this,De).width=o,l(this,De).height=n,s.width=o,s.height=n,this.player.resize(),m(this,Ve,[]),[ne.MP4,ne.APNG,ne.Images,ne.WebP,ne.GIF,ne.AlphaMaskVideo].includes(this.mediaType)){const t={canvas:s,imageBuffers:[],startTime:i,oldTotalTime:r,newTotalTime:a};await this.onExportImageFrame(t)}else"WebM"===this.mediaType&&await this.onExportWebMFrame(s)}catch(t){se("log",[...We,"run task error"],t),this.emit("done",!1)}}clearTaskInfo(){m(this,Me,0),m(this,ze,void 0),m(this,ke,[]),m(this,_e,0),m(this,Fe,0),m(this,Re,0),m(this,Be,0),m(this,Ke,[]),m(this,Ue,!0)}clearFFMpegCore(){if(l(this,be)){for(const t of l(this,Ve))t&&l(this,be).deleteFile(t);m(this,Ve,[]),l(this,be).terminate(),m(this,be,void 0)}}clearImage2WebPCore(){l(this,Ie)&&(l(this,Ie).FS.quit(),m(this,Ie,void 0))}clearMediaRecorder(){l(this,Te)&&(l(this,Te).stop(),m(this,Te,void 0)),m(this,Ae,[])}clearAllListeners(){for(const t of this.getListeners("ready"))this.off("ready",t);for(const t of this.getListeners("progress"))this.off("progress",t);for(const t of this.getListeners("done"))this.off("done",t);for(const t of this.getListeners("finish"))this.off("finish",t);for(const t of this.getListeners("error"))this.off("error",t)}onCancel(){this.canceled||(this.onFinish(!1),this.status=oe,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),se("log",We,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===re)return se("log",[...We],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===oe){if(await this.onInit()===oe)throw new Error("init environment failed")}if(this.clearTaskInfo(),!l(this,De)){const t=document.createElement("canvas");t.dataset.key="player-canvas",m(this,De,t)}this.player||(this.player=new w({canvas:l(this,De),pixelRatio:1,transparentBackground:!0,renderOptions:{willCaptureImage:!0}}),this.player.on("rendererror",t=>{this.onError(t)}),this.player.on("webglcontextlost",t=>{this.onError(t)}));let e=null;e??(e=document.querySelector('canvas[data-key="container-canvas"]')),e??(e=document.createElement("canvas")),e.dataset.key="container-canvas",e.style.display="none",this.setProgress({allTaskFrames:this.getAllTaskFrames(t)});const i=[];let s=!0;for(const[r,a]of t.entries()){if(this.canceled){s=!1;break}m(this,Me,r),m(this,ze,a);const{size:t,scene:o}=a;await new Promise(async n=>{try{if(!this.player)throw new Error("player not found");se("log",[...We,"export"],"start",a),this.player.destroyCurrentCompositions(),await this.player.loadScene(o,{env:"editor",autoplay:!1});const h=this.config.oldTotalTime,c=0;this.player.pause(),this.setProgress({currentTaskFrameIndex:0,currentTaskTotalFrames:Math.round(h*this.config.fps)});const l=(t,e)=>{this.off("done",l),t&&e?i[r]=e:s=!1,n()};this.on("done",l);const p={size:t,startTime:c,containerCanvas:e};await this.runTask(p)}catch(t){se("log",[...We,"export error"],t),s=!1,n()}})}m(this,Ke,i),m(this,Ue,s)}catch(t){this.onError(t),m(this,Ue,!1)}e>1&&l(this,Ue)?this.onFinish(!0,l(this,Ke)):this.onFinish(!1)}dispose(){this.status=oe,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,l(this,De)?.remove(),m(this,De,void 0),m(this,Ce,void 0),m(this,Ee,void 0)}};async function Ne(t,e,i,s){const[r,a]=e,o=JSON.parse(JSON.stringify(i));await t.loadScene(o,{reusable:!0,autoplay:!1}),t.gotoAndStop(s);const n=document.createElement("canvas");n.width=r,n.height=a;const h=n.getContext("2d");h&&(h.fillStyle="rgba(255, 255, 255, 1)",h.fillRect(0,0,r,a),function(t,e,i,s,r,a,o,n,h){2===arguments.length&&(i=s=0,r=t.canvas.width,a=t.canvas.height);o="number"==typeof o?C(o,0,1):.5,n="number"==typeof n?C(n,0,1):.5,h??(h={left:0,top:0,width:e instanceof HTMLVideoElement?e.videoWidth:e.width,height:e instanceof HTMLVideoElement?e.videoHeight:e.height});const c=h.width,l=h.height,p=Math.min(r/c,a/l);let m=c*p,d=l*p,u=1;m<r&&(u=r/m);Math.abs(u-1)<1e-14&&d<a&&(u=a/d);m*=u,d*=u;const y=Math.max(c/(m/r),0),g=Math.max(l/(d/a),0),f=Math.min((c-y)*o,c),w=Math.min((l-g)*n,l);t.drawImage(e,f+h.left,w+h.top,y,g,i,s,r,a)}(h,t.canvas,0,0,r,a,.5,.5));return n.toDataURL("image/png")}Se=new WeakMap,De=new WeakMap,be=new WeakMap,Ie=new WeakMap,Te=new WeakMap,Ae=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ve=new WeakMap,Me=new WeakMap,ze=new WeakMap,ke=new WeakMap,_e=new WeakMap,Fe=new WeakMap,Re=new WeakMap,Be=new WeakMap,Ke=new WeakMap,Ue=new WeakMap;var Oe={DEFAULT:"default",EXPORTING:"exporting",SUCCESS:"success",ERROR:"error"},He=class{constructor(t){h(this,"_eventEmitter",new v),h(this,"_pageData"),h(this,"_screenShotContainer"),h(this,"_screenShotPlayer"),h(this,"_SDKUtils"),h(this,"_ExportVideo"),h(this,"_gestureHandler"),h(this,"_playerContainer"),h(this,"_exportStatus",Oe.DEFAULT),h(this,"disposables",[]),h(this,"player"),h(this,"on",this._eventEmitter.on);const[e,i]=[t.offsetWidth,t.offsetHeight],s=document.createElement("div");s.id="player-container",s.style.width=`${e}px`,s.style.height=`${i}px`,s.style.position="absolute",s.style.backgroundRepeat="no-repeat",s.style.backgroundPosition="center center",t.appendChild(s),this._playerContainer=s,this.player=new w({container:s,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this._gestureHandler=new Xt(t),this._gestureHandler.registerViewEvent(),this.player.on("update",()=>{S(this._pageData,"You must call SDK#run() first");const t=this.player.getCompositions()[0]?.time;if(this._pageData.playing)if(void 0!==t)this._pageData.time===t&&this.player.pause(),this._pageData.time=t,this._SDKUtils.refreshPageTime(t);else{this._pageData.playing=!1,this.setPlayProgress(100);const t=this._pageData.viewProperties[this._pageData.activeData.view??0]?.scene,e=t?.compositions.find(e=>e.id===t.compositionId);this._pageData.time=e?.duration??2,this._SDKUtils.refreshPageTime(this._pageData.time)}this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}),this._screenShotContainer=document.createElement("canvas"),this._screenShotPlayer=new w({canvas:this._screenShotContainer,manualRender:!0,renderOptions:{willCaptureImage:!0}}),this._eventEmitter.on("pageDataChange",t=>{this._pageData=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("zoomChange",t=>{S(this._pageData,"You must call SDK#run() first"),this._pageData.property.zoom=t,this._SDKUtils.refreshInteractionParam(),this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.refresh(),this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.view=t;const e=this._pageData.viewProperties[t];this._gestureHandler.ignoreInteraction=!!e?.ignoreInteraction}),this._SDKUtils=new te(this.player,s,this._eventEmitter,this),this._ExportVideo=new Ge({mediaType:"MP4"});const r=new ResizeObserver(()=>{const e=[t.offsetWidth,t.offsetHeight],i=this._pageData?.viewProperties[this._pageData.activeData.view??0];S(i);const{size:s}=i,[r,a]=this._SDKUtils.getPlayerSizeByParent(e,s);this._playerContainer.style.width=`${r}px`,this._playerContainer.style.height=`${a}px`,this.player.resize(),this._gestureHandler.resize()});r.observe(t),this.disposables.push(()=>{r.disconnect()})}get pageData(){return this._pageData}get exportStatus(){return this._exportStatus}get exportOptions(){if(!this.pageData)return[];return this.pageData.viewProperties.filter(t=>!t.ignoreInteraction).map(t=>{const{size:e,scene:i,export:{time:s,audioEnable:r}}=t;return{size:e,scene:JSON.parse(JSON.stringify(i)),time:s,audioEnable:r}})}dispose(){this.player?.dispose(),this._screenShotPlayer?.dispose(),this._pageData=void 0,this._playerContainer.remove(),this._ExportVideo.dispose(),this._gestureHandler.dispose(),this.disposables.forEach(t=>{t()})}async getInitParam(t){const e=JSON.parse(JSON.stringify(t));if("string"==typeof e.scene)try{const t=await fetch(e.scene,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);const i=await t.json();return{...e,scene:i}}catch(t){throw new Error(`Failed to fetch scene data from ${e.scene}: ${t instanceof Error?t.message:String(t)}`)}return{...e,scene:e.scene}}async initSDK(t){const{scene:e,viewParams:i,options:s}=t,r=[];{const t=JSON.parse(JSON.stringify(e)),i=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(i){const[e,s]=i.previewSize??[1080,1920],a=i.duration??0;this._screenShotContainer.width=e,this._screenShotContainer.height=s,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize();const o=await Ne(this._screenShotPlayer,[e,s],t,a);r.push({size:[e,s],safeArea:[0,0,0,0],id:0,scene:t,thumbnail:o,ignoreInteraction:!0,export:{time:a,fileSizeLimit:1,audioEnable:!1}})}}for(let s=0;s<i.length;s++){const a=i[s];if(!a)continue;let o=JSON.parse(JSON.stringify(e));const n=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0];S(n);const h=n.previewSize??a.size,[c,l]=a.size;n.previewSize=[c,l];const p=n.duration??0;this._screenShotContainer.width=c,this._screenShotContainer.height=l,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize();const m=await Ne(this._screenShotPlayer,a.size,o,p);t.keepSafe&&(this._screenShotContainer.width=c,this._screenShotContainer.height=l,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize(),o=await this._SDKUtils.keepSceneSafe(this._screenShotPlayer,o,p,h,[c,l],a.safeArea)),r.push({...a,id:s+1,scene:o,thumbnail:m,ignoreInteraction:!1})}const a=r[0]?.scene;if(!a)return void console.warn("SDK need a view property at least.");const o=a.compositions.find(t=>t.id===a.compositionId)??a.compositions[0],n={...s,zoom:1,translation:[0,0],sync:!1},h=(o?.duration??0)-.1;this._pageData={time:h,property:n,activeData:{selectedItems:[]},items:[],viewProperties:r,playing:!1},this._SDKUtils.init(),this._gestureHandler.init(this._SDKUtils),this._gestureHandler.ignoreInteraction=!!r[0]?.ignoreInteraction,await this._SDKUtils.loadScene(0),this._SDKUtils.refreshPageTime(h)}async run(t){const e=await this.getInitParam(t);await this.initSDK(e),this._eventEmitter.emit("pageDataChange",this.getPageData())}getPageData(){return JSON.parse(JSON.stringify(this._pageData))}getActiveItems(){return S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem??""}setSelectedItems(t){this._SDKUtils.clearPreSelectedItem(),this._SDKUtils.clearSelectedItems(),this._SDKUtils.addSelectedItems([...t])}getItemProperty(t){S(this._pageData,"You must call SDK#run() first");const e=this._pageData.items.find(e=>e.id===t.itemId);if(e&&e.type===t.type)return{type:e.type,property:e.property}}getItemPropertyValue(t){S(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){S(this._pageData,"You must call SDK#run() first");const e=this._pageData.viewProperties[this._pageData.activeData.view??0]?.ignoreInteraction;e?console.warn("Static scene cannot change."):(await this._SDKUtils.changeItemProperty(t),this._gestureHandler.refresh(),this._gestureHandler.render())}async generateScreenShot(t){S(this._pageData,"You must call SDK#run() first");const e=this.pageData?.viewProperties?.[t];if(!e)return"";const{scene:i,size:[s,r]}=e,a=i.compositionId,o=i.compositions.find(t=>t.id===a),n=o?.duration??0;this._screenShotContainer.width=s,this._screenShotContainer.height=r,this._screenShotPlayer.destroyCurrentCompositions(),this._screenShotPlayer.resize();const h=JSON.parse(JSON.stringify(i));return await Ne(this._screenShotPlayer,[300,400],h,n)}async switchScene(t){if(S(this._pageData,"You must call SDK#run() first"),t===this._pageData.activeData.view)return;this._pageData.viewProperties[t]?(this._pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},await this._SDKUtils.loadScene(t)):console.warn("target scene does not exist."),this._eventEmitter.emit("selectedViewChange",t),this._eventEmitter.emit("pageDataChange",this.getPageData())}getConfig(){return S(this._pageData,"You must call SDK#run() first"),{safeAreaPreview:this._pageData.property.safeAreaPreview,zoom:this._pageData.property.zoom,adsorption:this._pageData.property.adsorption,sync:this._pageData.property.sync}}setConfig(t){S(this._pageData,"You must call SDK#run() first");const{adsorption:e,safeAreaPreview:i,zoom:s}=this._pageData.property;this._pageData.property={...this._pageData.property,...t},this._pageData.property.zoom!==s&&this._SDKUtils.setPageZoom(this._pageData.property.zoom),e!==t.adsorption&&this._gestureHandler.setAdsorptionEnabled(t.adsorption),i!==t.safeAreaPreview&&this._gestureHandler.setSafeAreaPreviewEnabled(t.safeAreaPreview),this._gestureHandler.refresh(),this._gestureHandler.render()}async setPlayProgress(t){S(this._pageData,"You must call SDK#run() first");const e=(this.player.getCompositions()[0]?.getDuration()??2)*t/100;this._pageData.time=e;!this.player.getCompositions().length&&(this.player.destroyCurrentCompositions(),await this._SDKUtils.loadScene(this._pageData.activeData.view??0)),this._pageData.playing?this.player.gotoAndPlay(e):this.player.gotoAndStop(e),this._SDKUtils.refreshPageTime(e)}getViewItems(){return this.getPageData()?.items??[]}setPlayState(t){S(this._pageData,"You must call SDK#run() first");const e="play"===t;this._pageData.playing!==e&&(this._pageData.playing=e,this._gestureHandler.ignoreInteraction=e,e?this.player.gotoAndPlay(this._pageData.time):this.player.gotoAndStop(this._pageData.time),this._gestureHandler.refresh(),this._gestureHandler.render())}getViewThumbnail(){return S(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:t.thumbnail}))}onExportProgress(t){this._eventEmitter.emit("exportProgress",t)}onExportFinish(t,e){this._exportStatus=t?Oe.SUCCESS:Oe.ERROR,this._eventEmitter.emit("exportComplete",t);const i=this.exportOptions[0]?.scene?.compositions?.[0]?.name??"videos";if(e&&e.length>0){const t=new d;e.forEach((e,s)=>{const{size:r}=this.exportOptions[s]??{},a=r?.[0]&&r?.[1]?`(${s+1})_${r[0]}×${r[1]}`:`(${s+1})`,o=`${i}${a}.mp4`;t.file(o,e)}),t.generateAsync({type:"blob"}).then(t=>{!function(t,e,i="application/octet-stream"){const s=new Blob(Array.isArray(t)?t:[t],{type:i}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}(t,`${i}.zip`,"application/zip")}).catch(t=>{se("error",["@vvfx/sdk"],"exportAllVideos is error",t)})}}onExportError(t){this._exportStatus=Oe.ERROR,se("error",["@vvfx/sdk"],"exportAllVideos is error",t)}exportAllVideos(){S(this.pageData,"You must call SDK#run() first"),this._exportStatus=Oe.EXPORTING,this._ExportVideo.onExport(this.exportOptions),this._ExportVideo.on("progress",this.onExportProgress.bind(this)),this._ExportVideo.once("finish",this.onExportFinish.bind(this)),this._ExportVideo.on("error",this.onExportError.bind(this))}cancelExportAllVideos(){this._exportStatus=Oe.ERROR,this._ExportVideo.onCancel(),this._eventEmitter.emit("exportComplete",!1)}async loadPageData(t){S(this._pageData,"You must call SDK#run() first"),this._pageData.activeData={view:this._pageData.viewProperties.length,selectedItems:[],preSelectedItem:void 0},this._pageData.viewProperties.push(...t.viewProperties),this._SDKUtils.init(),this._gestureHandler.init(this._SDKUtils),await this._SDKUtils.loadScene(this.pageData?.activeData.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}async runByPageData(t){const e=JSON.parse(JSON.stringify(t));e.property.zoom=1,e.property.translation=[0,0],this._pageData=e,this._SDKUtils.init(),this._gestureHandler.init(this._SDKUtils),await this._SDKUtils.loadScene(this.pageData?.activeData.view??0),this._SDKUtils.refreshPageTime(this._pageData.time),this._eventEmitter.emit("pageDataChange",this.getPageData())}};export{Oe as ExportStatusMap,He as SDK,g as spec};
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "require": "./dist/index.cjs"
18
18
  }
19
19
  },
20
- "version": "0.0.0-alpha.5",
20
+ "version": "0.0.0-alpha.6",
21
21
  "dependencies": {
22
22
  "@ffmpeg/ffmpeg": "0.12.15",
23
23
  "@ffmpeg/util": "0.12.2",