gfxlite 0.1.0
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/LICENSE +21 -0
- package/README.md +74 -0
- package/dist/gfxlite.es.js +6081 -0
- package/dist/gfxlite.umd.js +1455 -0
- package/dist/types/core/camera/Camera.d.ts +13 -0
- package/dist/types/core/camera/OrthographicCamera.d.ts +11 -0
- package/dist/types/core/camera/PerspectiveCamera.d.ts +9 -0
- package/dist/types/core/controls/OrbitControls.d.ts +84 -0
- package/dist/types/core/environment/Environment.d.ts +25 -0
- package/dist/types/core/environment/EnvironmentManager.d.ts +44 -0
- package/dist/types/core/geometry/BoxGeometry.d.ts +13 -0
- package/dist/types/core/geometry/CircleGeometry.d.ts +11 -0
- package/dist/types/core/geometry/ConeGeometry.d.ts +17 -0
- package/dist/types/core/geometry/CylinderGeometry.d.ts +19 -0
- package/dist/types/core/geometry/Geometry.d.ts +27 -0
- package/dist/types/core/geometry/PlaneGeometry.d.ts +15 -0
- package/dist/types/core/geometry/SphereGeometry.d.ts +13 -0
- package/dist/types/core/geometry/TorusGeometry.d.ts +15 -0
- package/dist/types/core/light/DirectionalLight.d.ts +19 -0
- package/dist/types/core/light/Light.d.ts +7 -0
- package/dist/types/core/material/BasicMaterial.d.ts +20 -0
- package/dist/types/core/material/LambertMaterial.d.ts +20 -0
- package/dist/types/core/material/Material.d.ts +34 -0
- package/dist/types/core/material/PhongMaterial.d.ts +22 -0
- package/dist/types/core/material/StandardMaterial.d.ts +42 -0
- package/dist/types/core/material/Texture.d.ts +24 -0
- package/dist/types/core/material/TextureManager.d.ts +18 -0
- package/dist/types/core/object/Mesh.d.ts +8 -0
- package/dist/types/core/object/Object3D.d.ts +35 -0
- package/dist/types/core/renderer/BatchManager.d.ts +82 -0
- package/dist/types/core/renderer/CullingComputePhase.d.ts +13 -0
- package/dist/types/core/renderer/DepthPrePhase.d.ts +17 -0
- package/dist/types/core/renderer/LightingManager.d.ts +20 -0
- package/dist/types/core/renderer/MainRenderPhase.d.ts +62 -0
- package/dist/types/core/renderer/Program.d.ts +25 -0
- package/dist/types/core/renderer/RenderPhase.d.ts +10 -0
- package/dist/types/core/renderer/Renderer.d.ts +61 -0
- package/dist/types/core/renderer/ShadowRenderPhase.d.ts +32 -0
- package/dist/types/core/renderer/SkyboxRenderPhase.d.ts +26 -0
- package/dist/types/core/scene/Scene.d.ts +16 -0
- package/dist/types/index.d.ts +28 -0
- package/dist/types/loaders/GLTFInterfaces.d.ts +144 -0
- package/dist/types/loaders/GLTFLoader.d.ts +30 -0
- package/dist/types/math/Box3.d.ts +21 -0
- package/dist/types/math/Euler.d.ts +12 -0
- package/dist/types/math/Matrix3.d.ts +20 -0
- package/dist/types/math/Matrix4.d.ts +31 -0
- package/dist/types/math/Quaternion.d.ts +22 -0
- package/dist/types/math/Utils.d.ts +3 -0
- package/dist/types/math/Vector2.d.ts +16 -0
- package/dist/types/math/Vector3.d.ts +32 -0
- package/dist/types/math/index.d.ts +10 -0
- package/package.json +53 -0
|
@@ -0,0 +1,1455 @@
|
|
|
1
|
+
(function(M,U){typeof exports=="object"&&typeof module<"u"?U(exports):typeof define=="function"&&define.amd?define(["exports"],U):(M=typeof globalThis<"u"?globalThis:M||self,U(M.GFXLite={}))})(this,function(M){"use strict";var tt=Object.defineProperty;var it=(M,U,b)=>U in M?tt(M,U,{enumerable:!0,configurable:!0,writable:!0,value:b}):M[U]=b;var l=(M,U,b)=>it(M,typeof U!="symbol"?U+"":U,b);class U{constructor(t=0,e=0){l(this,"x");l(this,"y");this.x=t,this.y=e}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.x/=t,this.y/=t,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}clone(){return new U(this.x,this.y)}}class b{constructor(t=0,e=0,i=0){l(this,"x");l(this,"y");l(this,"z");this.x=t,this.y=e,this.z=i}set(t,e,i){return this.x=t,this.y=e,this.z=i,this}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.x/=t,this.y/=t,this.z/=t,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}cross(t){const e=this.x,i=this.y,a=this.z,r=t.x,s=t.y,n=t.z;return this.x=i*n-a*s,this.y=a*r-e*n,this.z=e*s-i*r,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}normalize(){return this.divideScalar(this.length()||1)}toArray(){const t=[];return t[0]=this.x,t[1]=this.y,t[2]=this.z,t}clone(){return new b(this.x,this.y,this.z)}lerp(t,e){return e=Math.max(0,Math.min(1,e)),new b(this.x*(1-e)+t.x*e,this.y*(1-e)+t.y*e,this.z*(1-e)+t.z*e)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y,a=this.z-t.z;return Math.sqrt(e*e+i*i+a*a)}applyQuaternion(t){const e=this.x,i=this.y,a=this.z,r=t.x,s=t.y,n=t.z,o=t.w,c=o*e+s*a-n*i,u=o*i+n*e-r*a,h=o*a+r*i-s*e,p=-r*e-s*i-n*a;return this.x=c*o+p*-r+u*-n-h*-s,this.y=u*o+p*-s+h*-r-c*-n,this.z=h*o+p*-n+c*-s-u*-r,this}applyMatrix4(t){const e=this.x,i=this.y,a=this.z,r=t.elements,s=1/(r[3]*e+r[7]*i+r[11]*a+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*a+r[12])*s,this.y=(r[1]*e+r[5]*i+r[9]*a+r[13])*s,this.z=(r[2]*e+r[6]*i+r[10]*a+r[14])*s,this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}}class k{constructor(t,e){l(this,"min");l(this,"max");this.min=t?t.clone():new b(1/0,1/0,1/0),this.max=e?e.clone():new b(-1/0,-1/0,-1/0)}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromPoints(t){this.makeEmpty();for(const e of t)this.expandByPoint(e);return this}setFromBufferAttribute(t){if(this.makeEmpty(),t.length===0)return this;for(let e=0;e<t.length;e+=3){const i=t[e],a=t[e+1],r=t[e+2];i<this.min.x&&(this.min.x=i),a<this.min.y&&(this.min.y=a),r<this.min.z&&(this.min.z=r),i>this.max.x&&(this.max.x=i),a>this.max.y&&(this.max.y=a),r>this.max.z&&(this.max.z=r)}return this}clone(){return new k().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t){return this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){if(this.isEmpty())return this;const e=[new b(this.min.x,this.min.y,this.min.z).applyMatrix4(t),new b(this.min.x,this.min.y,this.max.z).applyMatrix4(t),new b(this.min.x,this.max.y,this.min.z).applyMatrix4(t),new b(this.min.x,this.max.y,this.max.z).applyMatrix4(t),new b(this.max.x,this.min.y,this.min.z).applyMatrix4(t),new b(this.max.x,this.min.y,this.max.z).applyMatrix4(t),new b(this.max.x,this.max.y,this.min.z).applyMatrix4(t),new b(this.max.x,this.max.y,this.max.z).applyMatrix4(t)];return this.setFromPoints(e),this}getCenter(t){return t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return t.subVectors(this.max,this.min)}}function F(w,t,e){return Math.max(t,Math.min(e,w))}function Se(w){return w*.01745329252}function Ce(w){return w*57.2957795131}class X{constructor(){l(this,"elements");this.elements=[1,0,0,0,1,0,0,0,1]}set(t,e,i,a,r,s,n,o,c){const u=this.elements;return u[0]=t,u[1]=a,u[2]=n,u[3]=e,u[4]=r,u[5]=o,u[6]=i,u[7]=s,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,a=e.elements,r=this.elements,s=i[0],n=i[3],o=i[6],c=i[1],u=i[4],h=i[7],p=i[2],d=i[5],f=i[8],m=a[0],x=a[3],g=a[6],y=a[1],v=a[4],S=a[7],P=a[2],T=a[5],B=a[8];return r[0]=s*m+n*y+o*P,r[3]=s*x+n*v+o*T,r[6]=s*g+n*S+o*B,r[1]=c*m+u*y+h*P,r[4]=c*x+u*v+h*T,r[7]=c*g+u*S+h*B,r[2]=p*m+d*y+f*P,r[5]=p*x+d*v+f*T,r[8]=p*g+d*S+f*B,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],a=t[2],r=t[3],s=t[4],n=t[5],o=t[6],c=t[7],u=t[8];return e*s*u-e*n*c-i*r*u+i*n*o+a*r*c-a*s*o}invert(){const t=this.elements,e=t[0],i=t[1],a=t[2],r=t[3],s=t[4],n=t[5],o=t[6],c=t[7],u=t[8],h=u*s-n*c,p=n*o-u*r,d=c*r-s*o,f=e*h+i*p+a*d;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=h*m,t[1]=(a*c-u*i)*m,t[2]=(n*i-a*s)*m,t[3]=p*m,t[4]=(u*e-a*o)*m,t[5]=(a*r-n*e)*m,t[6]=d*m,t[7]=(i*o-c*e)*m,t[8]=(s*e-i*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,a=t.y,r=t.z,s=Math.cos(i),n=Math.sin(i),o=Math.cos(a),c=Math.sin(a),u=Math.cos(r),h=Math.sin(r);switch(t.order){case"XYZ":{const p=s*u,d=s*h,f=n*u,m=n*h;e[0]=o*u,e[3]=-o*h,e[6]=c,e[1]=d+f*c,e[4]=p-m*c,e[7]=-n*o,e[2]=m-p*c,e[5]=f+d*c,e[8]=s*o;break}case"YXZ":{const p=o*u,d=o*h,f=c*u,m=c*h;e[0]=p+m*n,e[3]=f*n-d,e[6]=s*c,e[1]=s*h,e[4]=s*u,e[7]=-n,e[2]=d*n-f,e[5]=m+p*n,e[8]=s*o;break}case"ZXY":{const p=o*u,d=o*h,f=c*u,m=c*h;e[0]=p-m*n,e[3]=-s*h,e[6]=f+d*n,e[1]=d+f*n,e[4]=s*u,e[7]=m-p*n,e[2]=-s*c,e[5]=n,e[8]=s*o;break}case"ZYX":{const p=s*u,d=s*h,f=n*u,m=n*h;e[0]=o*u,e[3]=f*c-d,e[6]=p*c+m,e[1]=o*h,e[4]=m*c+p,e[7]=d*c-f,e[2]=-c,e[5]=n*o,e[8]=s*o;break}case"YZX":{const p=s*o,d=s*c,f=n*o,m=n*c;e[0]=o*u,e[3]=m-p*h,e[6]=f*h+d,e[1]=h,e[4]=s*u,e[7]=-n*u,e[2]=-c*u,e[5]=d*h+f,e[8]=p-m*h;break}case"XZY":{const p=s*o,d=s*c,f=n*o,m=n*c;e[0]=o*u,e[3]=-h,e[6]=c*u,e[1]=p*h+m,e[4]=s*u,e[7]=d*h-f,e[2]=f*h-d,e[5]=n*u,e[8]=m*h+p;break}}return this}makeRotationFromQuaternion(t){const e=this.elements,i=t.x,a=t.y,r=t.z,s=t.w,n=i+i,o=a+a,c=r+r,u=i*n,h=i*o,p=i*c,d=a*o,f=a*c,m=r*c,x=s*n,g=s*o,y=s*c;return e[0]=1-(d+m),e[1]=h+y,e[2]=p-g,e[3]=h-y,e[4]=1-(u+m),e[5]=f+x,e[6]=p+g,e[7]=f-x,e[8]=1-(u+d),this}fromArray(t){for(let e=0;e<9;e++)this.elements[e]=t[e];return this}toArray(){const t=[],e=this.elements;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}clone(){return new X().fromArray(this.elements)}}class pe{constructor(t=0,e=0,i=0,a="XYZ"){l(this,"x");l(this,"y");l(this,"z");l(this,"order");this.x=t,this.y=e,this.z=i,this.order=a}setFromQuaternion(t,e){const i=new X().makeRotationFromQuaternion(t);return this.setFromRotationMatrix(i,e)}setFromRotationMatrix(t,e){const i=t.elements,a=i[0],r=i[3],s=i[6],n=i[1],o=i[4],c=i[7],u=i[2],h=i[5],p=i[8];switch(e=e||this.order,e){case"XYZ":this.y=Math.asin(F(s,-1,1)),Math.abs(s)<.9999999?(this.x=Math.atan2(-c,p),this.z=Math.atan2(-r,a)):(this.x=Math.atan2(h,o),this.z=0);break;case"YXZ":this.x=Math.asin(-F(c,-1,1)),Math.abs(c)<.9999999?(this.y=Math.atan2(s,p),this.z=Math.atan2(n,o)):(this.y=Math.atan2(-u,a),this.z=0);break;case"ZXY":this.x=Math.asin(F(h,-1,1)),Math.abs(h)<.9999999?(this.y=Math.atan2(-u,p),this.z=Math.atan2(-r,o)):(this.y=0,this.z=Math.atan2(n,a));break;case"ZYX":this.y=Math.asin(-F(u,-1,1)),Math.abs(u)<.9999999?(this.x=Math.atan2(h,p),this.z=Math.atan2(n,a)):(this.x=0,this.z=Math.atan2(-r,o));break;case"YZX":this.z=Math.asin(F(n,-1,1)),Math.abs(n)<.9999999?(this.x=Math.atan2(-c,o),this.y=Math.atan2(-u,a)):(this.x=0,this.y=Math.atan2(s,p));break;case"XZY":this.z=Math.asin(-F(r,-1,1)),Math.abs(r)<.9999999?(this.x=Math.atan2(h,o),this.y=Math.atan2(s,a)):(this.x=Math.atan2(-c,p),this.y=0);break}return this.order=e,this}clone(){return new pe(this.x,this.y,this.z,this.order)}}class L{constructor(t=0,e=0,i=0,a=1){l(this,"x");l(this,"y");l(this,"z");l(this,"w");this.x=t,this.y=e,this.z=i,this.w=a}set(t,e,i,a){return this.x=t,this.y=e,this.z=i,this.w=a,this}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}setFromEuler(t){const e=t.x,i=t.y,a=t.z,r=t.order,s=Math.cos,n=Math.sin,o=s(e/2),c=s(i/2),u=s(a/2),h=n(e/2),p=n(i/2),d=n(a/2);switch(r){case"XYZ":this.x=h*c*u+o*p*d,this.y=o*p*u-h*c*d,this.z=o*c*d+h*p*u,this.w=o*c*u-h*p*d;break;case"YXZ":this.x=h*c*u+o*p*d,this.y=o*p*u-h*c*d,this.z=o*c*d-h*p*u,this.w=o*c*u+h*p*d;break;case"ZXY":this.x=h*c*u-o*p*d,this.y=o*p*u+h*c*d,this.z=o*c*d+h*p*u,this.w=o*c*u-h*p*d;break;case"ZYX":this.x=h*c*u-o*p*d,this.y=o*p*u+h*c*d,this.z=o*c*d-h*p*u,this.w=o*c*u+h*p*d;break;case"YZX":this.x=h*c*u+o*p*d,this.y=o*p*u+h*c*d,this.z=o*c*d-h*p*u,this.w=o*c*u-h*p*d;break;case"XZY":this.x=h*c*u-o*p*d,this.y=o*p*u-h*c*d,this.z=o*c*d+h*p*u,this.w=o*c*u+h*p*d;break}return this}setFromAxisAngle(t,e){const i=e/2,a=Math.sin(i);return this.x=t.x*a,this.y=t.y*a,this.z=t.z*a,this.w=Math.cos(i),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],a=e[3],r=e[6],s=e[1],n=e[4],o=e[7],c=e[2],u=e[5],h=e[8],p=i+n+h;if(p>0){const d=.5/Math.sqrt(p+1);this.w=.25/d,this.x=(u-o)*d,this.y=(r-c)*d,this.z=(s-a)*d}else if(i>n&&i>h){const d=2*Math.sqrt(1+i-n-h);this.w=(u-o)/d,this.x=.25*d,this.y=(a+s)/d,this.z=(r+c)/d}else if(n>h){const d=2*Math.sqrt(1+n-i-h);this.w=(r-c)/d,this.x=(a+s)/d,this.y=.25*d,this.z=(o+u)/d}else{const d=2*Math.sqrt(1+h-i-n);this.w=(s-a)/d,this.x=(r+c)/d,this.y=(o+u)/d,this.z=.25*d}return this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t.x,a=t.y,r=t.z,s=t.w,n=e.x,o=e.y,c=e.z,u=e.w;return this.x=i*u+s*n+a*c-r*o,this.y=a*u+s*o+r*n-i*c,this.z=r*u+s*c+i*o-a*n,this.w=s*u-i*n-a*o-r*c,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}clone(){return new L(this.x,this.y,this.z,this.w)}slerp(t,e){e=Math.max(0,Math.min(1,e));let i=this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w;if(i<0&&(t=new L(-t.x,-t.y,-t.z,-t.w),i=-i),i>.9995)return new L(this.x+e*(t.x-this.x),this.y+e*(t.y-this.y),this.z+e*(t.z-this.z),this.w+e*(t.w-this.w)).normalize();const r=Math.acos(i),s=r*e,n=Math.sin(s),o=Math.sin(r),c=Math.cos(s)-i*n/o,u=n/o;return new L(c*this.x+u*t.x,c*this.y+u*t.y,c*this.z+u*t.z,c*this.w+u*t.w)}normalize(){const t=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);return t===0?new L(0,0,0,1):new L(this.x/t,this.y/t,this.z/t,this.w/t)}}class A{constructor(){l(this,"elements");this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set(t,e,i,a,r,s,n,o,c,u,h,p,d,f,m,x){const g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=a,g[1]=r,g[5]=s,g[9]=n,g[13]=o,g[2]=c,g[6]=u,g[10]=h,g[14]=p,g[3]=d,g[7]=f,g[11]=m,g[15]=x,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,a=e.elements,r=this.elements,s=i[0],n=i[4],o=i[8],c=i[12],u=i[1],h=i[5],p=i[9],d=i[13],f=i[2],m=i[6],x=i[10],g=i[14],y=i[3],v=i[7],S=i[11],P=i[15],T=a[0],B=a[4],G=a[8],I=a[12],O=a[1],D=a[5],H=a[9],re=a[13],se=a[2],ne=a[6],oe=a[10],le=a[14],ue=a[3],ce=a[7],he=a[11],de=a[15];return r[0]=s*T+n*O+o*se+c*ue,r[4]=s*B+n*D+o*ne+c*ce,r[8]=s*G+n*H+o*oe+c*he,r[12]=s*I+n*re+o*le+c*de,r[1]=u*T+h*O+p*se+d*ue,r[5]=u*B+h*D+p*ne+d*ce,r[9]=u*G+h*H+p*oe+d*he,r[13]=u*I+h*re+p*le+d*de,r[2]=f*T+m*O+x*se+g*ue,r[6]=f*B+m*D+x*ne+g*ce,r[10]=f*G+m*H+x*oe+g*he,r[14]=f*I+m*re+x*le+g*de,r[3]=y*T+v*O+S*se+P*ue,r[7]=y*B+v*D+S*ne+P*ce,r[11]=y*G+v*H+S*oe+P*he,r[15]=y*I+v*re+S*le+P*de,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],a=t[8],r=t[12],s=t[1],n=t[5],o=t[9],c=t[13],u=t[2],h=t[6],p=t[10],d=t[14],f=t[3],m=t[7],x=t[11],g=t[15];return f*(+r*o*h-a*c*h-r*n*p+i*c*p+a*n*d-i*o*d)+m*(+e*o*d-e*c*p+r*s*p-a*s*d+a*c*u-r*o*u)+x*(+e*c*h-e*n*d-r*s*h+i*s*d+r*n*u-i*c*u)+g*(-a*n*u-e*o*h+e*n*p+a*s*h-i*s*p+i*o*u)}invert(){const t=this.elements,e=t[0],i=t[1],a=t[2],r=t[3],s=t[4],n=t[5],o=t[6],c=t[7],u=t[8],h=t[9],p=t[10],d=t[11],f=t[12],m=t[13],x=t[14],g=t[15],y=h*x*c-m*p*c+m*o*d-n*x*d-h*o*g+n*p*g,v=f*p*c-u*x*c-f*o*d+s*x*d+u*o*g-s*p*g,S=u*m*c-f*h*c+f*n*d-s*m*d-u*n*g+s*h*g,P=f*h*o-u*m*o-f*n*p+s*m*p+u*n*x-s*h*x,T=e*y+i*v+a*S+r*P;if(T===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const B=1/T;return t[0]=y*B,t[1]=(m*p*r-h*x*r-m*a*d+i*x*d+h*a*g-i*p*g)*B,t[2]=(n*x*r-m*o*r+m*a*c-i*x*c-n*a*g+i*o*g)*B,t[3]=(h*o*r-n*p*r-h*a*c+i*p*c+n*a*d-i*o*d)*B,t[4]=v*B,t[5]=(u*x*r-f*p*r+f*a*d-e*x*d-u*a*g+e*p*g)*B,t[6]=(f*o*r-s*x*r-f*a*c+e*x*c+s*a*g-e*o*g)*B,t[7]=(s*p*r-u*o*r+u*a*c-e*p*c-s*a*d+e*o*d)*B,t[8]=S*B,t[9]=(f*h*r-u*m*r-f*i*d+e*m*d+u*i*g-e*h*g)*B,t[10]=(s*m*r-f*n*r+f*i*c-e*m*c-s*i*g+e*n*g)*B,t[11]=(u*n*r-s*h*r-u*i*c+e*h*c+s*i*d-e*n*d)*B,t[12]=P*B,t[13]=(u*m*a-f*h*a+f*i*p-e*m*p-u*i*x+e*h*x)*B,t[14]=(f*n*a-s*m*a-f*i*o+e*m*o+s*i*x-e*n*x)*B,t[15]=(s*h*a-u*n*a+u*i*o-e*h*o-s*i*p+e*n*p)*B,this}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t){const e=this.elements;return e[12]=t.x,e[13]=t.y,e[14]=t.z,this}scalePosition(t){const e=this.elements;return e[12]*=t.x,e[13]*=t.y,e[14]*=t.z,this}setRotation(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[4]=i[3],e[5]=i[4],e[6]=i[5],e[8]=i[6],e[9]=i[7],e[10]=i[8],this}extractPosition(){const t=this.elements;return new b(t[12],t[13],t[14])}extractRotation(){const t=this.elements;return new X().set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10])}lookAt(t,e,i){const a=this.elements,r=t.clone().sub(e);r.length()===0&&(r.z=1),r.normalize();let s=i.clone().cross(r);s.length()===0&&(Math.abs(i.z)===1?r.x+=1e-4:r.z+=1e-4,r.normalize(),s=i.clone().cross(r)),s.normalize();const n=r.clone().cross(s);return a[0]=s.x,a[4]=n.x,a[8]=r.x,a[1]=s.y,a[5]=n.y,a[9]=r.y,a[2]=s.z,a[6]=n.z,a[10]=r.z,this}fromArray(t){for(let e=0;e<16;e++)this.elements[e]=t[e];return this}toArray(){const t=[],e=this.elements;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}clone(){return new A().fromArray(this.elements)}lerp(t,e){e=Math.max(0,Math.min(1,e));const i=new L().setFromRotationMatrix(this.extractRotation()),a=new L().setFromRotationMatrix(this.extractRotation()),r=this.extractPosition(),s=t.extractPosition(),n=i.slerp(a,e),o=r.lerp(s,e),c=new X().makeRotationFromQuaternion(n),u=this.clone();return u.setRotation(c),u.setPosition(o),u}compose(t,e,i){const a=this.elements,r=e.x,s=e.y,n=e.z,o=e.w,c=r+r,u=s+s,h=n+n,p=r*c,d=r*u,f=r*h,m=s*u,x=s*h,g=n*h,y=o*c,v=o*u,S=o*h,P=i.x,T=i.y,B=i.z;return a[0]=(1-(m+g))*P,a[1]=(d+S)*P,a[2]=(f-v)*P,a[3]=0,a[4]=(d-S)*T,a[5]=(1-(p+g))*T,a[6]=(x+y)*T,a[7]=0,a[8]=(f+v)*B,a[9]=(x-y)*B,a[10]=(1-(p+m))*B,a[11]=0,a[12]=t.x,a[13]=t.y,a[14]=t.z,a[15]=1,this}decompose(t,e,i){const a=this.elements;let r=new b(a[0],a[1],a[2]).length();const s=new b(a[4],a[5],a[6]).length(),n=new b(a[8],a[9],a[10]).length();this.determinant()<0&&(r=-r),t.x=a[12],t.y=a[13],t.z=a[14],i.x=r,i.y=s,i.z=n;const c=1/r,u=1/s,h=1/n,p=new A;p.copy(this);const d=p.elements;return d[0]*=c,d[1]*=c,d[2]*=c,d[4]*=u,d[5]*=u,d[6]*=u,d[8]*=h,d[9]*=h,d[10]*=h,e.setFromRotationMatrix(p.extractRotation()),this}perspective(t,e,i,a){const r=1/Math.tan(t/2),s=1/(i-a);return this.elements[0]=r/e,this.elements[1]=0,this.elements[2]=0,this.elements[3]=0,this.elements[4]=0,this.elements[5]=r,this.elements[6]=0,this.elements[7]=0,this.elements[8]=0,this.elements[9]=0,this.elements[10]=a*s,this.elements[11]=-1,this.elements[12]=0,this.elements[13]=0,this.elements[14]=a*i*s,this.elements[15]=0,this}orthographic(t,e,i,a,r,s){const n=1/(e-t),o=1/(a-i),c=1/(s-r),u=(e+t)*n,h=(a+i)*o,p=r*c;return this.elements[0]=2*n,this.elements[1]=0,this.elements[2]=0,this.elements[3]=0,this.elements[4]=0,this.elements[5]=2*o,this.elements[6]=0,this.elements[7]=0,this.elements[8]=0,this.elements[9]=0,this.elements[10]=-1*c,this.elements[11]=0,this.elements[12]=-u,this.elements[13]=-h,this.elements[14]=-p,this.elements[15]=1,this}}let Te=0;class N{constructor(){l(this,"id",Te++);l(this,"name","");l(this,"parent",null);l(this,"children",[]);l(this,"position",new b);l(this,"rotation",new L);l(this,"scale",new b(1,1,1));l(this,"castShadow",!1);l(this,"receiveShadow",!1);l(this,"localMatrix",new A);l(this,"worldMatrix",new A)}lookAt(t){const e=new A;e.lookAt(this.position,t,new b(0,1,0)),this.rotation.setFromRotationMatrix(e.extractRotation())}add(t){t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t)}remove(t){const e=this.children.indexOf(t);e!==-1&&(t.parent=null,this.children.splice(e,1))}rotateOnAxis(t,e){const i=new L;return i.setFromAxisAngle(t,e),this.rotation.multiply(i),this}rotateX(t){return this.rotateOnAxis(new b(1,0,0),t)}rotateY(t){return this.rotateOnAxis(new b(0,1,0),t)}rotateZ(t){return this.rotateOnAxis(new b(0,0,1),t)}updateLocalMatrix(){this.localMatrix.compose(this.position,this.rotation,this.scale)}updateWorldMatrix(t){this.updateLocalMatrix(),t?this.worldMatrix.multiplyMatrices(t,this.localMatrix):this.worldMatrix.copy(this.localMatrix);for(const e of this.children)e.updateWorldMatrix(this.worldMatrix)}traverse(t){t(this);for(const e of this.children)e.traverse(t)}}class fe extends N{constructor(e=new b(1,1,1),i=1){super();l(this,"color");l(this,"intensity");this.color=e,this.intensity=i}}class me extends N{constructor(){super(...arguments);l(this,"projectionMatrix",new A);l(this,"viewMatrix",new A);l(this,"viewProjectionMatrix",new A);l(this,"frustumPlanes",new Float32Array(24))}updateWorldMatrix(e){super.updateWorldMatrix(e),this.viewMatrix.copy(this.worldMatrix).invert(),this.updateViewProjectionMatrix()}updateProjectionMatrix(){this.updateViewProjectionMatrix()}updateViewProjectionMatrix(){this.viewProjectionMatrix.multiplyMatrices(this.projectionMatrix,this.viewMatrix),this.extractFrustumPlanes()}extractFrustumPlanes(){const e=this.viewProjectionMatrix.elements,i=this.frustumPlanes;i[0]=e[3]+e[0],i[1]=e[7]+e[4],i[2]=e[11]+e[8],i[3]=e[15]+e[12],this.normalizePlane(i,0),i[4]=e[3]-e[0],i[5]=e[7]-e[4],i[6]=e[11]-e[8],i[7]=e[15]-e[12],this.normalizePlane(i,4),i[8]=e[3]+e[1],i[9]=e[7]+e[5],i[10]=e[11]+e[9],i[11]=e[15]+e[13],this.normalizePlane(i,8),i[12]=e[3]-e[1],i[13]=e[7]-e[5],i[14]=e[11]-e[9],i[15]=e[15]-e[13],this.normalizePlane(i,12),i[16]=e[2],i[17]=e[6],i[18]=e[10],i[19]=e[14],this.normalizePlane(i,16),i[20]=e[3]-e[2],i[21]=e[7]-e[6],i[22]=e[11]-e[10],i[23]=e[15]-e[14],this.normalizePlane(i,20)}normalizePlane(e,i){const a=Math.sqrt(e[i]**2+e[i+1]**2+e[i+2]**2);a>0&&(e[i]/=a,e[i+1]/=a,e[i+2]/=a,e[i+3]/=a)}}class ve extends me{constructor(e=-1,i=1,a=1,r=-1,s=.1,n=2e3){super();l(this,"left");l(this,"right");l(this,"top");l(this,"bottom");l(this,"near");l(this,"far");this.left=e,this.right=i,this.top=a,this.bottom=r,this.near=s,this.far=n,this.updateProjectionMatrix()}updateProjectionMatrix(){this.projectionMatrix.orthographic(this.left,this.right,this.bottom,this.top,this.near,this.far),super.updateProjectionMatrix()}}class j extends fe{constructor(e=new b(1,1,1),i=1){super(e,i);l(this,"shadow",{camera:new ve(-5,5,5,-5,.5,50),mapSize:{width:2048,height:2048},bias:.005,map:void 0,view:void 0,sampler:void 0,autoUpdate:!0})}get direction(){const e=new b(0,0,-1);return e.applyQuaternion(this.rotation),e.normalize()}}const be=16,we=4,ge=16+112*be;class Ge{constructor(t,e,i){l(this,"device");l(this,"lightingBuffer",null);l(this,"shadowMapArray",null);l(this,"shadowMapArrayView",null);l(this,"dummyShadowMap");l(this,"dummyShadowSampler");l(this,"_lightingData",new Float32Array(ge/4));l(this,"_tempMatrix",new A);this.device=t,this.dummyShadowMap=e,this.dummyShadowSampler=i}collectLights(t){const e=[];return t.traverse(i=>{i instanceof fe&&e.push(i)}),e}updateLightingBuffer(t,e,i,a=!0){(!this.lightingBuffer||this.lightingBuffer.size<ge)&&(this.lightingBuffer&&this.lightingBuffer.destroy(),this.lightingBuffer=this.device.createBuffer({label:"Lighting Uniform Buffer",size:ge,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));let s=512;for(const c of e)c instanceof j&&c.castShadow&&(s=Math.max(s,c.shadow.mapSize.width,c.shadow.mapSize.height));(!this.shadowMapArray||this.shadowMapArray.width!==s)&&this.createShadowMapArray(s);const n=this._lightingData;n.fill(0),n.set(t.ambientLight.toArray(),0),new Uint32Array(n.buffer,12,1)[0]=e.length;let o=0;for(let c=0;c<Math.min(e.length,be);c++){const u=e[c],h=4+c*(112/4);let p=new b(0,0,-1),d=-1,f=null;u instanceof j&&(p=u.direction,a&&u.castShadow&&o<we&&(f=u,d=o,o++,u._shadowLayerIndex=d)),n.set(p.toArray(),h),n[h+3]=u.intensity,n.set(u.color.toArray(),h+4),new Int32Array(n.buffer,(h+7)*4,1)[0]=d,f&&f.shadow.camera&&(this._tempMatrix.multiplyMatrices(f.shadow.camera.projectionMatrix,f.shadow.camera.viewMatrix),n.set(this._tempMatrix.toArray(),h+8)),f&&(n[h+24]=f.shadow.mapSize.width,n[h+25]=f.shadow.mapSize.height,n[h+26]=i)}return this.device.queue.writeBuffer(this.lightingBuffer,0,n),this.lightingBuffer}createShadowMapArray(t){this.shadowMapArray&&this.shadowMapArray.destroy(),this.shadowMapArray=this.device.createTexture({label:"Shadow Map Array",size:[t,t,we],format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.shadowMapArrayView=this.shadowMapArray.createView({dimension:"2d-array"})}getLightingBuffer(){return this.lightingBuffer}getDummyShadowMap(){return this.dummyShadowMap}getShadowSampler(){return this.dummyShadowSampler}dispose(){this.lightingBuffer&&(this.lightingBuffer.destroy(),this.lightingBuffer=null),this.shadowMapArray&&(this.shadowMapArray.destroy(),this.shadowMapArray=null)}}class Y{constructor(t,e){l(this,"device");l(this,"label");this.device=t,this.label=e}}class q extends N{constructor(e,i){super();l(this,"geometry");l(this,"material");this.geometry=e,this.material=i}}let Ie=0;const z={Opaque:0,AlphaBlend:1,AlphaCutoff:2},E={Basic:0,Lambert:1,Phong:2,Standard:3};class W{constructor(){l(this,"id",Ie++);l(this,"needsUpdate",!0);l(this,"uniforms",{});l(this,"transparent",!1);l(this,"opacity",1);l(this,"blendMode",z.Opaque);l(this,"alphaCutoff",.5);l(this,"depthWrite",!0);l(this,"doubleSided",!1)}hasTextures(){return!1}getPipelineKey(){return`${this.materialType}_${this.transparent?1:0}_${this.hasTextures()?1:0}_${this.doubleSided?1:0}`}}class Ue{constructor(t,e){l(this,"pipeline");l(this,"bindGroupLayouts",null);const i=t.createShaderModule({label:"Vertex Shader",code:e.vertex.code}),a=t.createShaderModule({label:"Fragment Shader",code:e.fragment.code}),r=[];r.push({arrayStride:3*4,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]});const s=e.hasNormals??!e.positionOnly;let n=1;s&&r.push({arrayStride:3*4,attributes:[{shaderLocation:n++,offset:0,format:"float32x3"}]}),e.hasUVs&&r.push({arrayStride:2*4,attributes:[{shaderLocation:n++,offset:0,format:"float32x2"}]}),e.hasTangents&&r.push({arrayStride:4*4,attributes:[{shaderLocation:n++,offset:0,format:"float32x4"}]});let o="auto";e.bindGroupLayouts&&(this.bindGroupLayouts=e.bindGroupLayouts,o=t.createPipelineLayout({label:"Explicit Pipeline Layout",bindGroupLayouts:e.bindGroupLayouts}));const c={format:navigator.gpu.getPreferredCanvasFormat()};e.blend&&(c.blend=e.blend),this.pipeline=t.createRenderPipeline({label:"Render Pipeline",layout:o,vertex:{module:i,entryPoint:e.vertex.entryPoint||"main",buffers:r},fragment:{module:a,entryPoint:e.fragment.entryPoint||"main",targets:[c]},depthStencil:{depthWriteEnabled:e.depthWrite!==!1,depthCompare:e.depthCompare??"less",format:"depth24plus"},primitive:{topology:"triangle-list",cullMode:e.cullMode??"back"},multisample:e.multisample})}}const Le={color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};class Me extends Y{constructor(e,i,a,r,s,n,o,c){super(e,"Main Render Phase");l(this,"lightingManager");l(this,"batchManager");l(this,"textureManager");l(this,"environmentManager",null);l(this,"context");l(this,"depthTextureView");l(this,"msaaTextureView");l(this,"sampleCount");l(this,"renderList",[]);l(this,"batches",[]);l(this,"currentEnvironment",null);l(this,"skyboxRendered",!1);l(this,"clearColor",{r:.1,g:.1,b:.1,a:1});l(this,"cameraPosition",new b);l(this,"indirectPipelineCache",new Map);l(this,"materialBindGroupLayout",null);l(this,"lightingBindGroupLayout",null);l(this,"textureBindGroupLayout",null);l(this,"simpleTextureBindGroupLayout",null);l(this,"textureBindGroupCache",new Map);l(this,"simpleTextureBindGroupCache",new Map);l(this,"envParamsBufferCache",new Map);l(this,"sceneEnvironmentId",-1);l(this,"materialEnvKeyCache",new Map);l(this,"debugInfo",{calls:0,triangles:0,batches:0});l(this,"materialBindGroupCache",new Map);l(this,"materialBufferCache",new Map);this.lightingManager=i,this.batchManager=a,this.textureManager=r,this.context=s,this.depthTextureView=n,this.msaaTextureView=o,this.sampleCount=c,this.initBindGroupLayouts()}setEnvironmentManager(e){this.environmentManager=e,this.indirectPipelineCache.clear()}setEnvironment(e){this.currentEnvironment=e}setSkyboxRendered(e){this.skyboxRendered=e}setClearColor(e,i,a,r=1){this.clearColor={r:e,g:i,b:a,a:r}}initBindGroupLayouts(){this.materialBindGroupLayout=this.device.createBindGroupLayout({label:"Material Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.lightingBindGroupLayout=this.device.createBindGroupLayout({label:"Lighting Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}}]}),this.textureBindGroupLayout=this.device.createBindGroupLayout({label:"PBR Texture Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube"}},{binding:8,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:9,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:10,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.simpleTextureBindGroupLayout=this.device.createBindGroupLayout({label:"Simple Texture Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]})}getIndirectPipeline(e){const i=e.getPipelineKey();let a=this.indirectPipelineCache.get(i);if(a)return a;const r=e.materialType,s=r===E.Standard,n=r===E.Basic,o=e.hasTextures(),c=e.needsLighting,u=e.needsNormals,h=[this.batchManager.getRenderBindGroupLayout(),this.materialBindGroupLayout];c&&h.push(this.lightingBindGroupLayout),s?h.push(this.textureBindGroupLayout):o&&(n?h.push(this.simpleTextureBindGroupLayout):h.push(this.simpleTextureBindGroupLayout));const p=s||o,d=new Ue(this.device,{vertex:{code:e.getVertexShader()},fragment:{code:e.getFragmentShader()},multisample:{count:this.sampleCount},bindGroupLayouts:h,positionOnly:n&&!o,hasNormals:u,hasUVs:p,hasTangents:s,blend:e.transparent?Le:void 0,depthWrite:!e.transparent,depthCompare:"less-equal",cullMode:e.doubleSided?"none":"back"});let f=null;return c&&(f=this.createLightingBindGroup()),a={program:d,lightingBindGroup:f},this.indirectPipelineCache.set(i,a),a}createLightingBindGroup(){const e=this.lightingManager.getLightingBuffer(),i=this.lightingManager.shadowMapArrayView||this.lightingManager.getDummyShadowMap(),a=this.lightingManager.getShadowSampler();return this.device.createBindGroup({label:"Indirect Lighting Bind Group",layout:this.lightingBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:i},{binding:2,resource:a}]})}invalidateLightingBindGroups(){for(const[,e]of this.indirectPipelineCache)e.lightingBindGroup&&(e.lightingBindGroup=this.createLightingBindGroup())}prepare(e,i){this.renderList=[],this.debugInfo.calls=0,this.debugInfo.triangles=0,this.debugInfo.batches=0,this.cameraPosition.copy(i.position),e.traverse(a=>{a instanceof q&&this.renderList.push(a)}),this.batches=this.batchManager.prepareBatches(this.renderList),this.debugInfo.batches=this.batches.length}execute(e){if(this.batches.length===0)return;const i=[],a=[];for(const o of this.batches)o.material.transparent?a.push(o):i.push(o);a.length>0&&this.sortTransparentBatches(a);const r=this.context.getCurrentTexture().createView(),s=[...i,...a],n=this.skyboxRendered?"load":"clear";this.renderBatches(e,s,r,n,"load")}sortTransparentBatches(e){e.sort((i,a)=>{const r=this.getBatchCentroidDistance(i);return this.getBatchCentroidDistance(a)-r})}getBatchCentroidDistance(e){let i=0;for(const a of e.meshes){const r=a.worldMatrix.extractPosition(),s=r.x-this.cameraPosition.x,n=r.y-this.cameraPosition.y,o=r.z-this.cameraPosition.z;i+=Math.sqrt(s*s+n*n+o*o)}return i/e.meshes.length}renderBatches(e,i,a,r,s){if(i.length===0)return;const n={view:this.sampleCount>1?this.msaaTextureView:a,clearValue:this.clearColor,loadOp:r,storeOp:this.sampleCount>1?"discard":"store"};this.sampleCount>1&&(n.resolveTarget=a);const o=e.beginRenderPass({label:`Main Render Pass (color: ${r}, depth: ${s})`,colorAttachments:[n],depthStencilAttachment:{view:this.depthTextureView,depthClearValue:1,depthLoadOp:s,depthStoreOp:"store"}});let c=null,u=null;for(let h=0;h<i.length;h++){const p=i[h],d=p.material,f=d.materialType,m=f===E.Standard,x=f===E.Basic,g=d.hasTextures(),y=d.needsNormals,v=d.getPipelineKey(),S=this.getIndirectPipeline(d),P=this.batchManager.getGeometryData(p.geometry);v!==u&&(u=v,c=S.program.pipeline,o.setPipeline(c),S.lightingBindGroup&&o.setBindGroup(2,S.lightingBindGroup));const T=this.batchManager.getRenderBindGroup(p,0);o.setBindGroup(0,T),d.needsUpdate&&this.updateMaterial(d);const B=this.getMaterialBindGroup(d);if(o.setBindGroup(1,B),m){const D=this.getTextureBindGroup(d);o.setBindGroup(3,D)}else if(g){const D=this.getSimpleTextureBindGroup(d),H=x?2:3;o.setBindGroup(H,D)}o.setVertexBuffer(0,P.vertexBuffer);const G=m||g;let I=1;y&&P.normalBuffer&&o.setVertexBuffer(I++,P.normalBuffer),G&&P.uvBuffer&&o.setVertexBuffer(I++,P.uvBuffer),m&&P.tangentBuffer&&o.setVertexBuffer(I++,P.tangentBuffer);const O=this.batchManager.getIndirectBufferOffset(0);P.indexBuffer?(o.setIndexBuffer(P.indexBuffer,"uint32"),o.drawIndexedIndirect(p.indirectBuffer,O)):o.drawIndirect(p.indirectBuffer,O),this.debugInfo.calls++,this.debugInfo.triangles+=p.geometry.indexCount/3*p.instanceCount}o.end()}updateMaterial(e){const i=this.materialBufferCache.get(e.id);i&&i.destroy();const a=e.getUniformBufferData(),r=Math.ceil(Math.max(a.byteLength,16)/16)*16,s=this.device.createBuffer({label:`Material Uniform Buffer ${e.id}`,size:r,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(s,0,a);const n=this.device.createBindGroup({label:`Material Bind Group ${e.id}`,layout:this.materialBindGroupLayout,entries:[{binding:0,resource:{buffer:s}}]});this.materialBufferCache.set(e.id,s),this.materialBindGroupCache.set(e.id,n),this.textureBindGroupCache.delete(e.id),this.simpleTextureBindGroupCache.delete(e.id),e.needsUpdate=!1}getTextureBindGroup(e){var c,u;const i=e.envMap??this.currentEnvironment,a=(i==null?void 0:i.id)??-1,r=e.id,s=`${e.id}_${a}_${e.envMapIntensity}`;if(((c=this.currentEnvironment)==null?void 0:c.id)!==this.sceneEnvironmentId){for(const[h,p]of this.materialEnvKeyCache){if(!this.textureBindGroupCache.has(h))continue;const d=p.split("_"),f=parseInt(d[1]),m=this.sceneEnvironmentId;f===m&&(this.textureBindGroupCache.delete(h),this.materialEnvKeyCache.delete(h))}this.sceneEnvironmentId=((u=this.currentEnvironment)==null?void 0:u.id)??-1}let n=this.textureBindGroupCache.get(r);const o=this.materialEnvKeyCache.get(r);if(!n||o!==s){const h=this.textureManager,p=this.environmentManager,d=p==null?void 0:p.dummyCubemapView,f=p==null?void 0:p.cubemapSampler,m=p==null?void 0:p.brdfSampler,x=p==null?void 0:p.brdfLUTView,y=((i==null?void 0:i.intensity)??1)*e.envMapIntensity,v=i!=null&&i.irradianceMapView?1:0,S=`${a}_${y}`;let P=this.envParamsBufferCache.get(S);P||(P=this.device.createBuffer({label:`Env Params Buffer (${S})`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(P,0,new Float32Array([y,v,0,0])),this.envParamsBufferCache.set(S,P)),n=this.device.createBindGroup({label:`PBR Texture Bind Group ${e.id}`,layout:this.textureBindGroupLayout,entries:[{binding:0,resource:e.baseColorMap?h.uploadTexture(e.baseColorMap):h.dummyWhiteTexture},{binding:1,resource:e.normalMap?h.uploadTexture(e.normalMap):h.dummyNormalTexture},{binding:2,resource:e.metallicRoughnessMap?h.uploadTexture(e.metallicRoughnessMap):h.dummyWhiteTexture},{binding:3,resource:e.emissiveMap?h.uploadTexture(e.emissiveMap):h.dummyBlackTexture},{binding:4,resource:e.aoMap?h.uploadTexture(e.aoMap):h.dummyWhiteTexture},{binding:5,resource:h.defaultSampler},{binding:6,resource:(i==null?void 0:i.irradianceMapView)??d},{binding:7,resource:(i==null?void 0:i.prefilteredMapView)??d},{binding:8,resource:x??h.dummyWhiteTexture},{binding:9,resource:f},{binding:10,resource:m},{binding:11,resource:{buffer:P}}]}),this.textureBindGroupCache.set(r,n),this.materialEnvKeyCache.set(r,s)}return n}getSimpleTextureBindGroup(e){let i=this.simpleTextureBindGroupCache.get(e.id);if(!i){const a=this.textureManager,r=e.map;i=this.device.createBindGroup({label:`Simple Texture Bind Group ${e.id}`,layout:this.simpleTextureBindGroupLayout,entries:[{binding:0,resource:r?a.uploadTexture(r):a.dummyWhiteTexture},{binding:1,resource:a.defaultSampler}]}),this.simpleTextureBindGroupCache.set(e.id,i)}return i}getMaterialBindGroup(e){let i=this.materialBindGroupCache.get(e.id);return i||(this.updateMaterial(e),i=this.materialBindGroupCache.get(e.id)),i}dispose(){for(const e of this.materialBufferCache.values())e.destroy();this.materialBufferCache.clear(),this.materialBindGroupCache.clear(),this.textureBindGroupCache.clear(),this.simpleTextureBindGroupCache.clear(),this.materialEnvKeyCache.clear();for(const e of this.envParamsBufferCache.values())e.destroy();this.envParamsBufferCache.clear()}}class Ae extends Y{constructor(e,i,a){super(e,"Shadow Render Phase");l(this,"lightingManager");l(this,"batchManager");l(this,"shadowPipeline",null);l(this,"shadowsEnabled",!0);l(this,"lights",[]);l(this,"scene",null);l(this,"batches",[]);l(this,"shadowRenderBindGroupLayout",null);l(this,"lightIndexBuffer",null);l(this,"lightIndexBindGroupLayout",null);l(this,"lightIndexBindGroups",new Map);l(this,"shadowMapLayerViews",new Map);l(this,"cachedShadowMapArray",null);l(this,"_sceneBox",new k);l(this,"_tempBox",new k);this.lightingManager=i,this.batchManager=a,this.initShadowRenderPipeline()}initShadowRenderPipeline(){this.shadowRenderBindGroupLayout=this.device.createBindGroupLayout({label:"Shadow Render Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this.lightIndexBindGroupLayout=this.device.createBindGroupLayout({label:"Light Index Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]});const e=256;this.lightIndexBuffer=this.device.createBuffer({label:"Light Index Buffer",size:e*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});for(let r=0;r<4;r++){this.lightIndexBindGroups.set(r,this.device.createBindGroup({label:`Light Index Bind Group ${r}`,layout:this.lightIndexBindGroupLayout,entries:[{binding:0,resource:{buffer:this.lightIndexBuffer,offset:r*e,size:16}}]}));const s=new Uint32Array([r+1,0,0,0]);this.device.queue.writeBuffer(this.lightIndexBuffer,r*e,s)}const a=this.device.createShaderModule({label:"Shadow Vertex Shader",code:`
|
|
2
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
3
|
+
|
|
4
|
+
struct CameraData {
|
|
5
|
+
viewProjection: mat4x4<f32>,
|
|
6
|
+
frustum: array<vec4<f32>, 6>,
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
struct CameraUniforms {
|
|
10
|
+
mainViewProjection: mat4x4<f32>,
|
|
11
|
+
cameraPosition: vec3<f32>,
|
|
12
|
+
activeLightCount: u32,
|
|
13
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
struct InstanceData {
|
|
17
|
+
modelMatrix: mat4x4<f32>,
|
|
18
|
+
normalMatrix: mat4x4<f32>,
|
|
19
|
+
flags: vec4<f32>,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
struct CulledInstances {
|
|
23
|
+
indices: array<u32>,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
struct LightIndex {
|
|
27
|
+
cameraIndex: u32,
|
|
28
|
+
_pad0: u32,
|
|
29
|
+
_pad1: u32,
|
|
30
|
+
_pad2: u32,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
34
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
35
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
36
|
+
|
|
37
|
+
@group(1) @binding(0) var<uniform> lightInfo: LightIndex;
|
|
38
|
+
|
|
39
|
+
@vertex
|
|
40
|
+
fn main(
|
|
41
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
42
|
+
@location(0) position: vec3<f32>
|
|
43
|
+
) -> @invariant @builtin(position) vec4<f32> {
|
|
44
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
45
|
+
let modelMatrix = instances[actualIndex].modelMatrix;
|
|
46
|
+
let worldPos = modelMatrix * vec4<f32>(position, 1.0);
|
|
47
|
+
|
|
48
|
+
// Get light VP from cameras array using light index
|
|
49
|
+
let lightVP = cameraUniforms.cameras[lightInfo.cameraIndex].viewProjection;
|
|
50
|
+
return lightVP * worldPos;
|
|
51
|
+
}
|
|
52
|
+
`});this.shadowPipeline=this.device.createRenderPipeline({label:"Shadow Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.shadowRenderBindGroupLayout,this.lightIndexBindGroupLayout]}),vertex:{module:a,entryPoint:"main",buffers:[{arrayStride:3*4,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},depthStencil:{depthWriteEnabled:!0,depthCompare:"less",format:"depth32float"},primitive:{topology:"triangle-list"}})}setEnabled(e){this.shadowsEnabled=e}setLights(e){this.lights=e.filter(i=>i instanceof j&&i.castShadow)}prepare(e,i){if(this.shadowsEnabled){this.scene=e,this.batches=this.batchManager.getBatches();for(const a of this.lights)a.shadow.autoUpdate?this.updateShadowCameraBounds(a,e):(a.shadow.camera.position.copy(a.position),a.shadow.camera.rotation.copy(a.rotation),a.shadow.camera.updateWorldMatrix())}}execute(e){if(!this.shadowsEnabled||!this.scene||this.batches.length===0)return;const i=this.lightingManager.shadowMapArray;if(i){this.cachedShadowMapArray!==i&&(this.shadowMapLayerViews.clear(),this.cachedShadowMapArray=i);for(let a=0;a<this.lights.length;a++){const s=this.lights[a]._shadowLayerIndex;s===void 0||s<0||this.renderShadowForLight(e,a,i,s)}}}renderShadowForLight(e,i,a,r){let s=this.shadowMapLayerViews.get(r);s||(s=a.createView({label:`Shadow Map Layer ${r}`,baseArrayLayer:r,arrayLayerCount:1,dimension:"2d"}),this.shadowMapLayerViews.set(r,s));const n=e.beginRenderPass({label:`Shadow Pass - Light ${i}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});n.setPipeline(this.shadowPipeline);const o=this.lightIndexBindGroups.get(i);o&&n.setBindGroup(1,o);const c=i+1;for(const u of this.batches){const h=this.batchManager.getRenderBindGroup(u,c),p=this.batchManager.getGeometryData(u.geometry);n.setBindGroup(0,h),n.setVertexBuffer(0,p.vertexBuffer);const d=this.batchManager.getIndirectBufferOffset(c);p.indexBuffer?(n.setIndexBuffer(p.indexBuffer,"uint32"),n.drawIndexedIndirect(u.indirectBuffer,d)):n.drawIndirect(u.indirectBuffer,d)}n.end()}updateShadowCameraBounds(e,i){this._sceneBox.makeEmpty();let a=!1;if(i.traverse(o=>{o instanceof q&&(o.castShadow||o.receiveShadow)&&o.geometry.boundingBox&&(this._tempBox.copy(o.geometry.boundingBox),this._tempBox.applyMatrix4(o.worldMatrix),a?this._sceneBox.union(this._tempBox):(this._sceneBox.copy(this._tempBox),a=!0))}),!a)return;e.shadow.camera.position.copy(e.position),e.shadow.camera.rotation.copy(e.rotation),e.shadow.camera.updateWorldMatrix();const r=e.shadow.camera.viewMatrix,s=this._sceneBox.clone().applyMatrix4(r),n=1;e.shadow.camera.left=s.min.x-n,e.shadow.camera.right=s.max.x+n,e.shadow.camera.bottom=s.min.y-n,e.shadow.camera.top=s.max.y+n,e.shadow.camera.near=-s.max.z-n,e.shadow.camera.far=-s.min.z+n,e.shadow.camera.updateProjectionMatrix()}dispose(){this.shadowMapLayerViews.clear(),this.cachedShadowMapArray=null,this.lightIndexBindGroups.clear(),this.lightIndexBuffer&&(this.lightIndexBuffer.destroy(),this.lightIndexBuffer=null)}}class ze extends Y{constructor(e,i,a=1){super(e,"Depth Pre-Pass Phase");l(this,"batchManager");l(this,"depthTextureView",null);l(this,"sampleCount");l(this,"depthPipeline",null);l(this,"opaqueBatches",[]);this.batchManager=i,this.sampleCount=a,this.initDepthPipeline()}initDepthPipeline(){const e=this.batchManager.getRenderBindGroupLayout(),a=this.device.createShaderModule({label:"Depth Pre-Pass Vertex Shader",code:`
|
|
53
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
54
|
+
|
|
55
|
+
struct CameraData {
|
|
56
|
+
viewProjection: mat4x4<f32>,
|
|
57
|
+
frustum: array<vec4<f32>, 6>,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
struct CameraUniforms {
|
|
61
|
+
mainViewProjection: mat4x4<f32>,
|
|
62
|
+
cameraPosition: vec3<f32>,
|
|
63
|
+
activeLightCount: u32,
|
|
64
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
struct InstanceData {
|
|
68
|
+
modelMatrix: mat4x4<f32>,
|
|
69
|
+
normalMatrix: mat4x4<f32>,
|
|
70
|
+
flags: vec4<f32>,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
struct CulledInstances {
|
|
74
|
+
indices: array<u32>,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
78
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
79
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
80
|
+
|
|
81
|
+
@vertex
|
|
82
|
+
fn main(
|
|
83
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
84
|
+
@location(0) position: vec3<f32>
|
|
85
|
+
) -> @invariant @builtin(position) vec4<f32> {
|
|
86
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
87
|
+
let worldPos = instances[actualIndex].modelMatrix * vec4<f32>(position, 1.0);
|
|
88
|
+
return cameraUniforms.mainViewProjection * worldPos;
|
|
89
|
+
}
|
|
90
|
+
`});this.depthPipeline=this.device.createRenderPipeline({label:"Depth Pre-Pass Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[e]}),vertex:{module:a,entryPoint:"main",buffers:[{arrayStride:3*4,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},depthStencil:{depthWriteEnabled:!0,depthCompare:"less",format:"depth24plus"},primitive:{topology:"triangle-list"},multisample:{count:this.sampleCount}})}setDepthTextureView(e){this.depthTextureView=e}prepare(e,i){const a=this.batchManager.getBatches();this.opaqueBatches=a.filter(r=>!r.material.transparent)}execute(e){if(!this.depthTextureView||this.opaqueBatches.length===0)return;const i=e.beginRenderPass({label:"Depth Pre-Pass",colorAttachments:[],depthStencilAttachment:{view:this.depthTextureView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});if(!this.depthPipeline)return;i.setPipeline(this.depthPipeline);const a=0;for(const r of this.opaqueBatches){const s=this.batchManager.getRenderBindGroup(r,a),n=this.batchManager.getGeometryData(r.geometry);i.setBindGroup(0,s),i.setVertexBuffer(0,n.vertexBuffer);const o=this.batchManager.getIndirectBufferOffset(a);n.indexBuffer?(i.setIndexBuffer(n.indexBuffer,"uint32"),i.drawIndexedIndirect(r.indirectBuffer,o)):i.drawIndirect(r.indirectBuffer,o)}i.end()}dispose(){this.depthPipeline=null,this.opaqueBatches=[]}}class Ee extends Y{constructor(e,i,a,r=1){super(e,"Skybox Render Phase");l(this,"environmentManager");l(this,"presentationFormat");l(this,"sampleCount");l(this,"pipeline",null);l(this,"bindGroupLayout",null);l(this,"cameraBuffer",null);l(this,"paramsBuffer",null);l(this,"bindGroup",null);l(this,"colorTextureView",null);l(this,"depthTextureView",null);l(this,"environment",null);this.environmentManager=i,this.presentationFormat=a,this.sampleCount=r,this.createResources(),this.createPipeline()}createResources(){this.cameraBuffer=this.device.createBuffer({label:"Skybox Camera Buffer",size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.paramsBuffer=this.device.createBuffer({label:"Skybox Params Buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}createPipeline(){const e=`
|
|
91
|
+
struct VertexOutput {
|
|
92
|
+
@builtin(position) position: vec4<f32>,
|
|
93
|
+
@location(0) direction: vec3<f32>,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
@group(0) @binding(0) var<uniform> inverseViewProjection: mat4x4<f32>;
|
|
97
|
+
|
|
98
|
+
@vertex
|
|
99
|
+
fn main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
|
|
100
|
+
// Fullscreen triangle
|
|
101
|
+
var positions = array<vec2<f32>, 3>(
|
|
102
|
+
vec2<f32>(-1.0, -1.0),
|
|
103
|
+
vec2<f32>(3.0, -1.0),
|
|
104
|
+
vec2<f32>(-1.0, 3.0)
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
var output: VertexOutput;
|
|
108
|
+
let pos = positions[vertexIndex];
|
|
109
|
+
output.position = vec4<f32>(pos, 0.9999, 1.0); // Near far plane
|
|
110
|
+
|
|
111
|
+
// Compute world direction from clip space
|
|
112
|
+
let clipPos = vec4<f32>(pos, 1.0, 1.0);
|
|
113
|
+
let worldPos = inverseViewProjection * clipPos;
|
|
114
|
+
output.direction = normalize(worldPos.xyz / worldPos.w);
|
|
115
|
+
|
|
116
|
+
return output;
|
|
117
|
+
}
|
|
118
|
+
`,i=`
|
|
119
|
+
@group(0) @binding(1) var envCubemap: texture_cube<f32>;
|
|
120
|
+
@group(0) @binding(2) var envSampler: sampler;
|
|
121
|
+
@group(0) @binding(3) var<uniform> params: vec4<f32>; // x: intensity
|
|
122
|
+
|
|
123
|
+
@fragment
|
|
124
|
+
fn main(@location(0) direction: vec3<f32>) -> @location(0) vec4<f32> {
|
|
125
|
+
let color = textureSample(envCubemap, envSampler, direction).rgb * params.x;
|
|
126
|
+
|
|
127
|
+
// Tone mapping (Reinhard)
|
|
128
|
+
let mapped = color / (color + vec3<f32>(1.0));
|
|
129
|
+
|
|
130
|
+
// Gamma correction
|
|
131
|
+
let gammaCorrected = pow(mapped, vec3<f32>(1.0 / 2.2));
|
|
132
|
+
|
|
133
|
+
return vec4<f32>(gammaCorrected, 1.0);
|
|
134
|
+
}
|
|
135
|
+
`,a=this.device.createShaderModule({label:"Skybox Vertex Shader",code:e}),r=this.device.createShaderModule({label:"Skybox Fragment Shader",code:i});this.bindGroupLayout=this.device.createBindGroupLayout({label:"Skybox Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.pipeline=this.device.createRenderPipeline({label:"Skybox Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.bindGroupLayout]}),vertex:{module:a,entryPoint:"main"},fragment:{module:r,entryPoint:"main",targets:[{format:this.presentationFormat}]},primitive:{topology:"triangle-list",frontFace:"ccw",cullMode:"none"},depthStencil:{depthWriteEnabled:!1,depthCompare:"less-equal",format:"depth24plus"},multisample:{count:this.sampleCount}})}setEnvironment(e){this.environment=e,this.bindGroup=null}setRenderTargets(e,i){this.colorTextureView=e,this.depthTextureView=i}prepare(e,i){const a=i.viewMatrix.clone();a.elements[12]=0,a.elements[13]=0,a.elements[14]=0;const s=i.projectionMatrix.clone().multiply(a).clone().invert();this.device.queue.writeBuffer(this.cameraBuffer,0,new Float32Array(s.elements));const n=this.environmentManager.getSkyboxResources(this.environment);this.device.queue.writeBuffer(this.paramsBuffer,0,new Float32Array([n.intensity,0,0,0])),this.bindGroup||(this.bindGroup=this.device.createBindGroup({layout:this.bindGroupLayout,entries:[{binding:0,resource:{buffer:this.cameraBuffer}},{binding:1,resource:n.cubemapView},{binding:2,resource:n.sampler},{binding:3,resource:{buffer:this.paramsBuffer}}]}))}execute(e){if(!this.colorTextureView||!this.depthTextureView||!this.environment)return;const i=this.environmentManager.getSkyboxResources(this.environment);this.bindGroup=this.device.createBindGroup({layout:this.bindGroupLayout,entries:[{binding:0,resource:{buffer:this.cameraBuffer}},{binding:1,resource:i.cubemapView},{binding:2,resource:i.sampler},{binding:3,resource:{buffer:this.paramsBuffer}}]});const a=e.beginRenderPass({label:"Skybox Render Pass",colorAttachments:[{view:this.colorTextureView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:1}}],depthStencilAttachment:{view:this.depthTextureView,depthLoadOp:"load",depthStoreOp:"store"}});a.setPipeline(this.pipeline),a.setBindGroup(0,this.bindGroup),a.draw(3),a.end()}dispose(){var e,i;(e=this.cameraBuffer)==null||e.destroy(),(i=this.paramsBuffer)==null||i.destroy(),this.pipeline=null,this.bindGroup=null}}const Pe=64,Re=5,De=`
|
|
136
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
137
|
+
const WORKGROUP_SIZE: u32 = 64u;
|
|
138
|
+
|
|
139
|
+
struct CameraData {
|
|
140
|
+
viewProjection: mat4x4<f32>,
|
|
141
|
+
frustum: array<vec4<f32>, 6>,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
struct CameraUniforms {
|
|
145
|
+
mainViewProjection: mat4x4<f32>,
|
|
146
|
+
cameraPosition: vec3<f32>,
|
|
147
|
+
activeLightCount: u32,
|
|
148
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
struct InstanceData {
|
|
152
|
+
modelMatrix: mat4x4<f32>,
|
|
153
|
+
normalMatrix: mat4x4<f32>,
|
|
154
|
+
flags: vec4<f32>, // x: receiveShadow, y: castShadow, z: padding, w: padding
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
struct CulledInstances {
|
|
158
|
+
indices: array<u32>,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
struct IndirectArgs {
|
|
162
|
+
indexCount: u32,
|
|
163
|
+
instanceCount: atomic<u32>,
|
|
164
|
+
firstIndex: u32,
|
|
165
|
+
baseVertex: u32,
|
|
166
|
+
firstInstance: u32,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
struct BatchInfo {
|
|
170
|
+
instanceOffset: u32,
|
|
171
|
+
instanceCount: u32,
|
|
172
|
+
boundingSphereRadius: f32,
|
|
173
|
+
culledStridePerCamera: u32, // Aligned stride in u32 count (256-byte aligned / 4)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
@group(0) @binding(0) var<uniform> cameraUniforms: CameraUniforms;
|
|
177
|
+
|
|
178
|
+
@group(1) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
179
|
+
@group(1) @binding(1) var<storage, read_write> culled: CulledInstances;
|
|
180
|
+
@group(1) @binding(2) var<storage, read_write> indirectArgs: array<IndirectArgs, MAX_CAMERAS>;
|
|
181
|
+
@group(1) @binding(3) var<uniform> batchInfo: BatchInfo;
|
|
182
|
+
|
|
183
|
+
fn testFrustum(worldPos: vec4<f32>, radius: f32, cameraIndex: u32) -> bool {
|
|
184
|
+
let camera = cameraUniforms.cameras[cameraIndex];
|
|
185
|
+
|
|
186
|
+
for (var i = 0u; i < 6u; i++) {
|
|
187
|
+
let plane = camera.frustum[i];
|
|
188
|
+
if (dot(plane, worldPos) < -radius) {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
fn getScaledRadius(instanceIndex: u32) -> f32 {
|
|
196
|
+
let worldMatrix = instances[instanceIndex].modelMatrix;
|
|
197
|
+
|
|
198
|
+
// Extract scale from matrix basis vectors (squared lengths to avoid sqrt)
|
|
199
|
+
let scaleXSq = dot(worldMatrix[0].xyz, worldMatrix[0].xyz);
|
|
200
|
+
let scaleYSq = dot(worldMatrix[1].xyz, worldMatrix[1].xyz);
|
|
201
|
+
let scaleZSq = dot(worldMatrix[2].xyz, worldMatrix[2].xyz);
|
|
202
|
+
let maxScaleSq = max(max(scaleXSq, scaleYSq), scaleZSq);
|
|
203
|
+
|
|
204
|
+
// Use sqrt only once for the max scale
|
|
205
|
+
return batchInfo.boundingSphereRadius * sqrt(maxScaleSq);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
@compute @workgroup_size(${Pe})
|
|
209
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
210
|
+
let localIndex = globalId.x;
|
|
211
|
+
if (localIndex >= batchInfo.instanceCount) {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
let instanceIndex = batchInfo.instanceOffset + localIndex;
|
|
216
|
+
let instance = instances[instanceIndex];
|
|
217
|
+
|
|
218
|
+
// Extract world position from model matrix
|
|
219
|
+
let worldPos = vec4<f32>(
|
|
220
|
+
instance.modelMatrix[3][0],
|
|
221
|
+
instance.modelMatrix[3][1],
|
|
222
|
+
instance.modelMatrix[3][2],
|
|
223
|
+
1.0
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
let radius = getScaledRadius(instanceIndex);
|
|
227
|
+
let castShadow = instance.flags.y > 0.5;
|
|
228
|
+
|
|
229
|
+
// Use aligned stride for buffer offsets (in u32 count)
|
|
230
|
+
let slotsPerCamera = batchInfo.culledStridePerCamera;
|
|
231
|
+
|
|
232
|
+
// Test main camera (camera 0) - all objects
|
|
233
|
+
if (testFrustum(worldPos, radius, 0u)) {
|
|
234
|
+
let culledIndex = atomicAdd(&indirectArgs[0].instanceCount, 1u);
|
|
235
|
+
culled.indices[culledIndex] = instanceIndex;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Test shadow light cameras (cameras 1-4) - only shadow casters
|
|
239
|
+
if (castShadow) {
|
|
240
|
+
let numLights = cameraUniforms.activeLightCount;
|
|
241
|
+
for (var lightIdx = 0u; lightIdx < numLights; lightIdx++) {
|
|
242
|
+
let cameraIdx = lightIdx + 1u;
|
|
243
|
+
if (testFrustum(worldPos, radius, cameraIdx)) {
|
|
244
|
+
let culledIndex = atomicAdd(&indirectArgs[cameraIdx].instanceCount, 1u);
|
|
245
|
+
let bufferOffset = cameraIdx * slotsPerCamera;
|
|
246
|
+
culled.indices[bufferOffset + culledIndex] = instanceIndex;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
`;class Fe extends Y{constructor(e){super(e,"Unified Culling Compute Phase");l(this,"cullingPipeline",null);l(this,"batchManager",null)}setBatchManager(e){this.batchManager=e,this.initPipeline()}initPipeline(){if(!this.batchManager)return;const e=this.device.createShaderModule({label:"Unified Culling Shader",code:De});this.cullingPipeline=this.device.createComputePipeline({label:"Unified Culling Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.batchManager.getCameraBindGroupLayout(),this.batchManager.getCullBindGroupLayout()]}),compute:{module:e,entryPoint:"main"}})}prepare(e,i){}execute(e){if(!this.cullingPipeline||!this.batchManager)return;const i=this.batchManager.getBatches();if(i.length===0)return;const a=this.batchManager.getCameraBindGroup();if(!a)return;for(const s of i)for(let n=0;n<Re;n++){const o=n*20+4;e.clearBuffer(s.indirectBuffer,o,4)}const r=e.beginComputePass({label:"Unified Frustum Culling"});r.setPipeline(this.cullingPipeline),r.setBindGroup(0,a);for(const s of i){const n=this.batchManager.getCullBindGroup(s);r.setBindGroup(1,n);const o=Math.ceil(s.instanceCount/Pe);r.dispatchWorkgroups(o)}r.end()}}const xe=36,Ne=1024*1024,V=5,_=256;class Ve{constructor(t){l(this,"device");l(this,"instanceBuffer",null);l(this,"instanceBufferCapacity",0);l(this,"instanceDataArray",null);l(this,"batchCache",new Map);l(this,"geometryCache",new Map);l(this,"batches",[]);l(this,"totalInstances",0);l(this,"cameraBuffer",null);l(this,"cameraBindGroup",null);l(this,"cameraBindGroupLayout",null);l(this,"cullBindGroupLayout",null);l(this,"renderBindGroupLayout",null);l(this,"_tempMatrix",new A);l(this,"_batchInfoBuffer",new ArrayBuffer(16));l(this,"_batchInfoU32",new Uint32Array(this._batchInfoBuffer));l(this,"_batchInfoF32",new Float32Array(this._batchInfoBuffer));l(this,"_cameraUniformData",new Float32Array(208));l(this,"activeShadowLightCount",0);this.device=t,this.initBindGroupLayouts(),this.initCameraResources()}initBindGroupLayouts(){this.cameraBindGroupLayout=this.device.createBindGroupLayout({label:"Unified Camera Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE|GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this.cullBindGroupLayout=this.device.createBindGroupLayout({label:"Unified Cull Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.renderBindGroupLayout=this.device.createBindGroupLayout({label:"Instance Render Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]})}initCameraResources(){this.cameraBuffer=this.device.createBuffer({label:"Unified Camera Buffer",size:896,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.cameraBindGroup=this.device.createBindGroup({label:"Unified Camera Bind Group",layout:this.cameraBindGroupLayout,entries:[{binding:0,resource:{buffer:this.cameraBuffer}}]})}getCameraBindGroupLayout(){return this.cameraBindGroupLayout}getCullBindGroupLayout(){return this.cullBindGroupLayout}getRenderBindGroupLayout(){return this.renderBindGroupLayout}getCameraBindGroup(){return this.cameraBindGroup}getCameraBuffer(){return this.cameraBuffer}getActiveShadowLightCount(){return this.activeShadowLightCount}getGeometryData(t){const e=this.geometryCache.get(t.id);return e&&e.version===t.version?e:e?this.updateGeometryBuffers(t,e):this.createGeometryBuffers(t)}createGeometryBuffers(t){const e=this.device.createBuffer({label:`Vertex Buffer for Geometry ${t.id}`,size:t.vertices.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(e,0,t.vertices);let i=null;if(t.normals)i=this.device.createBuffer({label:`Normal Buffer for Geometry ${t.id}`,size:t.normals.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(i,0,t.normals);else{const o=new Float32Array(t.vertices.length);i=this.device.createBuffer({label:`Dummy Normal Buffer for Geometry ${t.id}`,size:o.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(i,0,o)}let a=null;t.uvs&&(a=this.device.createBuffer({label:`UV Buffer for Geometry ${t.id}`,size:t.uvs.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(a,0,t.uvs));let r=null;if(t.tangents)r=this.device.createBuffer({label:`Tangent Buffer for Geometry ${t.id}`,size:t.tangents.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(r,0,t.tangents);else{const o=new Float32Array(t.vertices.length/3*4);r=this.device.createBuffer({label:`Dummy Tangent Buffer for Geometry ${t.id}`,size:o.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(r,0,o)}let s=null;t.indices&&(s=this.device.createBuffer({label:`Index Buffer for Geometry ${t.id}`,size:t.indices.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this.device.queue.writeBuffer(s,0,t.indices));const n={vertexBuffer:e,normalBuffer:i,uvBuffer:a,tangentBuffer:r,indexBuffer:s,version:t.version};return this.geometryCache.set(t.id,n),n}updateGeometryBuffers(t,e){var r,s,n,o;const i=e.vertexBuffer.size!==t.vertices.byteLength,a=e.indexBuffer&&t.indices&&e.indexBuffer.size!==t.indices.byteLength;return i||a?(e.vertexBuffer.destroy(),(r=e.normalBuffer)==null||r.destroy(),(s=e.uvBuffer)==null||s.destroy(),(n=e.tangentBuffer)==null||n.destroy(),(o=e.indexBuffer)==null||o.destroy(),this.geometryCache.delete(t.id),this.createGeometryBuffers(t)):(this.device.queue.writeBuffer(e.vertexBuffer,0,t.vertices),e.normalBuffer&&t.normals&&this.device.queue.writeBuffer(e.normalBuffer,0,t.normals),e.uvBuffer&&t.uvs&&this.device.queue.writeBuffer(e.uvBuffer,0,t.uvs),e.tangentBuffer&&t.tangents&&this.device.queue.writeBuffer(e.tangentBuffer,0,t.tangents),e.indexBuffer&&t.indices&&this.device.queue.writeBuffer(e.indexBuffer,0,t.indices),e.version=t.version,e)}getBatchKey(t){return`${t.geometry.id}_${t.material.id}`}computeBoundingSphereRadius(t){const e=t.boundingBox;if(!e)return 1;const i=e.max.x-e.min.x,a=e.max.y-e.min.y,r=e.max.z-e.min.z;return Math.sqrt(i*i+a*a+r*r)/2}prepareBatches(t){const e=new Map;for(const i of t){const a=this.getBatchKey(i);e.has(a)||e.set(a,[]),e.get(a).push(i)}this.batches=[],this.totalInstances=0;for(const[i,a]of e){let r=this.batchCache.get(i);r||(r=this.createBatch(i,a[0].geometry,a[0].material),this.batchCache.set(i,r)),r.meshes=a,r.instanceOffset=this.totalInstances,r.instanceCount=a.length,this.ensureBatchResources(r),this.batches.push(r),this.totalInstances+=a.length}return this.batches}createBatch(t,e,i){const a=e.indexCount,r=this.computeBoundingSphereRadius(e),s=this.device.createBuffer({label:`Indirect Args Buffer [${t}]`,size:20*V,usage:GPUBufferUsage.INDIRECT|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),n=new Uint32Array(s.getMappedRange());for(let p=0;p<V;p++){const d=p*5;n[d+0]=a,n[d+1]=0,n[d+2]=0,n[d+3]=0,n[d+4]=0}s.unmap();const o=this.device.createBuffer({label:`Batch Info Buffer [${t}]`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),u=Math.ceil(1024*4/_)*_,h=this.device.createBuffer({label:`Culled Instance Buffer [${t}]`,size:u*V,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return{key:t,geometry:e,material:i,meshes:[],instanceOffset:0,instanceCount:0,boundingSphereRadius:r,culledStridePerCamera:u,indirectBuffer:s,culledInstanceBuffer:h,batchInfoBuffer:o,renderBindGroup:null,cullBindGroup:null}}ensureBatchResources(t){const e=t.instanceCount*4,i=Math.ceil(e/_)*_,a=i*V;if(t.culledInstanceBuffer.size<a){t.culledInstanceBuffer.destroy();const r=Math.ceil(e*2/_)*_,s=Math.max(r*V,_*V);t.culledInstanceBuffer=this.device.createBuffer({label:`Culled Instance Buffer [${t.key}]`,size:s,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),t.culledStridePerCamera=r,t.cullBindGroup=null,t.renderBindGroup=null}else t.culledStridePerCamera=i}ensureInstanceBufferCapacity(t){const e=t*xe*4;if(!this.instanceBuffer||this.instanceBufferCapacity<e){this.instanceBuffer&&this.instanceBuffer.destroy(),this.instanceBufferCapacity=Math.max(e*2,Ne),this.instanceBuffer=this.device.createBuffer({label:"Instance Storage Buffer",size:this.instanceBufferCapacity,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});for(const a of this.batchCache.values())a.cullBindGroup=null,a.renderBindGroup=null}const i=t*xe;(!this.instanceDataArray||this.instanceDataArray.length<i)&&(this.instanceDataArray=new Float32Array(i*2))}updateInstanceBuffer(t){if(this.totalInstances===0)return;this.ensureInstanceBufferCapacity(this.totalInstances);const e=this.instanceDataArray;let i=0;for(const a of t){for(const r of a.meshes){const s=r.worldMatrix;e.set(s.toArray(),i),i+=16;const n=this._tempMatrix.copy(s).invert().transpose();e.set(n.toArray(),i),i+=16,e[i++]=r.receiveShadow?1:0,e[i++]=r.castShadow?1:0,e[i++]=0,e[i++]=0}this._batchInfoU32[0]=a.instanceOffset,this._batchInfoU32[1]=a.instanceCount,this._batchInfoF32[2]=a.boundingSphereRadius,this._batchInfoU32[3]=a.culledStridePerCamera/4,this.device.queue.writeBuffer(a.batchInfoBuffer,0,this._batchInfoBuffer)}this.device.queue.writeBuffer(this.instanceBuffer,0,e,0,this.totalInstances*xe)}updateCameraUniforms(t,e){if(!this.cameraBuffer)return;const i=this._cameraUniformData;i.fill(0),i.set(t.viewProjectionMatrix.elements,0),i[16]=t.position.x,i[17]=t.position.y,i[18]=t.position.z;const a=Math.min(e.length,V-1);this.activeShadowLightCount=a,new Uint32Array(i.buffer,19*4,1)[0]=a;let r=20;i.set(t.viewProjectionMatrix.elements,r),i.set(t.frustumPlanes,r+16),r+=40;for(let s=0;s<a;s++){const n=e[s];if(n.castShadow&&n.shadow.camera){const o=n.shadow.camera;i.set(o.viewProjectionMatrix.elements,r),i.set(o.frustumPlanes,r+16)}r+=40}this.device.queue.writeBuffer(this.cameraBuffer,0,i)}getCullBindGroup(t){return t.cullBindGroup||(t.cullBindGroup=this.device.createBindGroup({label:`Cull Bind Group [${t.key}]`,layout:this.cullBindGroupLayout,entries:[{binding:0,resource:{buffer:this.instanceBuffer}},{binding:1,resource:{buffer:t.culledInstanceBuffer}},{binding:2,resource:{buffer:t.indirectBuffer}},{binding:3,resource:{buffer:t.batchInfoBuffer}}]})),t.cullBindGroup}getRenderBindGroup(t,e){const i=e*t.culledStridePerCamera,a=Math.min(t.instanceCount*4,t.culledStridePerCamera);return e===0?(t.renderBindGroup||(t.renderBindGroup=this.device.createBindGroup({label:`Render Bind Group [${t.key}] Camera 0`,layout:this.renderBindGroupLayout,entries:[{binding:0,resource:{buffer:this.instanceBuffer}},{binding:1,resource:{buffer:t.culledInstanceBuffer,offset:0,size:a}},{binding:2,resource:{buffer:this.cameraBuffer}}]})),t.renderBindGroup):this.device.createBindGroup({label:`Render Bind Group [${t.key}] Camera ${e}`,layout:this.renderBindGroupLayout,entries:[{binding:0,resource:{buffer:this.instanceBuffer}},{binding:1,resource:{buffer:t.culledInstanceBuffer,offset:i,size:a}},{binding:2,resource:{buffer:this.cameraBuffer}}]})}getIndirectBufferOffset(t){return t*20}getBatches(){return this.batches}getTotalInstances(){return this.totalInstances}getStats(){return{totalBatches:this.batches.length,totalInstances:this.totalInstances,drawCalls:this.batches.length,instanceBufferSize:this.instanceBufferCapacity}}dispose(){this.instanceBuffer&&(this.instanceBuffer.destroy(),this.instanceBuffer=null),this.cameraBuffer&&(this.cameraBuffer.destroy(),this.cameraBuffer=null);for(const t of this.batchCache.values())t.indirectBuffer.destroy(),t.culledInstanceBuffer.destroy(),t.batchInfoBuffer.destroy();this.batchCache.clear(),this.geometryCache.clear(),this.batches=[],this.totalInstances=0}}class _e{constructor(t){l(this,"device");l(this,"samplerCache",new Map);l(this,"dummyWhiteTexture");l(this,"dummyNormalTexture");l(this,"dummyBlackTexture");l(this,"defaultSampler");l(this,"mipmapPipeline",null);l(this,"mipmapBindGroupLayout",null);this.device=t,this.createDummyTextures(),this.createMipmapPipeline()}createDummyTextures(){const t=this.device.createTexture({label:"Dummy White Texture",size:[1,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:t},new Uint8Array([255,255,255,255]),{bytesPerRow:4},[1,1]),this.dummyWhiteTexture=t.createView();const e=this.device.createTexture({label:"Dummy Normal Texture",size:[1,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:e},new Uint8Array([128,128,255,255]),{bytesPerRow:4},[1,1]),this.dummyNormalTexture=e.createView();const i=this.device.createTexture({label:"Dummy Black Texture",size:[1,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:i},new Uint8Array([0,0,0,255]),{bytesPerRow:4},[1,1]),this.dummyBlackTexture=i.createView(),this.defaultSampler=this.device.createSampler({label:"Default Sampler",minFilter:"linear",magFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat"})}createMipmapPipeline(){const e=this.device.createShaderModule({label:"Mipmap Generation Shader",code:`
|
|
252
|
+
@group(0) @binding(0) var srcTexture: texture_2d<f32>;
|
|
253
|
+
@group(0) @binding(1) var dstTexture: texture_storage_2d<rgba8unorm, write>;
|
|
254
|
+
|
|
255
|
+
@compute @workgroup_size(8, 8)
|
|
256
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
257
|
+
let dstSize = textureDimensions(dstTexture);
|
|
258
|
+
if (globalId.x >= dstSize.x || globalId.y >= dstSize.y) {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
let srcCoord = globalId.xy * 2u;
|
|
263
|
+
|
|
264
|
+
let s00 = textureLoad(srcTexture, srcCoord + vec2<u32>(0u, 0u), 0);
|
|
265
|
+
let s10 = textureLoad(srcTexture, srcCoord + vec2<u32>(1u, 0u), 0);
|
|
266
|
+
let s01 = textureLoad(srcTexture, srcCoord + vec2<u32>(0u, 1u), 0);
|
|
267
|
+
let s11 = textureLoad(srcTexture, srcCoord + vec2<u32>(1u, 1u), 0);
|
|
268
|
+
|
|
269
|
+
let avg = (s00 + s10 + s01 + s11) * 0.25;
|
|
270
|
+
textureStore(dstTexture, globalId.xy, avg);
|
|
271
|
+
}
|
|
272
|
+
`});this.mipmapBindGroupLayout=this.device.createBindGroupLayout({label:"Mipmap Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba8unorm"}}]}),this.mipmapPipeline=this.device.createComputePipeline({label:"Mipmap Generation Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.mipmapBindGroupLayout]}),compute:{module:e,entryPoint:"main"}})}uploadTexture(t){if(!t.source)return this.dummyWhiteTexture;if(!t.needsUpdate&&t.gpuTextureView)return t.gpuTextureView;const e=t.source,i=e.width,a=e.height,r=t.mipmaps?Math.floor(Math.log2(Math.max(i,a)))+1:1;return t.gpuTexture&&t.gpuTexture.destroy(),t.gpuTexture=this.device.createTexture({label:`Texture ${t.id}`,size:[i,a],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.STORAGE_BINDING,mipLevelCount:r}),this.device.queue.copyExternalImageToTexture({source:e},{texture:t.gpuTexture},[i,a]),t.mipmaps&&r>1&&this.generateMipmaps(t.gpuTexture,i,a,r),t.gpuTextureView=t.gpuTexture.createView(),t.needsUpdate=!1,t.gpuTextureView}generateMipmaps(t,e,i,a){if(!this.mipmapPipeline||!this.mipmapBindGroupLayout)return;const r=this.device.createCommandEncoder({label:"Mipmap Generation"});let s=e,n=i;for(let o=1;o<a;o++){const c=Math.max(1,s>>1),u=Math.max(1,n>>1),h=t.createView({baseMipLevel:o-1,mipLevelCount:1}),p=t.createView({baseMipLevel:o,mipLevelCount:1}),d=this.device.createBindGroup({layout:this.mipmapBindGroupLayout,entries:[{binding:0,resource:h},{binding:1,resource:p}]}),f=r.beginComputePass();f.setPipeline(this.mipmapPipeline),f.setBindGroup(0,d),f.dispatchWorkgroups(Math.ceil(c/8),Math.ceil(u/8)),f.end(),s=c,n=u}this.device.queue.submit([r.finish()])}getSampler(t){const e=`${t.wrapS}_${t.wrapT}_${t.minFilter}_${t.magFilter}_${t.mipmaps}`;let i=this.samplerCache.get(e);return i||(i=this.device.createSampler({addressModeU:t.wrapS,addressModeV:t.wrapT,minFilter:t.minFilter,magFilter:t.magFilter,mipmapFilter:t.mipmaps?"linear":"nearest"}),this.samplerCache.set(e,i)),i}dispose(){this.samplerCache.clear()}}function Oe(w){const t=new Float32Array(1),e=new Int32Array(t.buffer);t[0]=w;const i=e[0],a=i>>16&32768,r=(i>>23&255)-127+15;let s=i>>13&1023;return r<=0?r<-10?a:(s=(s|1024)>>1-r,a|s):r===143?s?a|32256:a|31744:r>30?a|31744:a|r<<10|s}class ke{constructor(t){l(this,"device");l(this,"equirectToCubemapPipeline",null);l(this,"irradiancePipeline",null);l(this,"prefilterPipeline",null);l(this,"brdfPipeline",null);l(this,"equirectBindGroupLayout",null);l(this,"irradianceBindGroupLayout",null);l(this,"prefilterBindGroupLayout",null);l(this,"brdfBindGroupLayout",null);l(this,"environmentBindGroupLayout",null);l(this,"brdfLUT",null);l(this,"brdfLUTView",null);l(this,"brdfGenerated",!1);l(this,"dummyCubemapView",null);l(this,"cubemapSampler",null);l(this,"brdfSampler",null);l(this,"envParamsBuffer",null);l(this,"environmentBindGroupCache",new Map);l(this,"dummyEnvironmentBindGroup",null);this.device=t,this.createPipelines(),this.createDummyResources(),this.createEnvironmentBindGroupLayout(),this.generateBRDFLUT()}createPipelines(){this.createEquirectToCubemapPipeline(),this.createIrradiancePipeline(),this.createPrefilterPipeline(),this.createBRDFPipeline()}createEquirectToCubemapPipeline(){const e=this.device.createShaderModule({label:"Equirect to Cubemap Shader",code:`
|
|
273
|
+
const PI: f32 = 3.14159265359;
|
|
274
|
+
|
|
275
|
+
@group(0) @binding(0) var equirectMap: texture_2d<f32>;
|
|
276
|
+
@group(0) @binding(1) var equirectSampler: sampler;
|
|
277
|
+
@group(0) @binding(2) var outputCubemap: texture_storage_2d_array<rgba16float, write>;
|
|
278
|
+
|
|
279
|
+
fn getCubemapDirection(face: u32, uv: vec2<f32>) -> vec3<f32> {
|
|
280
|
+
let u = uv.x * 2.0 - 1.0;
|
|
281
|
+
let v = uv.y * 2.0 - 1.0;
|
|
282
|
+
|
|
283
|
+
switch (face) {
|
|
284
|
+
case 0u: { return normalize(vec3<f32>(1.0, -v, -u)); } // +X
|
|
285
|
+
case 1u: { return normalize(vec3<f32>(-1.0, -v, u)); } // -X
|
|
286
|
+
case 2u: { return normalize(vec3<f32>(u, 1.0, v)); } // +Y
|
|
287
|
+
case 3u: { return normalize(vec3<f32>(u, -1.0, -v)); } // -Y
|
|
288
|
+
case 4u: { return normalize(vec3<f32>(u, -v, 1.0)); } // +Z
|
|
289
|
+
default: { return normalize(vec3<f32>(-u, -v, -1.0)); } // -Z
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
fn sampleEquirectangular(dir: vec3<f32>) -> vec4<f32> {
|
|
294
|
+
let theta = atan2(dir.z, dir.x);
|
|
295
|
+
let phi = asin(clamp(dir.y, -1.0, 1.0));
|
|
296
|
+
let u = (theta / PI + 1.0) * 0.5;
|
|
297
|
+
let v = 0.5 - phi / PI; // V=0 at top (north pole), V=1 at bottom (south pole)
|
|
298
|
+
return textureSampleLevel(equirectMap, equirectSampler, vec2<f32>(u, v), 0.0);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
@compute @workgroup_size(8, 8, 1)
|
|
302
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
303
|
+
let faceSize = textureDimensions(outputCubemap).x;
|
|
304
|
+
if (globalId.x >= faceSize || globalId.y >= faceSize) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
let uv = (vec2<f32>(globalId.xy) + 0.5) / f32(faceSize);
|
|
309
|
+
let dir = getCubemapDirection(globalId.z, uv);
|
|
310
|
+
let color = sampleEquirectangular(dir);
|
|
311
|
+
|
|
312
|
+
textureStore(outputCubemap, globalId.xy, globalId.z, color);
|
|
313
|
+
}
|
|
314
|
+
`});this.equirectBindGroupLayout=this.device.createBindGroupLayout({label:"Equirect to Cubemap Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"2d-array"}}]}),this.equirectToCubemapPipeline=this.device.createComputePipeline({label:"Equirect to Cubemap Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.equirectBindGroupLayout]}),compute:{module:e,entryPoint:"main"}})}createIrradiancePipeline(){const e=this.device.createShaderModule({label:"Irradiance Convolution Shader",code:`
|
|
315
|
+
const PI: f32 = 3.14159265359;
|
|
316
|
+
const SAMPLE_DELTA: f32 = 0.025;
|
|
317
|
+
|
|
318
|
+
@group(0) @binding(0) var envCubemap: texture_cube<f32>;
|
|
319
|
+
@group(0) @binding(1) var envSampler: sampler;
|
|
320
|
+
@group(0) @binding(2) var outputIrradiance: texture_storage_2d_array<rgba16float, write>;
|
|
321
|
+
|
|
322
|
+
fn getCubemapDirection(face: u32, uv: vec2<f32>) -> vec3<f32> {
|
|
323
|
+
let u = uv.x * 2.0 - 1.0;
|
|
324
|
+
let v = uv.y * 2.0 - 1.0;
|
|
325
|
+
|
|
326
|
+
switch (face) {
|
|
327
|
+
case 0u: { return normalize(vec3<f32>(1.0, -v, -u)); }
|
|
328
|
+
case 1u: { return normalize(vec3<f32>(-1.0, -v, u)); }
|
|
329
|
+
case 2u: { return normalize(vec3<f32>(u, 1.0, v)); }
|
|
330
|
+
case 3u: { return normalize(vec3<f32>(u, -1.0, -v)); }
|
|
331
|
+
case 4u: { return normalize(vec3<f32>(u, -v, 1.0)); }
|
|
332
|
+
default: { return normalize(vec3<f32>(-u, -v, -1.0)); }
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
@compute @workgroup_size(8, 8, 1)
|
|
337
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
338
|
+
let faceSize = textureDimensions(outputIrradiance).x;
|
|
339
|
+
if (globalId.x >= faceSize || globalId.y >= faceSize) {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
let uv = (vec2<f32>(globalId.xy) + 0.5) / f32(faceSize);
|
|
344
|
+
let N = getCubemapDirection(globalId.z, uv);
|
|
345
|
+
|
|
346
|
+
// Build tangent frame
|
|
347
|
+
var up = vec3<f32>(0.0, 1.0, 0.0);
|
|
348
|
+
if (abs(N.y) > 0.999) {
|
|
349
|
+
up = vec3<f32>(0.0, 0.0, 1.0);
|
|
350
|
+
}
|
|
351
|
+
let right = normalize(cross(up, N));
|
|
352
|
+
up = cross(N, right);
|
|
353
|
+
|
|
354
|
+
var irradiance = vec3<f32>(0.0);
|
|
355
|
+
var sampleCount = 0.0;
|
|
356
|
+
|
|
357
|
+
// Hemisphere sampling
|
|
358
|
+
for (var phi = 0.0; phi < 2.0 * PI; phi += SAMPLE_DELTA) {
|
|
359
|
+
for (var theta = 0.0; theta < 0.5 * PI; theta += SAMPLE_DELTA) {
|
|
360
|
+
// Spherical to cartesian (in tangent space)
|
|
361
|
+
let tangentSample = vec3<f32>(
|
|
362
|
+
sin(theta) * cos(phi),
|
|
363
|
+
sin(theta) * sin(phi),
|
|
364
|
+
cos(theta)
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
// Tangent to world
|
|
368
|
+
let sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * N;
|
|
369
|
+
|
|
370
|
+
irradiance += textureSampleLevel(envCubemap, envSampler, sampleVec, 0.0).rgb * cos(theta) * sin(theta);
|
|
371
|
+
sampleCount += 1.0;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
irradiance = PI * irradiance / sampleCount;
|
|
376
|
+
textureStore(outputIrradiance, globalId.xy, globalId.z, vec4<f32>(irradiance, 1.0));
|
|
377
|
+
}
|
|
378
|
+
`});this.irradianceBindGroupLayout=this.device.createBindGroupLayout({label:"Irradiance Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"cube"}},{binding:1,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"2d-array"}}]}),this.irradiancePipeline=this.device.createComputePipeline({label:"Irradiance Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.irradianceBindGroupLayout]}),compute:{module:e,entryPoint:"main"}})}createPrefilterPipeline(){const e=this.device.createShaderModule({label:"Prefilter Shader",code:`
|
|
379
|
+
const PI: f32 = 3.14159265359;
|
|
380
|
+
const SAMPLE_COUNT: u32 = 1024u;
|
|
381
|
+
|
|
382
|
+
struct Params {
|
|
383
|
+
roughness: f32,
|
|
384
|
+
resolution: f32,
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
@group(0) @binding(0) var envCubemap: texture_cube<f32>;
|
|
388
|
+
@group(0) @binding(1) var envSampler: sampler;
|
|
389
|
+
@group(0) @binding(2) var outputPrefiltered: texture_storage_2d_array<rgba16float, write>;
|
|
390
|
+
@group(0) @binding(3) var<uniform> params: Params;
|
|
391
|
+
|
|
392
|
+
fn getCubemapDirection(face: u32, uv: vec2<f32>) -> vec3<f32> {
|
|
393
|
+
let u = uv.x * 2.0 - 1.0;
|
|
394
|
+
let v = uv.y * 2.0 - 1.0;
|
|
395
|
+
|
|
396
|
+
switch (face) {
|
|
397
|
+
case 0u: { return normalize(vec3<f32>(1.0, -v, -u)); }
|
|
398
|
+
case 1u: { return normalize(vec3<f32>(-1.0, -v, u)); }
|
|
399
|
+
case 2u: { return normalize(vec3<f32>(u, 1.0, v)); }
|
|
400
|
+
case 3u: { return normalize(vec3<f32>(u, -1.0, -v)); }
|
|
401
|
+
case 4u: { return normalize(vec3<f32>(u, -v, 1.0)); }
|
|
402
|
+
default: { return normalize(vec3<f32>(-u, -v, -1.0)); }
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
fn radicalInverse_VdC(bits_in: u32) -> f32 {
|
|
407
|
+
var bits = bits_in;
|
|
408
|
+
bits = (bits << 16u) | (bits >> 16u);
|
|
409
|
+
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
|
|
410
|
+
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
|
|
411
|
+
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
|
|
412
|
+
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
|
|
413
|
+
return f32(bits) * 2.3283064365386963e-10;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
fn hammersley(i: u32, N: u32) -> vec2<f32> {
|
|
417
|
+
return vec2<f32>(f32(i) / f32(N), radicalInverse_VdC(i));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
fn importanceSampleGGX(Xi: vec2<f32>, N: vec3<f32>, roughness: f32) -> vec3<f32> {
|
|
421
|
+
let a = roughness * roughness;
|
|
422
|
+
|
|
423
|
+
let phi = 2.0 * PI * Xi.x;
|
|
424
|
+
let cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));
|
|
425
|
+
let sinTheta = sqrt(1.0 - cosTheta * cosTheta);
|
|
426
|
+
|
|
427
|
+
// Spherical to cartesian
|
|
428
|
+
let H = vec3<f32>(
|
|
429
|
+
cos(phi) * sinTheta,
|
|
430
|
+
sin(phi) * sinTheta,
|
|
431
|
+
cosTheta
|
|
432
|
+
);
|
|
433
|
+
|
|
434
|
+
// Tangent to world
|
|
435
|
+
var up = vec3<f32>(0.0, 1.0, 0.0);
|
|
436
|
+
if (abs(N.y) > 0.999) {
|
|
437
|
+
up = vec3<f32>(0.0, 0.0, 1.0);
|
|
438
|
+
}
|
|
439
|
+
let tangent = normalize(cross(up, N));
|
|
440
|
+
let bitangent = cross(N, tangent);
|
|
441
|
+
|
|
442
|
+
return normalize(tangent * H.x + bitangent * H.y + N * H.z);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
fn DistributionGGX(N: vec3<f32>, H: vec3<f32>, roughness: f32) -> f32 {
|
|
446
|
+
let a = roughness * roughness;
|
|
447
|
+
let a2 = a * a;
|
|
448
|
+
let NdotH = max(dot(N, H), 0.0);
|
|
449
|
+
let NdotH2 = NdotH * NdotH;
|
|
450
|
+
|
|
451
|
+
let num = a2;
|
|
452
|
+
var denom = (NdotH2 * (a2 - 1.0) + 1.0);
|
|
453
|
+
denom = PI * denom * denom;
|
|
454
|
+
|
|
455
|
+
return num / denom;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
@compute @workgroup_size(8, 8, 1)
|
|
459
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
460
|
+
let faceSize = textureDimensions(outputPrefiltered).x;
|
|
461
|
+
if (globalId.x >= faceSize || globalId.y >= faceSize) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
let uv = (vec2<f32>(globalId.xy) + 0.5) / f32(faceSize);
|
|
466
|
+
let N = getCubemapDirection(globalId.z, uv);
|
|
467
|
+
let R = N;
|
|
468
|
+
let V = R;
|
|
469
|
+
|
|
470
|
+
var prefilteredColor = vec3<f32>(0.0);
|
|
471
|
+
var totalWeight = 0.0;
|
|
472
|
+
|
|
473
|
+
let roughness = max(params.roughness, 0.001);
|
|
474
|
+
|
|
475
|
+
for (var i = 0u; i < SAMPLE_COUNT; i++) {
|
|
476
|
+
let Xi = hammersley(i, SAMPLE_COUNT);
|
|
477
|
+
let H = importanceSampleGGX(Xi, N, roughness);
|
|
478
|
+
let L = normalize(2.0 * dot(V, H) * H - V);
|
|
479
|
+
|
|
480
|
+
let NdotL = max(dot(N, L), 0.0);
|
|
481
|
+
if (NdotL > 0.0) {
|
|
482
|
+
// Sample with mip level based on roughness and PDF
|
|
483
|
+
let D = DistributionGGX(N, H, roughness);
|
|
484
|
+
let NdotH = max(dot(N, H), 0.0);
|
|
485
|
+
let HdotV = max(dot(H, V), 0.0);
|
|
486
|
+
let pdf = D * NdotH / (4.0 * HdotV) + 0.0001;
|
|
487
|
+
|
|
488
|
+
let saTexel = 4.0 * PI / (6.0 * params.resolution * params.resolution);
|
|
489
|
+
let saSample = 1.0 / (f32(SAMPLE_COUNT) * pdf + 0.0001);
|
|
490
|
+
var mipLevel = 0.0;
|
|
491
|
+
if (roughness > 0.0) {
|
|
492
|
+
mipLevel = 0.5 * log2(saSample / saTexel);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
prefilteredColor += textureSampleLevel(envCubemap, envSampler, L, mipLevel).rgb * NdotL;
|
|
496
|
+
totalWeight += NdotL;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
prefilteredColor = prefilteredColor / max(totalWeight, 0.001);
|
|
501
|
+
textureStore(outputPrefiltered, globalId.xy, globalId.z, vec4<f32>(prefilteredColor, 1.0));
|
|
502
|
+
}
|
|
503
|
+
`});this.prefilterBindGroupLayout=this.device.createBindGroupLayout({label:"Prefilter Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"cube"}},{binding:1,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"2d-array"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.prefilterPipeline=this.device.createComputePipeline({label:"Prefilter Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.prefilterBindGroupLayout]}),compute:{module:e,entryPoint:"main"}})}createBRDFPipeline(){const e=this.device.createShaderModule({label:"BRDF LUT Shader",code:`
|
|
504
|
+
const PI: f32 = 3.14159265359;
|
|
505
|
+
const SAMPLE_COUNT: u32 = 1024u;
|
|
506
|
+
|
|
507
|
+
@group(0) @binding(0) var outputBRDF: texture_storage_2d<rgba16float, write>;
|
|
508
|
+
|
|
509
|
+
fn radicalInverse_VdC(bits_in: u32) -> f32 {
|
|
510
|
+
var bits = bits_in;
|
|
511
|
+
bits = (bits << 16u) | (bits >> 16u);
|
|
512
|
+
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
|
|
513
|
+
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
|
|
514
|
+
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
|
|
515
|
+
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
|
|
516
|
+
return f32(bits) * 2.3283064365386963e-10;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
fn hammersley(i: u32, N: u32) -> vec2<f32> {
|
|
520
|
+
return vec2<f32>(f32(i) / f32(N), radicalInverse_VdC(i));
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
fn importanceSampleGGX(Xi: vec2<f32>, N: vec3<f32>, roughness: f32) -> vec3<f32> {
|
|
524
|
+
let a = roughness * roughness;
|
|
525
|
+
|
|
526
|
+
let phi = 2.0 * PI * Xi.x;
|
|
527
|
+
let cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));
|
|
528
|
+
let sinTheta = sqrt(1.0 - cosTheta * cosTheta);
|
|
529
|
+
|
|
530
|
+
let H = vec3<f32>(
|
|
531
|
+
cos(phi) * sinTheta,
|
|
532
|
+
sin(phi) * sinTheta,
|
|
533
|
+
cosTheta
|
|
534
|
+
);
|
|
535
|
+
|
|
536
|
+
var up = vec3<f32>(0.0, 1.0, 0.0);
|
|
537
|
+
if (abs(N.y) > 0.999) {
|
|
538
|
+
up = vec3<f32>(0.0, 0.0, 1.0);
|
|
539
|
+
}
|
|
540
|
+
let tangent = normalize(cross(up, N));
|
|
541
|
+
let bitangent = cross(N, tangent);
|
|
542
|
+
|
|
543
|
+
return normalize(tangent * H.x + bitangent * H.y + N * H.z);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
fn GeometrySchlickGGX(NdotV: f32, roughness: f32) -> f32 {
|
|
547
|
+
let a = roughness;
|
|
548
|
+
let k = (a * a) / 2.0;
|
|
549
|
+
return NdotV / (NdotV * (1.0 - k) + k);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
fn GeometrySmith(N: vec3<f32>, V: vec3<f32>, L: vec3<f32>, roughness: f32) -> f32 {
|
|
553
|
+
let NdotV = max(dot(N, V), 0.0);
|
|
554
|
+
let NdotL = max(dot(N, L), 0.0);
|
|
555
|
+
let ggx2 = GeometrySchlickGGX(NdotV, roughness);
|
|
556
|
+
let ggx1 = GeometrySchlickGGX(NdotL, roughness);
|
|
557
|
+
return ggx1 * ggx2;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
@compute @workgroup_size(8, 8)
|
|
561
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
562
|
+
let size = textureDimensions(outputBRDF);
|
|
563
|
+
if (globalId.x >= size.x || globalId.y >= size.y) {
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
let NdotV = (f32(globalId.x) + 0.5) / f32(size.x);
|
|
568
|
+
let roughness = (f32(globalId.y) + 0.5) / f32(size.y);
|
|
569
|
+
|
|
570
|
+
let V = vec3<f32>(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV);
|
|
571
|
+
let N = vec3<f32>(0.0, 0.0, 1.0);
|
|
572
|
+
|
|
573
|
+
var A = 0.0;
|
|
574
|
+
var B = 0.0;
|
|
575
|
+
|
|
576
|
+
let r = max(roughness, 0.001);
|
|
577
|
+
|
|
578
|
+
for (var i = 0u; i < SAMPLE_COUNT; i++) {
|
|
579
|
+
let Xi = hammersley(i, SAMPLE_COUNT);
|
|
580
|
+
let H = importanceSampleGGX(Xi, N, r);
|
|
581
|
+
let L = normalize(2.0 * dot(V, H) * H - V);
|
|
582
|
+
|
|
583
|
+
let NdotL = max(L.z, 0.0);
|
|
584
|
+
let NdotH = max(H.z, 0.0);
|
|
585
|
+
let VdotH = max(dot(V, H), 0.0);
|
|
586
|
+
|
|
587
|
+
if (NdotL > 0.0) {
|
|
588
|
+
let G = GeometrySmith(N, V, L, r);
|
|
589
|
+
let G_Vis = (G * VdotH) / max(NdotH * NdotV, 0.001);
|
|
590
|
+
let Fc = pow(1.0 - VdotH, 5.0);
|
|
591
|
+
|
|
592
|
+
A += (1.0 - Fc) * G_Vis;
|
|
593
|
+
B += Fc * G_Vis;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
A /= f32(SAMPLE_COUNT);
|
|
598
|
+
B /= f32(SAMPLE_COUNT);
|
|
599
|
+
|
|
600
|
+
textureStore(outputBRDF, globalId.xy, vec4<f32>(A, B, 0.0, 1.0));
|
|
601
|
+
}
|
|
602
|
+
`});this.brdfBindGroupLayout=this.device.createBindGroupLayout({label:"BRDF Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float"}}]}),this.brdfPipeline=this.device.createComputePipeline({label:"BRDF Pipeline",layout:this.device.createPipelineLayout({bindGroupLayouts:[this.brdfBindGroupLayout]}),compute:{module:e,entryPoint:"main"}})}createDummyResources(){const t=this.device.createTexture({label:"Dummy Cubemap",size:[1,1,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,dimension:"2d"}),e=new Float32Array([0,0,0,1]);for(let i=0;i<6;i++)this.device.queue.writeTexture({texture:t,origin:[0,0,i]},e,{bytesPerRow:8},[1,1,1]);this.dummyCubemapView=t.createView({dimension:"cube"}),this.cubemapSampler=this.device.createSampler({label:"Cubemap Sampler",minFilter:"linear",magFilter:"linear",mipmapFilter:"linear"}),this.brdfSampler=this.device.createSampler({label:"BRDF Sampler",minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.envParamsBuffer=this.device.createBuffer({label:"Environment Params Buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}createEnvironmentBindGroupLayout(){this.environmentBindGroupLayout=this.device.createBindGroupLayout({label:"Environment Bind Group Layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]})}generateBRDFLUT(){if(this.brdfGenerated)return;const t=256;this.brdfLUT=this.device.createTexture({label:"BRDF LUT",size:[t,t],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),this.brdfLUTView=this.brdfLUT.createView();const e=this.device.createBindGroup({layout:this.brdfBindGroupLayout,entries:[{binding:0,resource:this.brdfLUTView}]}),i=this.device.createCommandEncoder(),a=i.beginComputePass();a.setPipeline(this.brdfPipeline),a.setBindGroup(0,e),a.dispatchWorkgroups(Math.ceil(t/8),Math.ceil(t/8)),a.end(),this.device.queue.submit([i.finish()]),this.brdfGenerated=!0}processEnvironment(t){var o,c,u,h;if(!t.hdrData||!t.needsUpdate)return;this.generateBRDFLUT();const e=t.resolution,i=t.specularMipLevels;(o=t.equirectTexture)==null||o.destroy(),t.equirectTexture=this.device.createTexture({label:"Equirectangular HDR",size:[t.hdrWidth,t.hdrHeight],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});const a=t.hdrData,r=new Uint16Array(a.length);for(let p=0;p<a.length;p++)r[p]=Oe(a[p]);this.device.queue.writeTexture({texture:t.equirectTexture},r,{bytesPerRow:t.hdrWidth*8},[t.hdrWidth,t.hdrHeight]),(c=t.cubemap)==null||c.destroy(),t.cubemap=this.device.createTexture({label:"Environment Cubemap",size:[e,e,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING,mipLevelCount:Math.floor(Math.log2(e))+1,dimension:"2d"}),t.cubemapView=t.cubemap.createView({dimension:"cube"});const s=32;(u=t.irradianceMap)==null||u.destroy(),t.irradianceMap=this.device.createTexture({label:"Irradiance Map",size:[s,s,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING,dimension:"2d"}),t.irradianceMapView=t.irradianceMap.createView({dimension:"cube"}),(h=t.prefilteredMap)==null||h.destroy(),t.prefilteredMap=this.device.createTexture({label:"Prefiltered Map",size:[e,e,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING,mipLevelCount:i,dimension:"2d"}),t.prefilteredMapView=t.prefilteredMap.createView({dimension:"cube"});const n=this.device.createCommandEncoder({label:"Environment Processing"});this.convertEquirectToCubemap(n,t.equirectTexture,t.cubemap,e),this.generateCubemapMipmaps(n,t.cubemap,e),this.generateIrradianceMap(n,t.cubemap,t.irradianceMap,s),this.generatePrefilteredMap(n,t.cubemap,t.prefilteredMap,e,i),this.device.queue.submit([n.finish()]),t.needsUpdate=!1,this.environmentBindGroupCache.delete(t.id)}convertEquirectToCubemap(t,e,i,a){const r=e.createView(),s=i.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1}),n=this.device.createSampler({minFilter:"linear",magFilter:"linear"}),o=this.device.createBindGroup({layout:this.equirectBindGroupLayout,entries:[{binding:0,resource:r},{binding:1,resource:n},{binding:2,resource:s}]}),c=t.beginComputePass();c.setPipeline(this.equirectToCubemapPipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(a/8),6),c.end()}generateCubemapMipmaps(t,e,i){const a=Math.floor(Math.log2(i))+1,s=this.device.createShaderModule({code:`
|
|
603
|
+
@group(0) @binding(0) var srcTexture: texture_2d_array<f32>;
|
|
604
|
+
@group(0) @binding(1) var dstTexture: texture_storage_2d_array<rgba16float, write>;
|
|
605
|
+
|
|
606
|
+
@compute @workgroup_size(8, 8, 1)
|
|
607
|
+
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
608
|
+
let dstSize = textureDimensions(dstTexture);
|
|
609
|
+
if (globalId.x >= dstSize.x || globalId.y >= dstSize.y) {
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
let srcCoord = globalId.xy * 2u;
|
|
614
|
+
let layer = globalId.z;
|
|
615
|
+
|
|
616
|
+
let s00 = textureLoad(srcTexture, srcCoord + vec2<u32>(0u, 0u), layer, 0);
|
|
617
|
+
let s10 = textureLoad(srcTexture, srcCoord + vec2<u32>(1u, 0u), layer, 0);
|
|
618
|
+
let s01 = textureLoad(srcTexture, srcCoord + vec2<u32>(0u, 1u), layer, 0);
|
|
619
|
+
let s11 = textureLoad(srcTexture, srcCoord + vec2<u32>(1u, 1u), layer, 0);
|
|
620
|
+
|
|
621
|
+
let avg = (s00 + s10 + s01 + s11) * 0.25;
|
|
622
|
+
textureStore(dstTexture, globalId.xy, layer, avg);
|
|
623
|
+
}
|
|
624
|
+
`}),n=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"2d-array"}}]}),o=this.device.createComputePipeline({layout:this.device.createPipelineLayout({bindGroupLayouts:[n]}),compute:{module:s,entryPoint:"main"}});let c=i,u=i;for(let h=1;h<a;h++){const p=Math.max(1,c>>1),d=Math.max(1,u>>1),f=e.createView({dimension:"2d-array",baseMipLevel:h-1,mipLevelCount:1}),m=e.createView({dimension:"2d-array",baseMipLevel:h,mipLevelCount:1}),x=this.device.createBindGroup({layout:n,entries:[{binding:0,resource:f},{binding:1,resource:m}]}),g=t.beginComputePass();g.setPipeline(o),g.setBindGroup(0,x),g.dispatchWorkgroups(Math.ceil(p/8),Math.ceil(d/8),6),g.end(),c=p,u=d}}generateIrradianceMap(t,e,i,a){const r=e.createView({dimension:"cube"}),s=i.createView({dimension:"2d-array"}),n=this.device.createBindGroup({layout:this.irradianceBindGroupLayout,entries:[{binding:0,resource:r},{binding:1,resource:this.cubemapSampler},{binding:2,resource:s}]}),o=t.beginComputePass();o.setPipeline(this.irradiancePipeline),o.setBindGroup(0,n),o.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(a/8),6),o.end()}generatePrefilteredMap(t,e,i,a,r){const s=e.createView({dimension:"cube"});for(let n=0;n<r;n++){const o=Math.max(1,a>>n),c=n/(r-1),u=i.createView({dimension:"2d-array",baseMipLevel:n,mipLevelCount:1}),h=this.device.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.device.queue.writeBuffer(h,0,new Float32Array([c,a]));const p=this.device.createBindGroup({layout:this.prefilterBindGroupLayout,entries:[{binding:0,resource:s},{binding:1,resource:this.cubemapSampler},{binding:2,resource:u},{binding:3,resource:{buffer:h}}]}),d=t.beginComputePass();d.setPipeline(this.prefilterPipeline),d.setBindGroup(0,p),d.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(o/8),6),d.end()}}getEnvironmentBindGroupLayout(){return this.environmentBindGroupLayout}getEnvironmentBindGroup(t){if(this.brdfGenerated||this.generateBRDFLUT(),!t||!t.irradianceMapView)return this.dummyEnvironmentBindGroup||(this.device.queue.writeBuffer(this.envParamsBuffer,0,new Float32Array([1,0,0,0])),this.dummyEnvironmentBindGroup=this.device.createBindGroup({layout:this.environmentBindGroupLayout,entries:[{binding:0,resource:this.dummyCubemapView},{binding:1,resource:this.dummyCubemapView},{binding:2,resource:this.brdfLUTView},{binding:3,resource:this.cubemapSampler},{binding:4,resource:this.brdfSampler},{binding:5,resource:{buffer:this.envParamsBuffer}}]})),this.dummyEnvironmentBindGroup;let e=this.environmentBindGroupCache.get(t.id);return e||(this.device.queue.writeBuffer(this.envParamsBuffer,0,new Float32Array([t.intensity,1,0,0])),e=this.device.createBindGroup({layout:this.environmentBindGroupLayout,entries:[{binding:0,resource:t.irradianceMapView},{binding:1,resource:t.prefilteredMapView},{binding:2,resource:this.brdfLUTView},{binding:3,resource:this.cubemapSampler},{binding:4,resource:this.brdfSampler},{binding:5,resource:{buffer:this.envParamsBuffer}}]}),this.environmentBindGroupCache.set(t.id,e)),e}getSkyboxResources(t){return{cubemapView:(t==null?void 0:t.cubemapView)??this.dummyCubemapView,sampler:this.cubemapSampler,intensity:(t==null?void 0:t.intensity)??1}}dispose(){var t,e;(t=this.brdfLUT)==null||t.destroy(),(e=this.envParamsBuffer)==null||e.destroy(),this.environmentBindGroupCache.clear()}}const Be={Basic:0,PCF:1,PCFSoft:2};class Xe{constructor(t,e={}){l(this,"canvas");l(this,"device");l(this,"context");l(this,"presentationFormat");l(this,"pixelRatio",1);l(this,"debug",!1);l(this,"isInitialized",!1);l(this,"initializationPromise");l(this,"lightingManager");l(this,"batchManager");l(this,"textureManager");l(this,"environmentManager");l(this,"mainPhase");l(this,"shadowPhase");l(this,"depthPrePhase");l(this,"skyboxPhase");l(this,"cullingPhase");l(this,"depthTexture");l(this,"depthTextureView");l(this,"msaaTexture");l(this,"msaaTextureView");l(this,"dummyShadowMap");l(this,"dummyShadowSampler");l(this,"shadowType",Be.PCF);l(this,"shadowsEnabled",!0);l(this,"sampleCount",1);l(this,"lastBackgroundType",null);l(this,"lastClearColor",null);l(this,"debugInfo",{render:{calls:0,triangles:0},memory:{geometries:0,programs:0}});this.canvas=t,this.sampleCount=e.antialias?4:1,e.shadowType!==void 0&&(this.shadowType=e.shadowType),e.shadows!==void 0&&(this.shadowsEnabled=e.shadows),this.resize(),this.initializationPromise=this.init()}async init(){if(!navigator.gpu){console.error("WebGPU not supported on this browser.");return}const t=await navigator.gpu.requestAdapter();if(!t){console.error("Failed to get GPU adapter.");return}if(this.device=await t.requestDevice(),this.context=this.canvas.getContext("webgpu"),!this.context){console.error("Failed to get WebGPU context.");return}this.presentationFormat=navigator.gpu.getPreferredCanvasFormat(),this.context.configure({device:this.device,format:this.presentationFormat,alphaMode:"premultiplied"}),this.createFrameResources();const e=this.device.createTexture({size:[1,1],format:"depth32float",usage:GPUTextureUsage.TEXTURE_BINDING});this.dummyShadowMap=e.createView(),this.dummyShadowSampler=this.device.createSampler({compare:"less",minFilter:"linear",magFilter:"linear"}),this.lightingManager=new Ge(this.device,this.dummyShadowMap,this.dummyShadowSampler),this.batchManager=new Ve(this.device),this.textureManager=new _e(this.device),this.environmentManager=new ke(this.device),this.cullingPhase=new Fe(this.device),this.cullingPhase.setBatchManager(this.batchManager),this.shadowPhase=new Ae(this.device,this.lightingManager,this.batchManager),this.mainPhase=new Me(this.device,this.lightingManager,this.batchManager,this.textureManager,this.context,this.depthTextureView,this.msaaTextureView,this.sampleCount),this.mainPhase.setEnvironmentManager(this.environmentManager),this.skyboxPhase=new Ee(this.device,this.environmentManager,this.presentationFormat,this.sampleCount),this.depthPrePhase=new ze(this.device,this.batchManager,this.sampleCount),this.depthPrePhase.setDepthTextureView(this.depthTextureView),console.log("GFXLite Renderer Initialized"),this.isInitialized=!0}getPixelRatio(){return this.pixelRatio}setPixelRatio(t){this.pixelRatio=t}resize(){if(!this.canvas)return;const t=this.canvas.clientWidth,e=this.canvas.clientHeight;this.canvas.width=t*this.pixelRatio,this.canvas.height=e*this.pixelRatio,this.device&&(this.depthTexture&&this.depthTexture.destroy(),this.msaaTexture&&this.msaaTexture.destroy(),this.createFrameResources(),this.mainPhase&&(this.mainPhase=new Me(this.device,this.lightingManager,this.batchManager,this.textureManager,this.context,this.depthTextureView,this.msaaTextureView,this.sampleCount),this.mainPhase.setEnvironmentManager(this.environmentManager)),this.depthPrePhase&&this.depthPrePhase.setDepthTextureView(this.depthTextureView))}createFrameResources(){this.msaaTexture=this.device.createTexture({size:[this.canvas.width,this.canvas.height],format:this.presentationFormat,usage:GPUTextureUsage.RENDER_ATTACHMENT,sampleCount:this.sampleCount}),this.msaaTextureView=this.msaaTexture.createView(),this.depthTexture=this.device.createTexture({size:[this.canvas.width,this.canvas.height],format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT,sampleCount:this.sampleCount}),this.depthTextureView=this.depthTexture.createView()}async render(t,e){var u;this.isInitialized||await this.initializationPromise,this.debug&&(this.debugInfo.render.calls=0,this.debugInfo.render.triangles=0),t.updateWorldMatrix(),e.updateWorldMatrix();const i=this.lightingManager.collectLights(t);this.lightingManager.updateLightingBuffer(t,i,this.shadowType,this.shadowsEnabled);const a=this.shadowsEnabled?i.filter(h=>h instanceof j&&h.castShadow):[];this.shadowPhase.setEnabled(this.shadowsEnabled),this.shadowPhase.setLights(i),this.shadowPhase.prepare(t,e),(u=t.environment)!=null&&u.needsUpdate&&this.environmentManager.processEnvironment(t.environment),this.depthPrePhase.prepare(t,e),this.skyboxPhase.setEnvironment(t.environment),this.skyboxPhase.prepare(t,e),this.mainPhase.setEnvironment(t.environment),this.mainPhase.prepare(t,e);const r=this.batchManager.getBatches();this.batchManager.updateInstanceBuffer(r),this.batchManager.updateCameraUniforms(e,a);const s=this.device.createCommandEncoder();this.cullingPhase.execute(s),this.shadowPhase.execute(s),this.depthPrePhase.execute(s);const n=this.sampleCount>1?this.msaaTextureView:this.context.getCurrentTexture().createView(),o=t.background.type==="environment"&&t.environment!==null;o&&(this.skyboxPhase.setRenderTargets(n,this.depthTextureView),this.skyboxPhase.execute(s));let c=!1;if(t.background.type!==this.lastBackgroundType)c=!0;else if(t.background.type==="color"){const h=t.background.color;(!this.lastClearColor||this.lastClearColor.r!==h.x||this.lastClearColor.g!==h.y||this.lastClearColor.b!==h.z)&&(c=!0)}if(c){if(t.background.type==="color"){const h=t.background.color;this.mainPhase.setClearColor(h.x,h.y,h.z,1),this.lastClearColor={r:h.x,g:h.y,b:h.z}}else t.background.type==="none"?(this.mainPhase.setClearColor(0,0,0,0),this.lastClearColor=null):(this.mainPhase.setClearColor(.1,.1,.1,1),this.lastClearColor=null);this.lastBackgroundType=t.background.type}this.mainPhase.setSkyboxRendered(o),this.mainPhase.execute(s),this.device.queue.submit([s.finish()]),this.debug&&(this.debugInfo.render.calls=this.mainPhase.debugInfo.calls,this.debugInfo.render.triangles=this.mainPhase.debugInfo.triangles)}dispose(){var t,e,i,a,r,s,n,o,c,u,h,p;(t=this.lightingManager)==null||t.dispose(),(e=this.batchManager)==null||e.dispose(),(i=this.textureManager)==null||i.dispose(),(a=this.environmentManager)==null||a.dispose(),(s=(r=this.shadowPhase)==null?void 0:r.dispose)==null||s.call(r),(o=(n=this.depthPrePhase)==null?void 0:n.dispose)==null||o.call(n),(u=(c=this.skyboxPhase)==null?void 0:c.dispose)==null||u.call(c),(p=(h=this.mainPhase)==null?void 0:h.dispose)==null||p.call(h),this.depthTexture&&this.depthTexture.destroy(),this.msaaTexture&&this.msaaTexture.destroy()}}class qe extends N{constructor(){super(...arguments);l(this,"ambientLight",new b(.1,.1,.1));l(this,"environment",null);l(this,"background",{type:"none"})}}class He extends me{constructor(e=50,i=1,a=.1,r=2e3){super();l(this,"fov");l(this,"aspect");l(this,"near");l(this,"far");this.fov=e,this.aspect=i,this.near=a,this.far=r,this.updateProjectionMatrix()}updateProjectionMatrix(){this.projectionMatrix.perspective(this.fov*Math.PI/180,this.aspect,this.near,this.far),super.updateProjectionMatrix()}}class je extends W{constructor({color:e=new b(1,1,1),opacity:i=1,transparent:a,map:r}={}){super();l(this,"materialType",E.Basic);l(this,"needsLighting",!1);l(this,"needsNormals",!1);l(this,"map",null);this.uniforms.color=e,this.map=r??null,this.opacity=i,this.transparent=a??i<1,this.transparent&&(this.blendMode=z.AlphaBlend,this.depthWrite=!1)}hasTextures(){return!!this.map}getUniformBufferData(){const e=this.uniforms.color;return new Float32Array([...e.toArray(),this.opacity])}getVertexShader(){return this.map?`
|
|
625
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
626
|
+
|
|
627
|
+
struct CameraData {
|
|
628
|
+
viewProjection: mat4x4<f32>,
|
|
629
|
+
frustum: array<vec4<f32>, 6>,
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
struct CameraUniforms {
|
|
633
|
+
mainViewProjection: mat4x4<f32>,
|
|
634
|
+
cameraPosition: vec3<f32>,
|
|
635
|
+
activeLightCount: u32,
|
|
636
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
struct InstanceData {
|
|
640
|
+
modelMatrix: mat4x4<f32>,
|
|
641
|
+
normalMatrix: mat4x4<f32>,
|
|
642
|
+
flags: vec4<f32>,
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
struct CulledInstances {
|
|
646
|
+
indices: array<u32>,
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
650
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
651
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
652
|
+
|
|
653
|
+
struct VertexOutput {
|
|
654
|
+
@builtin(position) @invariant position: vec4<f32>,
|
|
655
|
+
@location(0) vUV: vec2<f32>,
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
@vertex
|
|
659
|
+
fn main(
|
|
660
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
661
|
+
@location(0) position: vec3<f32>,
|
|
662
|
+
@location(1) uv: vec2<f32>
|
|
663
|
+
) -> VertexOutput {
|
|
664
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
665
|
+
let worldPos = instances[actualIndex].modelMatrix * vec4<f32>(position, 1.0);
|
|
666
|
+
|
|
667
|
+
var output: VertexOutput;
|
|
668
|
+
output.position = cameraUniforms.mainViewProjection * worldPos;
|
|
669
|
+
output.vUV = uv;
|
|
670
|
+
return output;
|
|
671
|
+
}
|
|
672
|
+
`:`
|
|
673
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
674
|
+
|
|
675
|
+
struct CameraData {
|
|
676
|
+
viewProjection: mat4x4<f32>,
|
|
677
|
+
frustum: array<vec4<f32>, 6>,
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
struct CameraUniforms {
|
|
681
|
+
mainViewProjection: mat4x4<f32>,
|
|
682
|
+
cameraPosition: vec3<f32>,
|
|
683
|
+
activeLightCount: u32,
|
|
684
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
struct InstanceData {
|
|
688
|
+
modelMatrix: mat4x4<f32>,
|
|
689
|
+
normalMatrix: mat4x4<f32>,
|
|
690
|
+
flags: vec4<f32>,
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
struct CulledInstances {
|
|
694
|
+
indices: array<u32>,
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
698
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
699
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
700
|
+
|
|
701
|
+
@vertex
|
|
702
|
+
fn main(
|
|
703
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
704
|
+
@location(0) position: vec3<f32>
|
|
705
|
+
) -> @invariant @builtin(position) vec4<f32> {
|
|
706
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
707
|
+
let worldPos = instances[actualIndex].modelMatrix * vec4<f32>(position, 1.0);
|
|
708
|
+
return cameraUniforms.mainViewProjection * worldPos;
|
|
709
|
+
}
|
|
710
|
+
`}getFragmentShader(){return this.map?`
|
|
711
|
+
struct MaterialUniforms {
|
|
712
|
+
color: vec3<f32>,
|
|
713
|
+
opacity: f32,
|
|
714
|
+
}
|
|
715
|
+
@group(1) @binding(0) var<uniform> material: MaterialUniforms;
|
|
716
|
+
|
|
717
|
+
@group(2) @binding(0) var map: texture_2d<f32>;
|
|
718
|
+
@group(2) @binding(1) var mapSampler: sampler;
|
|
719
|
+
|
|
720
|
+
@fragment
|
|
721
|
+
fn main(@location(0) vUV: vec2<f32>) -> @location(0) vec4<f32> {
|
|
722
|
+
let texColor = textureSample(map, mapSampler, vUV);
|
|
723
|
+
let color = material.color * texColor.rgb;
|
|
724
|
+
return vec4<f32>(color, texColor.a * material.opacity);
|
|
725
|
+
}
|
|
726
|
+
`:`
|
|
727
|
+
struct MaterialUniforms {
|
|
728
|
+
color: vec3<f32>,
|
|
729
|
+
opacity: f32,
|
|
730
|
+
}
|
|
731
|
+
@group(1) @binding(0) var<uniform> material: MaterialUniforms;
|
|
732
|
+
|
|
733
|
+
@fragment
|
|
734
|
+
fn main() -> @location(0) vec4<f32> {
|
|
735
|
+
return vec4<f32>(material.color, material.opacity);
|
|
736
|
+
}
|
|
737
|
+
`}}let Ye=0;class R{constructor(t,e,i,a,r){l(this,"id",Ye++);l(this,"vertices");l(this,"normals",null);l(this,"uvs",null);l(this,"tangents",null);l(this,"indices",null);l(this,"indexCount");l(this,"boundingBox",null);l(this,"version",0);this.vertices=t,this.normals=i||null,this.uvs=a||null,this.tangents=r||null,e?(this.indices=e,this.indexCount=e.length):this.indexCount=t.length/3,this.computeBoundingBox()}computeBoundingBox(){if(!this.vertices||this.vertices.length===0){this.boundingBox=null;return}this.boundingBox=new k,this.boundingBox.setFromBufferAttribute(this.vertices)}invalidate(){this.computeBoundingBox(),this.version++}setBuffers(t,e,i,a){this.vertices=t,this.indices=e,this.normals=i,this.uvs=a,this.indexCount=e.length}}class Z extends R{constructor({width:e=1,height:i=1,depth:a=1}={}){const{vertices:r,indices:s,normals:n,uvs:o}=Z.build(e,i,a);super(r,s,n,o);l(this,"width");l(this,"height");l(this,"depth");this.width=e,this.height=i,this.depth=a}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=Z.build(this.width,this.height,this.depth);this.setBuffers(e,i,a,r),super.invalidate()}static build(e,i,a){const r=e/2,s=i/2,n=a/2,o=24,c=36,u=new Float32Array(o*3),h=new Float32Array(o*3),p=new Float32Array(o*2),d=new Uint32Array(c);let f=0,m=0,x=0,g=0;const y=(v,S,P,T,B)=>{u.set(v,f),u.set(S,f+3),u.set(P,f+6),u.set(T,f+9),f+=12;for(let G=0;G<4;G++)h.set(B,(g+G)*3);p.set([0,0,1,0,1,1,0,1],m),m+=8,d.set([g,g+2,g+1,g,g+3,g+2],x),x+=6,g+=4};return y([-r,-s,-n],[r,-s,-n],[r,s,-n],[-r,s,-n],[0,0,-1]),y([r,-s,n],[-r,-s,n],[-r,s,n],[r,s,n],[0,0,1]),y([r,-s,-n],[r,-s,n],[r,s,n],[r,s,-n],[1,0,0]),y([-r,-s,n],[-r,-s,-n],[-r,s,-n],[-r,s,n],[-1,0,0]),y([-r,s,-n],[r,s,-n],[r,s,n],[-r,s,n],[0,1,0]),y([-r,-s,n],[r,-s,n],[r,-s,-n],[-r,-s,-n],[0,-1,0]),{vertices:u,indices:d,normals:h,uvs:p}}}class K extends R{constructor({radius:e=1,widthSegments:i=32,heightSegments:a=16}={}){const{vertices:r,indices:s,normals:n,uvs:o}=K.build(e,i,a);super(new Float32Array(r),new Uint32Array(s),new Float32Array(n),new Float32Array(o));l(this,"radius");l(this,"widthSegments");l(this,"heightSegments");this.radius=e,this.widthSegments=i,this.heightSegments=a}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=K.build(this.radius,this.widthSegments,this.heightSegments);this.setBuffers(new Float32Array(e),new Uint32Array(i),new Float32Array(a),new Float32Array(r)),super.invalidate()}static build(e,i,a){const r=[],s=[],n=[];for(let c=0;c<=a;c++){const u=c/a,h=u*Math.PI;for(let p=0;p<=i;p++){const d=p/i,f=d*Math.PI*2,m=-e*Math.cos(f)*Math.sin(h),x=e*Math.cos(h),g=e*Math.sin(f)*Math.sin(h);r.push(m,x,g),s.push(d,u)}}for(let c=0;c<a;c++)for(let u=0;u<i;u++){const h=c*(i+1)+u,p=h+i+1,d=h+1,f=p+1;n.push(h,p,d),n.push(p,f,d)}const o=[];for(let c=0;c<r.length;c+=3){const u=r[c],h=r[c+1],p=r[c+2],d=new b(u,h,p).normalize();o.push(d.x,d.y,d.z)}return{vertices:r,indices:n,normals:o,uvs:s}}}class Q extends R{constructor({width:e=1,height:i=1,widthSegments:a=1,heightSegments:r=1}={}){const{vertices:s,indices:n,normals:o,uvs:c}=Q.build(e,i,a,r);super(new Float32Array(s),new Uint32Array(n),new Float32Array(o),new Float32Array(c));l(this,"width");l(this,"height");l(this,"widthSegments");l(this,"heightSegments");this.width=e,this.height=i,this.widthSegments=a,this.heightSegments=r}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=Q.build(this.width,this.height,this.widthSegments,this.heightSegments);this.setBuffers(new Float32Array(e),new Uint32Array(i),new Float32Array(a),new Float32Array(r)),super.invalidate()}static build(e,i,a,r){const s=[],n=[],o=[],c=[],u=e/2,h=i/2,p=a,d=r,f=e/p,m=i/d;for(let x=0;x<=d;x++){const g=x*m-h,y=x/d;for(let v=0;v<=p;v++){const S=v*f-u,P=v/p;s.push(S,0,g),n.push(0,1,0),o.push(P,y)}}for(let x=0;x<d;x++)for(let g=0;g<p;g++){const y=g+(p+1)*x,v=g+(p+1)*(x+1),S=g+1+(p+1)*(x+1),P=g+1+(p+1)*x;c.push(y,v,P),c.push(v,S,P)}return{vertices:s,indices:c,normals:n,uvs:o}}}class J extends R{constructor({radiusTop:e=1,radiusBottom:i=1,height:a=1,radialSegments:r=32,heightSegments:s=1,openEnded:n=!1}={}){const{vertices:o,indices:c,normals:u,uvs:h}=J.build(e,i,a,r,s,n);super(new Float32Array(o),new Uint32Array(c),new Float32Array(u),new Float32Array(h));l(this,"radiusTop");l(this,"radiusBottom");l(this,"height");l(this,"radialSegments");l(this,"heightSegments");l(this,"openEnded");this.radiusTop=e,this.radiusBottom=i,this.height=a,this.radialSegments=r,this.heightSegments=s,this.openEnded=n}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=J.build(this.radiusTop,this.radiusBottom,this.height,this.radialSegments,this.heightSegments,this.openEnded);this.setBuffers(new Float32Array(e),new Uint32Array(i),new Float32Array(a),new Float32Array(r)),super.invalidate()}static build(e,i,a,r,s,n){const o=[],c=[],u=[],h=[],p=a/2;for(let d=0;d<=s;d++){const f=d/s,m=f*a-p,x=(1-f)*i+f*e;for(let g=0;g<=r;g++){const y=g/r,v=y*Math.PI*2,S=x*Math.cos(v),P=m,T=x*Math.sin(v);o.push(S,P,T);const B=Math.cos(v),G=Math.sin(v);c.push(B,0,G),u.push(y,f)}}for(let d=0;d<s;d++)for(let f=0;f<r;f++){const m=d*(r+1)+f,x=m+r+1,g=m+1,y=x+1;h.push(m,x,g),h.push(x,y,g)}if(!n){const d=o.length/3;o.push(0,p,0),c.push(0,1,0),u.push(.5,.5);for(let m=0;m<=r;m++){const g=m/r*Math.PI*2,y=e*Math.cos(g),v=e*Math.sin(g);o.push(y,p,v),c.push(0,1,0),u.push(Math.cos(g)*.5+.5,Math.sin(g)*.5+.5)}for(let m=0;m<r;m++){const x=d,g=d+1+m,y=d+1+m+1;h.push(x,y,g)}const f=o.length/3;o.push(0,-p,0),c.push(0,-1,0),u.push(.5,.5);for(let m=0;m<=r;m++){const g=m/r*Math.PI*2,y=i*Math.cos(g),v=i*Math.sin(g);o.push(y,-p,v),c.push(0,-1,0),u.push(Math.cos(g)*.5+.5,Math.sin(g)*.5+.5)}for(let m=0;m<r;m++){const x=f,g=f+1+m+1,y=f+1+m;h.push(x,y,g)}}return{vertices:o,indices:h,normals:c,uvs:u}}}class ee extends R{constructor({radius:e=1,tube:i=.4,radialSegments:a=16,tubularSegments:r=32}={}){const{vertices:s,indices:n,normals:o,uvs:c}=ee.build(e,i,a,r);super(new Float32Array(s),new Uint32Array(n),new Float32Array(o),new Float32Array(c));l(this,"radius");l(this,"tube");l(this,"radialSegments");l(this,"tubularSegments");this.radius=e,this.tube=i,this.radialSegments=a,this.tubularSegments=r}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=ee.build(this.radius,this.tube,this.radialSegments,this.tubularSegments);this.setBuffers(new Float32Array(e),new Uint32Array(i),new Float32Array(a),new Float32Array(r)),super.invalidate()}static build(e,i,a,r){const s=[],n=[],o=[],c=[];for(let u=0;u<=a;u++){const h=u/a;for(let p=0;p<=r;p++){const d=p/r,f=d*Math.PI*2,m=h*Math.PI*2,x=(e+i*Math.cos(m))*Math.cos(f),g=(e+i*Math.cos(m))*Math.sin(f),y=i*Math.sin(m);s.push(x,g,y);const v=e*Math.cos(f),S=e*Math.sin(f),P=0,T=x-v,B=g-S,G=y-P,I=Math.sqrt(T*T+B*B+G*G);n.push(T/I,B/I,G/I),o.push(d,h)}}for(let u=0;u<a;u++)for(let h=0;h<r;h++){const p=(r+1)*u+h,d=(r+1)*(u+1)+h,f=(r+1)*(u+1)+h+1,m=(r+1)*u+h+1;c.push(p,m,d),c.push(m,f,d)}return{vertices:s,indices:c,normals:n,uvs:o}}}class te extends R{constructor({radius:e=1,segments:i=32}={}){const{vertices:a,indices:r,normals:s,uvs:n}=te.build(e,i);super(new Float32Array(a),new Uint32Array(r),new Float32Array(s),new Float32Array(n));l(this,"radius");l(this,"segments");this.radius=e,this.segments=i}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=te.build(this.radius,this.segments);this.setBuffers(new Float32Array(e),new Uint32Array(i),new Float32Array(a),new Float32Array(r)),super.invalidate()}static build(e,i){const a=[],r=[],s=[],n=[];a.push(0,0,0),r.push(0,0,1),s.push(.5,.5);for(let o=0;o<=i;o++){const c=o/i*Math.PI*2,u=e*Math.cos(c),h=e*Math.sin(c);a.push(u,h,0),r.push(0,0,1),s.push(Math.cos(c)*.5+.5,Math.sin(c)*.5+.5)}for(let o=1;o<=i;o++)n.push(0,o,o+1);return{vertices:a,indices:n,normals:r,uvs:s}}}class ie extends R{constructor({radius:e=1,height:i=1,radialSegments:a=32,heightSegments:r=1,openEnded:s=!1}={}){const{vertices:n,indices:o,normals:c,uvs:u}=ie.build(e,i,a,r,s);super(new Float32Array(n),new Uint32Array(o),new Float32Array(c),new Float32Array(u));l(this,"radius");l(this,"height");l(this,"radialSegments");l(this,"heightSegments");l(this,"openEnded");this.radius=e,this.height=i,this.radialSegments=a,this.heightSegments=r,this.openEnded=s}invalidate(){const{vertices:e,indices:i,normals:a,uvs:r}=ie.build(this.radius,this.height,this.radialSegments,this.heightSegments,this.openEnded);this.setBuffers(new Float32Array(e),new Uint32Array(i),new Float32Array(a),new Float32Array(r)),super.invalidate()}static build(e,i,a,r,s){const n=[],o=[],c=[],u=[],h=i/2;for(let p=0;p<=r;p++){const d=p/r,f=h-d*i,m=d*e;for(let x=0;x<=a;x++){const g=x/a,y=g*Math.PI*2,v=m*Math.cos(y),S=f,P=m*Math.sin(y);n.push(v,S,P);const T=Math.cos(y),B=Math.sin(y),G=e/i,I=Math.sqrt(T*T+G*G+B*B);o.push(T/I,G/I,B/I),c.push(g,d)}}for(let p=0;p<r;p++)for(let d=0;d<a;d++){const f=p*(a+1)+d,m=f+a+1,x=f+1,g=m+1;u.push(f,x,m),u.push(m,x,g)}if(!s){const p=n.length/3;n.push(0,-h,0),o.push(0,-1,0),c.push(.5,.5);for(let d=0;d<=a;d++){const f=d/a*Math.PI*2,m=e*Math.cos(f),x=e*Math.sin(f);n.push(m,-h,x),o.push(0,-1,0),c.push(Math.cos(f)*.5+.5,Math.sin(f)*.5+.5)}for(let d=0;d<a;d++){const f=p,m=p+1+d+1,x=p+1+d;u.push(f,x,m)}}return{vertices:n,indices:u,normals:o,uvs:c}}}class $e extends W{constructor({color:e=new b(1,1,1),specular:i=new b(1,1,1),shininess:a=30,opacity:r=1,transparent:s,map:n}={}){super();l(this,"materialType",E.Phong);l(this,"needsLighting",!0);l(this,"needsNormals",!0);l(this,"map",null);this.uniforms.color=e,this.uniforms.specular=i,this.uniforms.shininess=a,this.map=n??null,this.opacity=r,this.transparent=s??r<1,this.transparent&&(this.blendMode=z.AlphaBlend,this.depthWrite=!1)}hasTextures(){return!!this.map}getUniformBufferData(){const e=this.uniforms.color,i=this.uniforms.specular,a=this.uniforms.shininess;return new Float32Array([...e.toArray(),this.opacity,...i.toArray(),a,this.map?1:0,0,0,0])}getVertexShader(){const e=!!this.map;return`
|
|
738
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
739
|
+
|
|
740
|
+
struct CameraData {
|
|
741
|
+
viewProjection: mat4x4<f32>,
|
|
742
|
+
frustum: array<vec4<f32>, 6>,
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
struct CameraUniforms {
|
|
746
|
+
mainViewProjection: mat4x4<f32>,
|
|
747
|
+
cameraPosition: vec3<f32>,
|
|
748
|
+
activeLightCount: u32,
|
|
749
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
struct InstanceData {
|
|
753
|
+
modelMatrix: mat4x4<f32>,
|
|
754
|
+
normalMatrix: mat4x4<f32>,
|
|
755
|
+
flags: vec4<f32>, // x: receiveShadow, y: castShadow
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
struct CulledInstances {
|
|
759
|
+
indices: array<u32>,
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
763
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
764
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
765
|
+
|
|
766
|
+
struct VertexOutput {
|
|
767
|
+
@builtin(position) @invariant position: vec4<f32>,
|
|
768
|
+
@location(0) vPosition: vec3<f32>,
|
|
769
|
+
@location(1) vNormal: vec3<f32>,
|
|
770
|
+
${e?"@location(2) vUV: vec2<f32>,":""}
|
|
771
|
+
@location(${e?3:2}) vCameraPos: vec3<f32>,
|
|
772
|
+
@location(${e?4:3}) vReceiveShadow: f32,
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
@vertex
|
|
776
|
+
fn main(
|
|
777
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
778
|
+
@location(0) position: vec3<f32>,
|
|
779
|
+
@location(1) normal: vec3<f32>${e?`,
|
|
780
|
+
@location(2) uv: vec2<f32>`:""}
|
|
781
|
+
) -> VertexOutput {
|
|
782
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
783
|
+
let instance = instances[actualIndex];
|
|
784
|
+
|
|
785
|
+
let worldPos = instance.modelMatrix * vec4<f32>(position, 1.0);
|
|
786
|
+
|
|
787
|
+
var output: VertexOutput;
|
|
788
|
+
output.position = cameraUniforms.mainViewProjection * worldPos;
|
|
789
|
+
output.vPosition = worldPos.xyz;
|
|
790
|
+
output.vNormal = normalize((instance.normalMatrix * vec4<f32>(normal, 0.0)).xyz);
|
|
791
|
+
${e?"output.vUV = uv;":""}
|
|
792
|
+
output.vCameraPos = cameraUniforms.cameraPosition;
|
|
793
|
+
output.vReceiveShadow = instance.flags.x;
|
|
794
|
+
return output;
|
|
795
|
+
}
|
|
796
|
+
`}getFragmentShader(){const e=!!this.map;return`
|
|
797
|
+
struct MaterialUniforms {
|
|
798
|
+
color: vec3<f32>,
|
|
799
|
+
opacity: f32,
|
|
800
|
+
specular: vec3<f32>,
|
|
801
|
+
shininess: f32,
|
|
802
|
+
hasMap: f32,
|
|
803
|
+
_pad0: f32,
|
|
804
|
+
_pad1: f32,
|
|
805
|
+
_pad2: f32,
|
|
806
|
+
}
|
|
807
|
+
@group(1) @binding(0) var<uniform> material: MaterialUniforms;
|
|
808
|
+
|
|
809
|
+
struct Light {
|
|
810
|
+
direction: vec3<f32>,
|
|
811
|
+
intensity: f32,
|
|
812
|
+
color: vec3<f32>,
|
|
813
|
+
shadowLayerIndex: i32,
|
|
814
|
+
viewProj: mat4x4<f32>,
|
|
815
|
+
shadowMapSize: vec2<f32>,
|
|
816
|
+
shadowType: f32,
|
|
817
|
+
padding: f32,
|
|
818
|
+
}
|
|
819
|
+
struct LightUniforms {
|
|
820
|
+
ambientColor: vec3<f32>,
|
|
821
|
+
lightCount: u32,
|
|
822
|
+
lights: array<Light, 16>,
|
|
823
|
+
}
|
|
824
|
+
@group(2) @binding(0) var<uniform> lighting: LightUniforms;
|
|
825
|
+
@group(2) @binding(1) var shadowMap: texture_depth_2d_array;
|
|
826
|
+
@group(2) @binding(2) var shadowSampler: sampler_comparison;
|
|
827
|
+
|
|
828
|
+
${e?`
|
|
829
|
+
@group(3) @binding(0) var map: texture_2d<f32>;
|
|
830
|
+
@group(3) @binding(1) var mapSampler: sampler;
|
|
831
|
+
`:""}
|
|
832
|
+
|
|
833
|
+
@fragment
|
|
834
|
+
fn main(
|
|
835
|
+
@location(0) vPosition: vec3<f32>,
|
|
836
|
+
@location(1) vNormal: vec3<f32>,
|
|
837
|
+
${e?"@location(2) vUV: vec2<f32>,":""}
|
|
838
|
+
@location(${e?3:2}) vCameraPos: vec3<f32>,
|
|
839
|
+
@location(${e?4:3}) vReceiveShadow: f32
|
|
840
|
+
) -> @location(0) vec4<f32> {
|
|
841
|
+
let normal = normalize(vNormal);
|
|
842
|
+
let viewDir = normalize(vCameraPos - vPosition);
|
|
843
|
+
|
|
844
|
+
// Sample texture if present
|
|
845
|
+
var baseColor = material.color;
|
|
846
|
+
var alpha = material.opacity;
|
|
847
|
+
${e?`
|
|
848
|
+
if (material.hasMap > 0.5) {
|
|
849
|
+
let texColor = textureSample(map, mapSampler, vUV);
|
|
850
|
+
baseColor *= texColor.rgb;
|
|
851
|
+
alpha *= texColor.a;
|
|
852
|
+
}
|
|
853
|
+
`:""}
|
|
854
|
+
|
|
855
|
+
// Ambient
|
|
856
|
+
let ambient = lighting.ambientColor * baseColor;
|
|
857
|
+
|
|
858
|
+
// Diffuse & Specular
|
|
859
|
+
var diffuse = vec3<f32>(0.0);
|
|
860
|
+
var specular = vec3<f32>(0.0);
|
|
861
|
+
|
|
862
|
+
for (var i = 0u; i < lighting.lightCount; i++) {
|
|
863
|
+
let light = lighting.lights[i];
|
|
864
|
+
let lightDir = normalize(-light.direction);
|
|
865
|
+
|
|
866
|
+
// Shadow Calculation
|
|
867
|
+
var shadow = 1.0;
|
|
868
|
+
|
|
869
|
+
// Transform position to light space
|
|
870
|
+
let lightPos = light.viewProj * vec4<f32>(vPosition, 1.0);
|
|
871
|
+
let shadowPos = vec3<f32>(
|
|
872
|
+
lightPos.x * 0.5 + 0.5,
|
|
873
|
+
-lightPos.y * 0.5 + 0.5,
|
|
874
|
+
lightPos.z
|
|
875
|
+
);
|
|
876
|
+
|
|
877
|
+
// Sample shadow map
|
|
878
|
+
var shadowSample = 0.0;
|
|
879
|
+
let layerIndex = light.shadowLayerIndex;
|
|
880
|
+
let shadowType = light.shadowType;
|
|
881
|
+
|
|
882
|
+
if (layerIndex >= 0) {
|
|
883
|
+
if (shadowType > 1.5) {
|
|
884
|
+
// PCFSoft (5x5)
|
|
885
|
+
var shadowSum = 0.0;
|
|
886
|
+
let texelSize = vec2<f32>(1.0 / light.shadowMapSize.x, 1.0 / light.shadowMapSize.y);
|
|
887
|
+
for (var x = -2; x <= 2; x++) {
|
|
888
|
+
for (var y = -2; y <= 2; y++) {
|
|
889
|
+
let offset = vec2<f32>(f32(x), f32(y)) * texelSize;
|
|
890
|
+
shadowSum += textureSampleCompare(shadowMap, shadowSampler, shadowPos.xy + offset, layerIndex, shadowPos.z - 0.005);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
shadowSample = shadowSum / 25.0;
|
|
894
|
+
} else {
|
|
895
|
+
// PCF (Single sample, hardware filtering) or Basic
|
|
896
|
+
shadowSample = textureSampleCompare(shadowMap, shadowSampler, shadowPos.xy, layerIndex, shadowPos.z - 0.005);
|
|
897
|
+
}
|
|
898
|
+
} else {
|
|
899
|
+
// No shadow
|
|
900
|
+
shadowSample = 1.0;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
// Apply shadow only if within light frustum
|
|
904
|
+
if (shadowPos.x > 0.0 && shadowPos.x < 1.0 && shadowPos.y > 0.0 && shadowPos.y < 1.0 && shadowPos.z > 0.0 && shadowPos.z < 1.0) {
|
|
905
|
+
// Check receiveShadow flag from vertex output
|
|
906
|
+
if (vReceiveShadow > 0.5) {
|
|
907
|
+
shadow = shadowSample;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// Diffuse
|
|
912
|
+
let diff = max(dot(normal, lightDir), 0.0);
|
|
913
|
+
diffuse += diff * light.color * light.intensity * baseColor * shadow;
|
|
914
|
+
|
|
915
|
+
// Specular (Blinn-Phong)
|
|
916
|
+
if (diff > 0.0) {
|
|
917
|
+
let halfDir = normalize(lightDir + viewDir);
|
|
918
|
+
let specAngle = max(dot(normal, halfDir), 0.0);
|
|
919
|
+
let spec = pow(specAngle, material.shininess);
|
|
920
|
+
specular += spec * material.specular * light.color * light.intensity * shadow;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
return vec4<f32>(ambient + diffuse + specular, alpha);
|
|
925
|
+
}
|
|
926
|
+
`}}class We extends W{constructor({color:e=new b(1,1,1),opacity:i=1,transparent:a,map:r}={}){super();l(this,"materialType",E.Lambert);l(this,"needsLighting",!0);l(this,"needsNormals",!0);l(this,"map",null);this.uniforms.color=e,this.map=r??null,this.opacity=i,this.transparent=a??i<1,this.transparent&&(this.blendMode=z.AlphaBlend,this.depthWrite=!1)}hasTextures(){return!!this.map}getUniformBufferData(){const e=this.uniforms.color;return new Float32Array([...e.toArray(),this.opacity,this.map?1:0,0,0,0])}getVertexShader(){const e=!!this.map;return`
|
|
927
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
928
|
+
|
|
929
|
+
struct CameraData {
|
|
930
|
+
viewProjection: mat4x4<f32>,
|
|
931
|
+
frustum: array<vec4<f32>, 6>,
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
struct CameraUniforms {
|
|
935
|
+
mainViewProjection: mat4x4<f32>,
|
|
936
|
+
cameraPosition: vec3<f32>,
|
|
937
|
+
activeLightCount: u32,
|
|
938
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
struct InstanceData {
|
|
942
|
+
modelMatrix: mat4x4<f32>,
|
|
943
|
+
normalMatrix: mat4x4<f32>,
|
|
944
|
+
flags: vec4<f32>, // x: receiveShadow, y: castShadow
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
struct CulledInstances {
|
|
948
|
+
indices: array<u32>,
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
952
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
953
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
954
|
+
|
|
955
|
+
struct VertexOutput {
|
|
956
|
+
@builtin(position) @invariant position: vec4<f32>,
|
|
957
|
+
@location(0) vPosition: vec3<f32>,
|
|
958
|
+
@location(1) vNormal: vec3<f32>,
|
|
959
|
+
${e?"@location(2) vUV: vec2<f32>,":""}
|
|
960
|
+
@location(${e?3:2}) vReceiveShadow: f32,
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
@vertex
|
|
964
|
+
fn main(
|
|
965
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
966
|
+
@location(0) position: vec3<f32>,
|
|
967
|
+
@location(1) normal: vec3<f32>${e?`,
|
|
968
|
+
@location(2) uv: vec2<f32>`:""}
|
|
969
|
+
) -> VertexOutput {
|
|
970
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
971
|
+
let instance = instances[actualIndex];
|
|
972
|
+
|
|
973
|
+
let worldPos = instance.modelMatrix * vec4<f32>(position, 1.0);
|
|
974
|
+
|
|
975
|
+
var output: VertexOutput;
|
|
976
|
+
output.position = cameraUniforms.mainViewProjection * worldPos;
|
|
977
|
+
output.vPosition = worldPos.xyz;
|
|
978
|
+
output.vNormal = normalize((instance.normalMatrix * vec4<f32>(normal, 0.0)).xyz);
|
|
979
|
+
${e?"output.vUV = uv;":""}
|
|
980
|
+
output.vReceiveShadow = instance.flags.x;
|
|
981
|
+
return output;
|
|
982
|
+
}
|
|
983
|
+
`}getFragmentShader(){const e=!!this.map;return`
|
|
984
|
+
struct MaterialUniforms {
|
|
985
|
+
color: vec3<f32>,
|
|
986
|
+
opacity: f32,
|
|
987
|
+
hasMap: f32,
|
|
988
|
+
_pad0: f32,
|
|
989
|
+
_pad1: f32,
|
|
990
|
+
_pad2: f32,
|
|
991
|
+
}
|
|
992
|
+
@group(1) @binding(0) var<uniform> material: MaterialUniforms;
|
|
993
|
+
|
|
994
|
+
struct Light {
|
|
995
|
+
direction: vec3<f32>,
|
|
996
|
+
intensity: f32,
|
|
997
|
+
color: vec3<f32>,
|
|
998
|
+
shadowLayerIndex: i32,
|
|
999
|
+
viewProj: mat4x4<f32>,
|
|
1000
|
+
shadowMapSize: vec2<f32>,
|
|
1001
|
+
shadowType: f32,
|
|
1002
|
+
padding: f32,
|
|
1003
|
+
}
|
|
1004
|
+
struct LightUniforms {
|
|
1005
|
+
ambientColor: vec3<f32>,
|
|
1006
|
+
lightCount: u32,
|
|
1007
|
+
lights: array<Light, 16>,
|
|
1008
|
+
}
|
|
1009
|
+
@group(2) @binding(0) var<uniform> lighting: LightUniforms;
|
|
1010
|
+
@group(2) @binding(1) var shadowMap: texture_depth_2d_array;
|
|
1011
|
+
@group(2) @binding(2) var shadowSampler: sampler_comparison;
|
|
1012
|
+
|
|
1013
|
+
${e?`
|
|
1014
|
+
@group(3) @binding(0) var map: texture_2d<f32>;
|
|
1015
|
+
@group(3) @binding(1) var mapSampler: sampler;
|
|
1016
|
+
`:""}
|
|
1017
|
+
|
|
1018
|
+
@fragment
|
|
1019
|
+
fn main(
|
|
1020
|
+
@location(0) vPosition: vec3<f32>,
|
|
1021
|
+
@location(1) vNormal: vec3<f32>,
|
|
1022
|
+
${e?"@location(2) vUV: vec2<f32>,":""}
|
|
1023
|
+
@location(${e?3:2}) vReceiveShadow: f32
|
|
1024
|
+
) -> @location(0) vec4<f32> {
|
|
1025
|
+
let normal = normalize(vNormal);
|
|
1026
|
+
|
|
1027
|
+
// Sample texture if present
|
|
1028
|
+
var baseColor = material.color;
|
|
1029
|
+
var alpha = material.opacity;
|
|
1030
|
+
${e?`
|
|
1031
|
+
let texColor = textureSample(map, mapSampler, vUV);
|
|
1032
|
+
baseColor *= texColor.rgb;
|
|
1033
|
+
alpha *= texColor.a;
|
|
1034
|
+
`:""}
|
|
1035
|
+
|
|
1036
|
+
// Ambient
|
|
1037
|
+
let ambient = lighting.ambientColor * baseColor;
|
|
1038
|
+
|
|
1039
|
+
// Diffuse
|
|
1040
|
+
var diffuse = vec3<f32>(0.0);
|
|
1041
|
+
|
|
1042
|
+
for (var i = 0u; i < lighting.lightCount; i++) {
|
|
1043
|
+
let light = lighting.lights[i];
|
|
1044
|
+
let lightDir = normalize(-light.direction);
|
|
1045
|
+
|
|
1046
|
+
// Shadow Calculation
|
|
1047
|
+
var shadow = 1.0;
|
|
1048
|
+
|
|
1049
|
+
// Transform position to light space
|
|
1050
|
+
let lightPos = light.viewProj * vec4<f32>(vPosition, 1.0);
|
|
1051
|
+
let shadowPos = vec3<f32>(
|
|
1052
|
+
lightPos.x * 0.5 + 0.5,
|
|
1053
|
+
-lightPos.y * 0.5 + 0.5,
|
|
1054
|
+
lightPos.z
|
|
1055
|
+
);
|
|
1056
|
+
|
|
1057
|
+
// Sample shadow map
|
|
1058
|
+
var shadowSample = 0.0;
|
|
1059
|
+
let layerIndex = light.shadowLayerIndex;
|
|
1060
|
+
let shadowType = light.shadowType;
|
|
1061
|
+
|
|
1062
|
+
if (layerIndex >= 0) {
|
|
1063
|
+
if (shadowType > 1.5) {
|
|
1064
|
+
// PCFSoft (5x5)
|
|
1065
|
+
var shadowSum = 0.0;
|
|
1066
|
+
let texelSize = vec2<f32>(1.0 / light.shadowMapSize.x, 1.0 / light.shadowMapSize.y);
|
|
1067
|
+
for (var x = -2; x <= 2; x++) {
|
|
1068
|
+
for (var y = -2; y <= 2; y++) {
|
|
1069
|
+
let offset = vec2<f32>(f32(x), f32(y)) * texelSize;
|
|
1070
|
+
shadowSum += textureSampleCompare(shadowMap, shadowSampler, shadowPos.xy + offset, layerIndex, shadowPos.z - 0.005);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
shadowSample = shadowSum / 25.0;
|
|
1074
|
+
} else {
|
|
1075
|
+
// PCF (Single sample, hardware filtering) or Basic
|
|
1076
|
+
shadowSample = textureSampleCompare(shadowMap, shadowSampler, shadowPos.xy, layerIndex, shadowPos.z - 0.005);
|
|
1077
|
+
}
|
|
1078
|
+
} else {
|
|
1079
|
+
// No shadow
|
|
1080
|
+
shadowSample = 1.0;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// Apply shadow only if within light frustum
|
|
1084
|
+
if (shadowPos.x > 0.0 && shadowPos.x < 1.0 && shadowPos.y > 0.0 && shadowPos.y < 1.0 && shadowPos.z > 0.0 && shadowPos.z < 1.0) {
|
|
1085
|
+
// Check receiveShadow flag from vertex output
|
|
1086
|
+
if (vReceiveShadow > 0.5) {
|
|
1087
|
+
shadow = shadowSample;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// Diffuse
|
|
1092
|
+
let diff = max(dot(normal, lightDir), 0.0);
|
|
1093
|
+
diffuse += diff * light.color * light.intensity * baseColor * shadow;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
return vec4<f32>(ambient + diffuse, alpha);
|
|
1097
|
+
}
|
|
1098
|
+
`}}class $ extends W{constructor(e={}){super();l(this,"materialType",E.Standard);l(this,"needsLighting",!0);l(this,"needsNormals",!0);l(this,"baseColorMap",null);l(this,"normalMap",null);l(this,"metallicRoughnessMap",null);l(this,"emissiveMap",null);l(this,"aoMap",null);l(this,"envMap",null);l(this,"envMapIntensity",1);this.uniforms.baseColor=e.baseColor??new b(1,1,1),this.uniforms.metallic=e.metallic??0,this.uniforms.roughness=e.roughness??.5,this.uniforms.emissive=e.emissive??new b(0,0,0),this.uniforms.emissiveFactor=e.emissiveFactor??1,this.uniforms.normalScale=e.normalScale??1,this.uniforms.occlusionStrength=e.occlusionStrength??1,this.baseColorMap=e.baseColorMap??null,this.normalMap=e.normalMap??null,this.metallicRoughnessMap=e.metallicRoughnessMap??null,this.emissiveMap=e.emissiveMap??null,this.aoMap=e.aoMap??null,this.opacity=e.opacity??1;const i=e.transparent??!1,a=this.opacity<1||e.blendMode===z.AlphaBlend;this.transparent=i||a,this.blendMode=e.blendMode??(this.transparent?z.AlphaBlend:z.Opaque),this.alphaCutoff=e.alphaCutoff??.5,this.doubleSided=e.doubleSided??!1,this.depthWrite=!this.transparent,this.envMap=e.envMap??null,this.envMapIntensity=e.envMapIntensity??1}hasTextures(){return!!(this.baseColorMap||this.normalMap||this.metallicRoughnessMap||this.emissiveMap||this.aoMap)}getUniformBufferData(){const e=this.uniforms.baseColor,i=this.uniforms.emissive;return new Float32Array([...e.toArray(),this.opacity,...i.toArray(),this.uniforms.emissiveFactor,this.uniforms.metallic,this.uniforms.roughness,this.uniforms.normalScale,this.uniforms.occlusionStrength,this.baseColorMap?1:0,this.normalMap?1:0,this.metallicRoughnessMap?1:0,this.emissiveMap?1:0,this.aoMap?1:0,this.alphaCutoff,this.blendMode,0])}getVertexShader(){return`
|
|
1099
|
+
const MAX_CAMERAS: u32 = 5u;
|
|
1100
|
+
|
|
1101
|
+
struct CameraData {
|
|
1102
|
+
viewProjection: mat4x4<f32>,
|
|
1103
|
+
frustum: array<vec4<f32>, 6>,
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
struct CameraUniforms {
|
|
1107
|
+
mainViewProjection: mat4x4<f32>,
|
|
1108
|
+
cameraPosition: vec3<f32>,
|
|
1109
|
+
activeLightCount: u32,
|
|
1110
|
+
cameras: array<CameraData, MAX_CAMERAS>,
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
struct InstanceData {
|
|
1114
|
+
modelMatrix: mat4x4<f32>,
|
|
1115
|
+
normalMatrix: mat4x4<f32>,
|
|
1116
|
+
flags: vec4<f32>, // x: receiveShadow, y: castShadow
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
struct CulledInstances {
|
|
1120
|
+
indices: array<u32>,
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
@group(0) @binding(0) var<storage, read> instances: array<InstanceData>;
|
|
1124
|
+
@group(0) @binding(1) var<storage, read> culled: CulledInstances;
|
|
1125
|
+
@group(0) @binding(2) var<uniform> cameraUniforms: CameraUniforms;
|
|
1126
|
+
|
|
1127
|
+
struct VertexOutput {
|
|
1128
|
+
@builtin(position) @invariant position: vec4<f32>,
|
|
1129
|
+
@location(0) vPosition: vec3<f32>,
|
|
1130
|
+
@location(1) vNormal: vec3<f32>,
|
|
1131
|
+
@location(2) vUV: vec2<f32>,
|
|
1132
|
+
@location(3) vCameraPos: vec3<f32>,
|
|
1133
|
+
@location(4) vReceiveShadow: f32,
|
|
1134
|
+
@location(5) vTangent: vec4<f32>,
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
@vertex
|
|
1138
|
+
fn main(
|
|
1139
|
+
@builtin(instance_index) instanceIndex: u32,
|
|
1140
|
+
@location(0) position: vec3<f32>,
|
|
1141
|
+
@location(1) normal: vec3<f32>,
|
|
1142
|
+
@location(2) uv: vec2<f32>,
|
|
1143
|
+
@location(3) tangent: vec4<f32>
|
|
1144
|
+
) -> VertexOutput {
|
|
1145
|
+
let actualIndex = culled.indices[instanceIndex];
|
|
1146
|
+
let instance = instances[actualIndex];
|
|
1147
|
+
|
|
1148
|
+
let worldPos = instance.modelMatrix * vec4<f32>(position, 1.0);
|
|
1149
|
+
|
|
1150
|
+
var output: VertexOutput;
|
|
1151
|
+
output.position = cameraUniforms.mainViewProjection * worldPos;
|
|
1152
|
+
output.vPosition = worldPos.xyz;
|
|
1153
|
+
output.vNormal = normalize((instance.normalMatrix * vec4<f32>(normal, 0.0)).xyz);
|
|
1154
|
+
output.vUV = uv;
|
|
1155
|
+
output.vCameraPos = cameraUniforms.cameraPosition;
|
|
1156
|
+
output.vReceiveShadow = instance.flags.x;
|
|
1157
|
+
// Transform tangent to world space (using model matrix for direction)
|
|
1158
|
+
output.vTangent = vec4<f32>(normalize((instance.modelMatrix * vec4<f32>(tangent.xyz, 0.0)).xyz), tangent.w);
|
|
1159
|
+
return output;
|
|
1160
|
+
}
|
|
1161
|
+
`}getFragmentShader(){return`
|
|
1162
|
+
const PI: f32 = 3.14159265359;
|
|
1163
|
+
|
|
1164
|
+
struct MaterialUniforms {
|
|
1165
|
+
baseColor: vec4<f32>, // RGB + alpha
|
|
1166
|
+
emissive: vec4<f32>, // RGB + emissiveFactor
|
|
1167
|
+
props: vec4<f32>, // metallic, roughness, normalScale, occlusionStrength
|
|
1168
|
+
flags: vec4<f32>, // hasBaseColorMap, hasNormalMap, hasMetallicRoughnessMap, hasEmissiveMap
|
|
1169
|
+
flags2: vec4<f32>, // hasAOMap, alphaCutoff, blendMode, pad
|
|
1170
|
+
}
|
|
1171
|
+
@group(1) @binding(0) var<uniform> material: MaterialUniforms;
|
|
1172
|
+
|
|
1173
|
+
struct Light {
|
|
1174
|
+
direction: vec3<f32>,
|
|
1175
|
+
intensity: f32,
|
|
1176
|
+
color: vec3<f32>,
|
|
1177
|
+
shadowLayerIndex: i32,
|
|
1178
|
+
viewProj: mat4x4<f32>,
|
|
1179
|
+
shadowMapSize: vec2<f32>,
|
|
1180
|
+
shadowType: f32,
|
|
1181
|
+
padding: f32,
|
|
1182
|
+
}
|
|
1183
|
+
struct LightUniforms {
|
|
1184
|
+
ambientColor: vec3<f32>,
|
|
1185
|
+
lightCount: u32,
|
|
1186
|
+
lights: array<Light, 16>,
|
|
1187
|
+
}
|
|
1188
|
+
@group(2) @binding(0) var<uniform> lighting: LightUniforms;
|
|
1189
|
+
@group(2) @binding(1) var shadowMap: texture_depth_2d_array;
|
|
1190
|
+
@group(2) @binding(2) var shadowSampler: sampler_comparison;
|
|
1191
|
+
|
|
1192
|
+
// Textures (group 3)
|
|
1193
|
+
@group(3) @binding(0) var baseColorMap: texture_2d<f32>;
|
|
1194
|
+
@group(3) @binding(1) var normalMap: texture_2d<f32>;
|
|
1195
|
+
@group(3) @binding(2) var metallicRoughnessMap: texture_2d<f32>;
|
|
1196
|
+
@group(3) @binding(3) var emissiveMap: texture_2d<f32>;
|
|
1197
|
+
@group(3) @binding(4) var aoMap: texture_2d<f32>;
|
|
1198
|
+
@group(3) @binding(5) var texSampler: sampler;
|
|
1199
|
+
|
|
1200
|
+
// Environment IBL (group 3, bindings 6-11)
|
|
1201
|
+
struct EnvironmentParams {
|
|
1202
|
+
intensity: f32,
|
|
1203
|
+
hasEnvironment: f32,
|
|
1204
|
+
_pad1: f32,
|
|
1205
|
+
_pad2: f32,
|
|
1206
|
+
}
|
|
1207
|
+
@group(3) @binding(6) var irradianceMap: texture_cube<f32>;
|
|
1208
|
+
@group(3) @binding(7) var prefilteredMap: texture_cube<f32>;
|
|
1209
|
+
@group(3) @binding(8) var brdfLUT: texture_2d<f32>;
|
|
1210
|
+
@group(3) @binding(9) var envSampler: sampler;
|
|
1211
|
+
@group(3) @binding(10) var brdfSampler: sampler;
|
|
1212
|
+
@group(3) @binding(11) var<uniform> envParams: EnvironmentParams;
|
|
1213
|
+
|
|
1214
|
+
// PBR Helper Functions
|
|
1215
|
+
fn DistributionGGX(N: vec3<f32>, H: vec3<f32>, roughness: f32) -> f32 {
|
|
1216
|
+
let a = roughness * roughness;
|
|
1217
|
+
let a2 = a * a;
|
|
1218
|
+
let NdotH = max(dot(N, H), 0.0);
|
|
1219
|
+
let NdotH2 = NdotH * NdotH;
|
|
1220
|
+
|
|
1221
|
+
let num = a2;
|
|
1222
|
+
var denom = (NdotH2 * (a2 - 1.0) + 1.0);
|
|
1223
|
+
denom = PI * denom * denom;
|
|
1224
|
+
|
|
1225
|
+
return num / denom;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
fn GeometrySchlickGGX(NdotV: f32, roughness: f32) -> f32 {
|
|
1229
|
+
let r = (roughness + 1.0);
|
|
1230
|
+
let k = (r * r) / 8.0;
|
|
1231
|
+
|
|
1232
|
+
let num = NdotV;
|
|
1233
|
+
let denom = NdotV * (1.0 - k) + k;
|
|
1234
|
+
|
|
1235
|
+
return num / denom;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
fn GeometrySmith(N: vec3<f32>, V: vec3<f32>, L: vec3<f32>, roughness: f32) -> f32 {
|
|
1239
|
+
let NdotV = max(dot(N, V), 0.0);
|
|
1240
|
+
let NdotL = max(dot(N, L), 0.0);
|
|
1241
|
+
let ggx2 = GeometrySchlickGGX(NdotV, roughness);
|
|
1242
|
+
let ggx1 = GeometrySchlickGGX(NdotL, roughness);
|
|
1243
|
+
|
|
1244
|
+
return ggx1 * ggx2;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
fn fresnelSchlick(cosTheta: f32, F0: vec3<f32>) -> vec3<f32> {
|
|
1248
|
+
return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
fn fresnelSchlickRoughness(cosTheta: f32, F0: vec3<f32>, roughness: f32) -> vec3<f32> {
|
|
1252
|
+
return F0 + (max(vec3<f32>(1.0 - roughness), F0) - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
const MAX_REFLECTION_LOD: f32 = 4.0;
|
|
1256
|
+
|
|
1257
|
+
fn sampleIBL(N: vec3<f32>, V: vec3<f32>, F0: vec3<f32>, roughness: f32, metallic: f32, albedo: vec3<f32>) -> vec3<f32> {
|
|
1258
|
+
if (envParams.hasEnvironment < 0.5) {
|
|
1259
|
+
return vec3<f32>(0.0);
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
let NdotV = max(dot(N, V), 0.0);
|
|
1263
|
+
let R = reflect(-V, N);
|
|
1264
|
+
|
|
1265
|
+
// Fresnel term for IBL (using roughness for energy conservation)
|
|
1266
|
+
let F = fresnelSchlickRoughness(NdotV, F0, roughness);
|
|
1267
|
+
|
|
1268
|
+
// Diffuse IBL
|
|
1269
|
+
let irradiance = textureSample(irradianceMap, envSampler, N).rgb;
|
|
1270
|
+
let kD = (vec3<f32>(1.0) - F) * (1.0 - metallic);
|
|
1271
|
+
let diffuseIBL = kD * irradiance * albedo;
|
|
1272
|
+
|
|
1273
|
+
// Specular IBL - F * brdf.x + brdf.y is the split-sum approximation
|
|
1274
|
+
let prefilteredColor = textureSampleLevel(prefilteredMap, envSampler, R, roughness * MAX_REFLECTION_LOD).rgb;
|
|
1275
|
+
let brdf = textureSample(brdfLUT, brdfSampler, vec2<f32>(NdotV, roughness)).rg;
|
|
1276
|
+
let specularIBL = prefilteredColor * (F * brdf.x + brdf.y);
|
|
1277
|
+
|
|
1278
|
+
return (diffuseIBL + specularIBL) * envParams.intensity;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
fn getNormalFromMap(normal: vec3<f32>, tangent: vec4<f32>, worldPos: vec3<f32>, uv: vec2<f32>) -> vec3<f32> {
|
|
1282
|
+
if (material.flags.y < 0.5) {
|
|
1283
|
+
return normal;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
let tangentNormal = textureSample(normalMap, texSampler, uv).xyz * 2.0 - 1.0;
|
|
1287
|
+
|
|
1288
|
+
let N = normalize(normal);
|
|
1289
|
+
var T: vec3<f32>;
|
|
1290
|
+
var B: vec3<f32>;
|
|
1291
|
+
|
|
1292
|
+
// Compute derivatives unconditionally to avoid "dpdx must only be called from uniform control flow" error
|
|
1293
|
+
let Q1 = dpdx(worldPos);
|
|
1294
|
+
let Q2 = dpdy(worldPos);
|
|
1295
|
+
let st1 = dpdx(uv);
|
|
1296
|
+
let st2 = dpdy(uv);
|
|
1297
|
+
|
|
1298
|
+
// Use provided tangent if valid (w is +/- 1.0). BatchManager uses 0.0 for dummy tangents.
|
|
1299
|
+
// Note: This condition is non-uniform (varying), but since derivatives are now computed outside, it's safe.
|
|
1300
|
+
if (abs(tangent.w) > 0.5) {
|
|
1301
|
+
T = normalize(tangent.xyz);
|
|
1302
|
+
B = cross(N, T) * tangent.w;
|
|
1303
|
+
} else {
|
|
1304
|
+
// Fallback to derivative-based TBN
|
|
1305
|
+
T = normalize(Q1 * st2.y - Q2 * st1.y);
|
|
1306
|
+
B = -normalize(cross(N, T));
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
let TBN = mat3x3<f32>(T, B, N);
|
|
1310
|
+
|
|
1311
|
+
return normalize(TBN * (tangentNormal * vec3<f32>(material.props.z, material.props.z, 1.0)));
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
fn calculateShadow(worldPos: vec3<f32>, light: Light, receiveShadow: f32) -> f32 {
|
|
1315
|
+
// Early return for no shadow layer (uniform condition)
|
|
1316
|
+
if (light.shadowLayerIndex < 0) {
|
|
1317
|
+
return 1.0;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
let lightPos = light.viewProj * vec4<f32>(worldPos, 1.0);
|
|
1321
|
+
let shadowPos = vec3<f32>(
|
|
1322
|
+
lightPos.x * 0.5 + 0.5,
|
|
1323
|
+
-lightPos.y * 0.5 + 0.5,
|
|
1324
|
+
lightPos.z
|
|
1325
|
+
);
|
|
1326
|
+
|
|
1327
|
+
// Always sample shadow map (uniform control flow for textureSampleCompare)
|
|
1328
|
+
var shadowSample = 0.0;
|
|
1329
|
+
let layerIndex = light.shadowLayerIndex;
|
|
1330
|
+
|
|
1331
|
+
if (light.shadowType > 1.5) {
|
|
1332
|
+
// PCFSoft (5x5)
|
|
1333
|
+
let texelSize = vec2<f32>(1.0 / light.shadowMapSize.x, 1.0 / light.shadowMapSize.y);
|
|
1334
|
+
for (var x = -2; x <= 2; x++) {
|
|
1335
|
+
for (var y = -2; y <= 2; y++) {
|
|
1336
|
+
let offset = vec2<f32>(f32(x), f32(y)) * texelSize;
|
|
1337
|
+
shadowSample += textureSampleCompare(shadowMap, shadowSampler, shadowPos.xy + offset, layerIndex, shadowPos.z - 0.005);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
shadowSample = shadowSample / 25.0;
|
|
1341
|
+
} else {
|
|
1342
|
+
shadowSample = textureSampleCompare(shadowMap, shadowSampler, shadowPos.xy, layerIndex, shadowPos.z - 0.005);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
// Apply shadow only if within light frustum and receiveShadow is enabled
|
|
1346
|
+
if (shadowPos.x > 0.0 && shadowPos.x < 1.0 &&
|
|
1347
|
+
shadowPos.y > 0.0 && shadowPos.y < 1.0 &&
|
|
1348
|
+
shadowPos.z > 0.0 && shadowPos.z < 1.0 &&
|
|
1349
|
+
receiveShadow > 0.5) {
|
|
1350
|
+
return shadowSample;
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
return 1.0;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
@fragment
|
|
1357
|
+
fn main(
|
|
1358
|
+
@location(0) vPosition: vec3<f32>,
|
|
1359
|
+
@location(1) vNormal: vec3<f32>,
|
|
1360
|
+
@location(2) vUV: vec2<f32>,
|
|
1361
|
+
@location(3) vCameraPos: vec3<f32>,
|
|
1362
|
+
@location(4) vReceiveShadow: f32,
|
|
1363
|
+
@location(5) vTangent: vec4<f32>
|
|
1364
|
+
) -> @location(0) vec4<f32> {
|
|
1365
|
+
// Sample textures
|
|
1366
|
+
var albedo = material.baseColor.rgb;
|
|
1367
|
+
var alpha = material.baseColor.a;
|
|
1368
|
+
if (material.flags.x > 0.5) {
|
|
1369
|
+
let texColor = textureSample(baseColorMap, texSampler, vUV);
|
|
1370
|
+
albedo *= texColor.rgb;
|
|
1371
|
+
alpha *= texColor.a;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// Alpha cutoff for masked materials (blendMode == 2)
|
|
1375
|
+
if (material.flags2.z > 1.5 && material.flags2.z < 2.5) {
|
|
1376
|
+
if (alpha < material.flags2.y) {
|
|
1377
|
+
discard;
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
var metallic = material.props.x;
|
|
1382
|
+
var roughness = material.props.y;
|
|
1383
|
+
if (material.flags.z > 0.5) {
|
|
1384
|
+
let mrSample = textureSample(metallicRoughnessMap, texSampler, vUV);
|
|
1385
|
+
roughness *= mrSample.g; // G channel = roughness (glTF)
|
|
1386
|
+
metallic *= mrSample.b; // B channel = metallic (glTF)
|
|
1387
|
+
}
|
|
1388
|
+
roughness = clamp(roughness, 0.04, 1.0);
|
|
1389
|
+
|
|
1390
|
+
var emissive = material.emissive.rgb * material.emissive.w;
|
|
1391
|
+
if (material.flags.w > 0.5) {
|
|
1392
|
+
emissive *= textureSample(emissiveMap, texSampler, vUV).rgb;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
var ao = 1.0;
|
|
1396
|
+
if (material.flags2.x > 0.5) {
|
|
1397
|
+
ao = mix(1.0, textureSample(aoMap, texSampler, vUV).r, material.props.w);
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// Get normal
|
|
1401
|
+
let N = getNormalFromMap(vNormal, vTangent, vPosition, vUV);
|
|
1402
|
+
let V = normalize(vCameraPos - vPosition);
|
|
1403
|
+
|
|
1404
|
+
// Calculate F0 (reflectance at normal incidence)
|
|
1405
|
+
let F0 = mix(vec3<f32>(0.04), albedo, metallic);
|
|
1406
|
+
|
|
1407
|
+
// Reflectance equation
|
|
1408
|
+
var Lo = vec3<f32>(0.0);
|
|
1409
|
+
|
|
1410
|
+
for (var i = 0u; i < lighting.lightCount; i++) {
|
|
1411
|
+
let light = lighting.lights[i];
|
|
1412
|
+
let L = normalize(-light.direction);
|
|
1413
|
+
let H = normalize(V + L);
|
|
1414
|
+
|
|
1415
|
+
let shadow = calculateShadow(vPosition, light, vReceiveShadow);
|
|
1416
|
+
let radiance = light.color * light.intensity * shadow;
|
|
1417
|
+
|
|
1418
|
+
// Cook-Torrance BRDF
|
|
1419
|
+
let NDF = DistributionGGX(N, H, roughness);
|
|
1420
|
+
let G = GeometrySmith(N, V, L, roughness);
|
|
1421
|
+
let F = fresnelSchlick(max(dot(H, V), 0.0), F0);
|
|
1422
|
+
|
|
1423
|
+
let kS = F;
|
|
1424
|
+
var kD = vec3<f32>(1.0) - kS;
|
|
1425
|
+
kD *= 1.0 - metallic;
|
|
1426
|
+
|
|
1427
|
+
let numerator = NDF * G * F;
|
|
1428
|
+
let denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0) + 0.0001;
|
|
1429
|
+
let specular = numerator / denominator;
|
|
1430
|
+
|
|
1431
|
+
let NdotL = max(dot(N, L), 0.0);
|
|
1432
|
+
Lo += (kD * albedo / PI + specular) * radiance * NdotL;
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
// IBL ambient lighting (replaces simple ambient)
|
|
1436
|
+
let iblAmbient = sampleIBL(N, V, F0, roughness, metallic, albedo) * ao;
|
|
1437
|
+
|
|
1438
|
+
// Fallback simple ambient when no environment
|
|
1439
|
+
var kD_ambient = vec3<f32>(1.0 - metallic);
|
|
1440
|
+
let simpleAmbient = lighting.ambientColor * albedo * kD_ambient * ao;
|
|
1441
|
+
|
|
1442
|
+
// Use IBL if available, otherwise use simple ambient
|
|
1443
|
+
let ambient = select(simpleAmbient, iblAmbient, envParams.hasEnvironment > 0.5);
|
|
1444
|
+
|
|
1445
|
+
let color = ambient + Lo + emissive;
|
|
1446
|
+
|
|
1447
|
+
// Tone mapping (simple Reinhard)
|
|
1448
|
+
let mapped = color / (color + vec3<f32>(1.0));
|
|
1449
|
+
|
|
1450
|
+
// Gamma correction
|
|
1451
|
+
let gammaCorrected = pow(mapped, vec3<f32>(1.0 / 2.2));
|
|
1452
|
+
|
|
1453
|
+
return vec4<f32>(gammaCorrected, alpha);
|
|
1454
|
+
}
|
|
1455
|
+
`}}let Ze=0;class ae{constructor(t,e){l(this,"id",Ze++);l(this,"source",null);l(this,"needsUpdate",!0);l(this,"wrapS","repeat");l(this,"wrapT","repeat");l(this,"minFilter","linear");l(this,"magFilter","linear");l(this,"mipmaps",!0);l(this,"flipY",!0);l(this,"gpuTexture",null);l(this,"gpuTextureView",null);t&&(this.source=t),e&&(e.wrapS!==void 0&&(this.wrapS=e.wrapS),e.wrapT!==void 0&&(this.wrapT=e.wrapT),e.minFilter!==void 0&&(this.minFilter=e.minFilter),e.magFilter!==void 0&&(this.magFilter=e.magFilter),e.mipmaps!==void 0&&(this.mipmaps=e.mipmaps),e.flipY!==void 0&&(this.flipY=e.flipY))}static async load(t,e){const a=await(await fetch(t)).blob(),r=(e==null?void 0:e.flipY)!==!1,s=await createImageBitmap(a,{imageOrientation:r?"flipY":"none"});return new ae(s,e)}dispose(){this.gpuTexture&&(this.gpuTexture.destroy(),this.gpuTexture=null,this.gpuTextureView=null)}}let Ke=0;class ye{constructor(t={}){l(this,"id",Ke++);l(this,"needsUpdate",!0);l(this,"hdrData",null);l(this,"hdrWidth",0);l(this,"hdrHeight",0);l(this,"resolution");l(this,"specularMipLevels");l(this,"intensity");l(this,"equirectTexture",null);l(this,"cubemap",null);l(this,"cubemapView",null);l(this,"irradianceMap",null);l(this,"irradianceMapView",null);l(this,"prefilteredMap",null);l(this,"prefilteredMapView",null);this.resolution=t.resolution??512,this.specularMipLevels=t.specularMipLevels??5,this.intensity=t.intensity??1}static async loadHDR(t,e){const i=await fetch(t);if(!i.ok)throw new Error(`Failed to load HDR: ${i.statusText}`);const a=await i.arrayBuffer(),{data:r,width:s,height:n}=Qe(new Uint8Array(a)),o=new ye(e);return o.hdrData=r,o.hdrWidth=s,o.hdrHeight=n,o.needsUpdate=!0,o}dispose(){var t,e,i,a;(t=this.equirectTexture)==null||t.destroy(),(e=this.cubemap)==null||e.destroy(),(i=this.irradianceMap)==null||i.destroy(),(a=this.prefilteredMap)==null||a.destroy(),this.equirectTexture=null,this.cubemap=null,this.cubemapView=null,this.irradianceMap=null,this.irradianceMapView=null,this.prefilteredMap=null,this.prefilteredMapView=null,this.hdrData=null}}function Qe(w){let t=0;const e=()=>{let u="";for(;t<w.length&&w[t]!==10;)u+=String.fromCharCode(w[t]),t++;return t++,u},i=e();if(!i.startsWith("#?RADIANCE")&&!i.startsWith("#?RGBE"))throw new Error("Invalid HDR file: missing magic number");for(;;){const u=e();if(u==="")break;u.startsWith("FORMAT=")&&u.substring(7)}const r=e().match(/-Y\s+(\d+)\s+\+X\s+(\d+)/);if(!r)throw new Error("Invalid HDR file: cannot parse resolution");const s=parseInt(r[1],10),n=parseInt(r[2],10),o=new Uint8Array(n*s*4);for(let u=0;u<s;u++)if(w[t]===2&&w[t+1]===2){if((w[t+2]<<8|w[t+3])!==n)throw new Error("Invalid HDR scanline width");t+=4;const p=new Uint8Array(n*4);for(let d=0;d<4;d++){let f=0;for(;f<n;){const m=w[t++];if(m>128){const x=m-128,g=w[t++];for(let y=0;y<x;y++)p[f*4+d]=g,f++}else for(let x=0;x<m;x++)p[f*4+d]=w[t++],f++}}o.set(p,u*n*4)}else for(let h=0;h<n;h++)o[(u*n+h)*4+0]=w[t++],o[(u*n+h)*4+1]=w[t++],o[(u*n+h)*4+2]=w[t++],o[(u*n+h)*4+3]=w[t++];const c=new Float32Array(n*s*4);for(let u=0;u<n*s;u++){const h=o[u*4+0],p=o[u*4+1],d=o[u*4+2],f=o[u*4+3];if(f===0)c[u*4+0]=0,c[u*4+1]=0,c[u*4+2]=0;else{const m=2**(f-128-8);c[u*4+0]=h*m,c[u*4+1]=p*m,c[u*4+2]=d*m}c[u*4+3]=1}return{data:c,width:n,height:s}}const C={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};class Je{constructor(){l(this,"json",null);l(this,"bufferData",new Map);l(this,"textures",new Map);l(this,"materials",new Map);l(this,"meshes",new Map);l(this,"geometries",new Map);l(this,"baseURL","")}async load(t){this.baseURL=t.substring(0,t.lastIndexOf("/")+1);const e=await fetch(t);if(!e.ok)throw new Error(`Failed to load GLTF file: ${t}`);const i=await e.arrayBuffer();if(new DataView(i,0,4).getUint32(0,!0)===1179937895)return this.parseGLB(i);{const r=new TextDecoder().decode(i),s=JSON.parse(r);return this.parse(s)}}async parseGLB(t){const e=new DataView(t),i=e.getUint32(8,!0);let a=null,r=null,s=12;for(;s<i;){const n=e.getUint32(s,!0),o=e.getUint32(s+4,!0);if(s+=8,o===1313821514){const c=new Uint8Array(t,s,n),u=new TextDecoder().decode(c);a=JSON.parse(u)}else o===5130562&&(r=t.slice(s,s+n));s+=n}if(!a)throw new Error("GLB missing JSON chunk");return this.json=a,this.bufferData.clear(),this.textures.clear(),this.materials.clear(),this.geometries.clear(),this.meshes.clear(),r&&this.bufferData.set(0,r),this.parse(a,!0)}async parse(t,e=!1){return this.json=t,e||(this.bufferData.clear(),this.textures.clear(),this.materials.clear(),this.geometries.clear(),this.meshes.clear()),await this.loadBuffers(),await this.loadTextures(),this.loadMaterials(),this.loadMeshes(),this.buildScene()}async loadBuffers(){var e;if(!((e=this.json)!=null&&e.buffers))return;const t=this.json.buffers.map(async(i,a)=>{let r=i.uri;if(!r){if(this.bufferData.has(a))return;throw new Error("Embedded buffers (GLB) not found or supported.")}if(r.startsWith("data:")){const c=await(await fetch(r)).arrayBuffer();this.bufferData.set(a,c);return}r=this.resolveURL(r);const s=await fetch(r);if(!s.ok)throw new Error(`Failed to load buffer: ${r}`);const n=await s.arrayBuffer();this.bufferData.set(a,n)});await Promise.all(t)}resolveURL(t){return t.startsWith("http")||t.startsWith("data:")?t:this.baseURL+t}async loadTextures(){var a;if(!((a=this.json)!=null&&a.textures))return;const t=(this.json.images||[]).map(async(r,s)=>{let n;if(r.uri){const o=this.resolveURL(r.uri),u=await(await fetch(o)).blob();n=await createImageBitmap(u)}else if(r.bufferView!==void 0){const o=this.json.bufferViews[r.bufferView],c=this.bufferData.get(o.buffer);if(!c)throw new Error(`Buffer ${o.buffer} not found for image ${s}`);const u=new Blob([new Uint8Array(c,o.byteOffset||0,o.byteLength)],{type:r.mimeType});n=await createImageBitmap(u)}else throw new Error(`Image ${s} has no uri or bufferView`);return{index:s,source:n}}),e=await Promise.all(t),i=new Map;e.forEach(({index:r,source:s})=>{i.set(r,s)}),this.json.textures.forEach((r,s)=>{if(r.source===void 0)return;const n=i.get(r.source);if(!n)return;const o=r.sampler!==void 0&&this.json.samplers?this.json.samplers[r.sampler]:{},c=new ae(n,{wrapS:this.convertWrapMode(o.wrapS),wrapT:this.convertWrapMode(o.wrapT),minFilter:this.convertMinFilter(o.minFilter),magFilter:this.convertMagFilter(o.magFilter),flipY:!1});this.textures.set(s,c)})}convertWrapMode(t){switch(t){case C.CLAMP_TO_EDGE:return"clamp-to-edge";case C.MIRRORED_REPEAT:return"mirror-repeat";case C.REPEAT:return"repeat";default:return"repeat"}}convertMinFilter(t){switch(t){case C.NEAREST:case C.NEAREST_MIPMAP_NEAREST:case C.NEAREST_MIPMAP_LINEAR:return"nearest";case C.LINEAR:case C.LINEAR_MIPMAP_NEAREST:case C.LINEAR_MIPMAP_LINEAR:return"linear";default:return"linear"}}convertMagFilter(t){switch(t){case C.NEAREST:return"nearest";case C.LINEAR:return"linear";default:return"linear"}}loadMaterials(){var t;(t=this.json)!=null&&t.materials&&this.json.materials.forEach((e,i)=>{var r,s,n,o,c,u;const a=new $({baseColor:(r=e.pbrMetallicRoughness)!=null&&r.baseColorFactor?new b(e.pbrMetallicRoughness.baseColorFactor[0],e.pbrMetallicRoughness.baseColorFactor[1],e.pbrMetallicRoughness.baseColorFactor[2]):new b(1,1,1),opacity:(s=e.pbrMetallicRoughness)!=null&&s.baseColorFactor?e.pbrMetallicRoughness.baseColorFactor[3]:1,metallic:((n=e.pbrMetallicRoughness)==null?void 0:n.metallicFactor)??1,roughness:((o=e.pbrMetallicRoughness)==null?void 0:o.roughnessFactor)??1,emissive:e.emissiveFactor?new b(e.emissiveFactor[0],e.emissiveFactor[1],e.emissiveFactor[2]):new b(0,0,0),emissiveFactor:1,doubleSided:e.doubleSided??!1,alphaCutoff:e.alphaCutoff??.5,blendMode:e.alphaMode==="BLEND"?1:e.alphaMode==="MASK"?2:0,transparent:e.alphaMode==="BLEND"});(c=e.pbrMetallicRoughness)!=null&&c.baseColorTexture&&(a.baseColorMap=this.textures.get(e.pbrMetallicRoughness.baseColorTexture.index)||null),(u=e.pbrMetallicRoughness)!=null&&u.metallicRoughnessTexture&&(a.metallicRoughnessMap=this.textures.get(e.pbrMetallicRoughness.metallicRoughnessTexture.index)||null),e.normalTexture&&(a.normalMap=this.textures.get(e.normalTexture.index)||null,a.uniforms.normalScale=e.normalTexture.scale??1),e.emissiveTexture&&(a.emissiveMap=this.textures.get(e.emissiveTexture.index)||null),e.occlusionTexture&&(a.aoMap=this.textures.get(e.occlusionTexture.index)||null,a.uniforms.occlusionStrength=e.occlusionTexture.strength??1),this.materials.set(i,a)})}loadMeshes(){var t;(t=this.json)!=null&&t.meshes&&this.json.meshes.forEach((e,i)=>{const a=[];e.primitives.forEach(r=>{const s=r.attributes;if(s.POSITION===void 0)return;const n=this.getAccessor(s.POSITION),o=this.getAccessorData(n);let c;if(s.NORMAL!==void 0){const f=this.getAccessor(s.NORMAL);c=this.getAccessorData(f)}let u;if(s.TEXCOORD_0!==void 0){const f=this.getAccessor(s.TEXCOORD_0);u=this.getAccessorData(f)}let h;if(r.indices!==void 0){const f=this.getAccessor(r.indices),m=this.getAccessorData(f);m instanceof Uint32Array?h=m:h=new Uint32Array(m)}let p;if(s.TANGENT!==void 0){const f=this.getAccessor(s.TANGENT);p=this.getAccessorData(f)}const d=new R(o,h,c,u,p);a.push(d)}),this.geometries.set(i,a)})}getAccessor(t){return this.json.accessors[t]}getAccessorData(t){const e=this.json.bufferViews[t.bufferView],i=this.bufferData.get(e.buffer);if(!i)throw new Error(`Buffer ${e.buffer} not found`);const a=(e.byteOffset||0)+(t.byteOffset||0),r=t.componentType,s=t.count,n=this.getNumComponents(t.type),o=s*n,c=this.getComponentSize(r)*n,u=e.byteStride||c;if(u===c)return this.createTypedArray(i,a,o,r);{const h=this.getComponentSize(r),p=new ArrayBuffer(o*h),d=new DataView(p),f=new DataView(i,a,s*u);for(let m=0;m<s;m++){const x=m*u,g=m*n*h;for(let y=0;y<n;y++){const v=y*h;switch(r){case C.BYTE:d.setInt8(g+v,f.getInt8(x+v));break;case C.UNSIGNED_BYTE:d.setUint8(g+v,f.getUint8(x+v));break;case C.SHORT:d.setInt16(g+v,f.getInt16(x+v,!0));break;case C.UNSIGNED_SHORT:d.setUint16(g+v,f.getUint16(x+v,!0));break;case C.UNSIGNED_INT:d.setUint32(g+v,f.getUint32(x+v,!0));break;case C.FLOAT:d.setFloat32(g+v,f.getFloat32(x+v,!0));break}}}return this.createTypedArray(p,0,o,r)}}getNumComponents(t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 0}}getComponentSize(t){switch(t){case C.BYTE:return 1;case C.UNSIGNED_BYTE:return 1;case C.SHORT:return 2;case C.UNSIGNED_SHORT:return 2;case C.UNSIGNED_INT:return 4;case C.FLOAT:return 4;default:return 0}}createTypedArray(t,e,i,a){switch(a){case C.BYTE:return new Int8Array(t,e,i);case C.UNSIGNED_BYTE:return new Uint8Array(t,e,i);case C.SHORT:return new Int16Array(t,e,i);case C.UNSIGNED_SHORT:return new Uint16Array(t,e,i);case C.UNSIGNED_INT:return new Uint32Array(t,e,i);case C.FLOAT:return new Float32Array(t,e,i);default:throw new Error(`Unknown component type ${a}`)}}buildScene(){var a,r;const t=((a=this.json)==null?void 0:a.scene)??0,e=(r=this.json)!=null&&r.scenes?this.json.scenes[t]:void 0,i=new N;return i.name="GLTF Root",e&&e.nodes&&e.nodes.forEach(s=>{const n=this.parseNode(s);i.add(n)}),i}parseNode(t){const e=this.json.nodes[t],i=new N;if(i.name=e.name||`Node_${t}`,e.matrix?(i.localMatrix.set(e.matrix[0],e.matrix[1],e.matrix[2],e.matrix[3],e.matrix[4],e.matrix[5],e.matrix[6],e.matrix[7],e.matrix[8],e.matrix[9],e.matrix[10],e.matrix[11],e.matrix[12],e.matrix[13],e.matrix[14],e.matrix[15]),i.localMatrix.decompose(i.position,i.rotation,i.scale)):(e.translation&&i.position.set(e.translation[0],e.translation[1],e.translation[2]),e.rotation&&i.rotation.set(e.rotation[0],e.rotation[1],e.rotation[2],e.rotation[3]),e.scale&&i.scale.set(e.scale[0],e.scale[1],e.scale[2]),i.updateLocalMatrix()),e.mesh!==void 0){const a=this.geometries.get(e.mesh),r=this.json.meshes[e.mesh];if(a)if(a.length===1){const n=r.primitives[0].material;let o=this.materials.get(n);o||(o=new $);const c=new q(a[0],o);return c.name=i.name,c.position.copy(i.position),c.rotation.copy(i.rotation),c.scale.copy(i.scale),c.localMatrix.copy(i.localMatrix),this.createMeshNode(a,r,i)}else a.forEach((s,n)=>{const c=r.primitives[n].material;let u=this.materials.get(c);u||(u=new $);const h=new q(s,u);h.name=`${i.name}_Primitive_${n}`,i.add(h)})}return e.children&&e.children.forEach(a=>{const r=this.parseNode(a);i.add(r)}),i}createMeshNode(t,e,i){if(t.length===1){const r=e.primitives[0].material;let s=this.materials.get(r);s||(s=new $);const n=new q(t[0],s);return n.name=i.name,n.position.copy(i.position),n.rotation.copy(i.rotation),n.scale.copy(i.scale),n.updateLocalMatrix(),i.children.forEach(o=>{n.add(o)}),n}else return i}}class et{constructor(t,e,i={}){l(this,"enabled",!0);l(this,"target");l(this,"minDistance",.1);l(this,"maxDistance",1/0);l(this,"minPolarAngle",0);l(this,"maxPolarAngle",Math.PI);l(this,"enableDamping",!0);l(this,"dampingFactor",.05);l(this,"rotateSpeed",1);l(this,"panSpeed",1);l(this,"zoomSpeed",1);l(this,"enablePan",!0);l(this,"enableZoom",!0);l(this,"camera");l(this,"domElement");l(this,"spherical",{radius:1,phi:Math.PI/2,theta:0});l(this,"sphericalDelta",{phi:0,theta:0});l(this,"panOffset",new b);l(this,"scale",1);l(this,"isPointerDown",!1);l(this,"pointerStart",{x:0,y:0});l(this,"pointerType","rotate");l(this,"touches",[]);l(this,"lastPinchDistance",0);l(this,"onPointerDownBound");l(this,"onPointerMoveBound");l(this,"onPointerUpBound");l(this,"onWheelBound");l(this,"onContextMenuBound");this.camera=t,this.domElement=e,this.target=i.target??new b(0,0,0),i.enabled!==void 0&&(this.enabled=i.enabled),i.minDistance!==void 0&&(this.minDistance=i.minDistance),i.maxDistance!==void 0&&(this.maxDistance=i.maxDistance),i.minPolarAngle!==void 0&&(this.minPolarAngle=i.minPolarAngle),i.maxPolarAngle!==void 0&&(this.maxPolarAngle=i.maxPolarAngle),i.enableDamping!==void 0&&(this.enableDamping=i.enableDamping),i.dampingFactor!==void 0&&(this.dampingFactor=i.dampingFactor),i.rotateSpeed!==void 0&&(this.rotateSpeed=i.rotateSpeed),i.panSpeed!==void 0&&(this.panSpeed=i.panSpeed),i.zoomSpeed!==void 0&&(this.zoomSpeed=i.zoomSpeed),i.enablePan!==void 0&&(this.enablePan=i.enablePan),i.enableZoom!==void 0&&(this.enableZoom=i.enableZoom),this.updateSphericalFromCamera(),this.onPointerDownBound=this.onPointerDown.bind(this),this.onPointerMoveBound=this.onPointerMove.bind(this),this.onPointerUpBound=this.onPointerUp.bind(this),this.onWheelBound=this.onWheel.bind(this),this.onContextMenuBound=a=>a.preventDefault(),this.domElement.addEventListener("pointerdown",this.onPointerDownBound),this.domElement.addEventListener("pointermove",this.onPointerMoveBound),this.domElement.addEventListener("pointerup",this.onPointerUpBound),this.domElement.addEventListener("pointercancel",this.onPointerUpBound),this.domElement.addEventListener("wheel",this.onWheelBound,{passive:!1}),this.domElement.addEventListener("contextmenu",this.onContextMenuBound)}updateSphericalFromCamera(){const t=new b().subVectors(this.camera.position,this.target);this.spherical.radius=t.length(),this.spherical.radius===0&&(this.spherical.radius=1),this.spherical.phi=Math.acos(Math.max(-1,Math.min(1,t.y/this.spherical.radius))),this.spherical.theta=Math.atan2(t.x,t.z)}onPointerDown(t){this.enabled&&(this.domElement.setPointerCapture(t.pointerId),this.isPointerDown=!0,this.pointerStart.x=t.clientX,this.pointerStart.y=t.clientY,t.button===2||t.shiftKey?this.pointerType="pan":this.pointerType="rotate",this.touches.push({id:t.pointerId,x:t.clientX,y:t.clientY}))}onPointerMove(t){if(!this.enabled||!this.isPointerDown)return;const e=this.touches.findIndex(r=>r.id===t.pointerId);if(e>=0&&(this.touches[e].x=t.clientX,this.touches[e].y=t.clientY),this.touches.length===2&&this.enableZoom){const r=this.touches[0].x-this.touches[1].x,s=this.touches[0].y-this.touches[1].y,n=Math.sqrt(r*r+s*s);if(this.lastPinchDistance>0){const o=n/this.lastPinchDistance;this.scale*=o}this.lastPinchDistance=n;return}const i=t.clientX-this.pointerStart.x,a=t.clientY-this.pointerStart.y;if(this.pointerType==="rotate"){const r=2*Math.PI/this.domElement.clientHeight*this.rotateSpeed;this.sphericalDelta.theta-=i*r,this.sphericalDelta.phi-=a*r}else this.pointerType==="pan"&&this.enablePan&&this.pan(i,a);this.pointerStart.x=t.clientX,this.pointerStart.y=t.clientY}onPointerUp(t){this.domElement.releasePointerCapture(t.pointerId);const e=this.touches.findIndex(i=>i.id===t.pointerId);e>=0&&this.touches.splice(e,1),this.touches.length===0&&(this.isPointerDown=!1,this.lastPinchDistance=0)}onWheel(t){!this.enabled||!this.enableZoom||(t.preventDefault(),t.deltaY<0?this.scale/=.95**this.zoomSpeed:t.deltaY>0&&(this.scale*=.95**this.zoomSpeed))}pan(t,e){const r=new b().subVectors(this.camera.position,this.target).length()*this.panSpeed*.001,s=this.camera.worldMatrix.elements,n=new b(s[0],s[1],s[2]).normalize(),o=new b(s[4],s[5],s[6]).normalize();this.panOffset.add(n.multiplyScalar(-t*r)),this.panOffset.add(o.multiplyScalar(e*r))}update(){if(!this.enabled)return;this.enableDamping?(this.spherical.theta+=this.sphericalDelta.theta*this.dampingFactor,this.spherical.phi+=this.sphericalDelta.phi*this.dampingFactor):(this.spherical.theta+=this.sphericalDelta.theta,this.spherical.phi+=this.sphericalDelta.phi),this.spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this.spherical.phi)),this.spherical.phi=Math.max(1e-4,Math.min(Math.PI-1e-4,this.spherical.phi)),this.spherical.radius*=this.scale,this.spherical.radius=Math.max(this.minDistance,Math.min(this.maxDistance,this.spherical.radius)),this.target.add(this.panOffset);const t=Math.sin(this.spherical.phi)*this.spherical.radius,e=new b(t*Math.sin(this.spherical.theta),Math.cos(this.spherical.phi)*this.spherical.radius,t*Math.cos(this.spherical.theta));this.camera.position.copy(this.target).add(e),this.camera.lookAt(this.target),this.enableDamping?(this.sphericalDelta.theta*=1-this.dampingFactor,this.sphericalDelta.phi*=1-this.dampingFactor):(this.sphericalDelta.theta=0,this.sphericalDelta.phi=0),this.scale=1,this.panOffset.set(0,0,0)}setTarget(t,e,i){this.target.set(t,e,i),this.updateSphericalFromCamera()}reset(){this.updateSphericalFromCamera(),this.sphericalDelta.theta=0,this.sphericalDelta.phi=0,this.scale=1,this.panOffset.set(0,0,0)}dispose(){this.domElement.removeEventListener("pointerdown",this.onPointerDownBound),this.domElement.removeEventListener("pointermove",this.onPointerMoveBound),this.domElement.removeEventListener("pointerup",this.onPointerUpBound),this.domElement.removeEventListener("pointercancel",this.onPointerUpBound),this.domElement.removeEventListener("wheel",this.onWheelBound),this.domElement.removeEventListener("contextmenu",this.onContextMenuBound)}}M.BasicMaterial=je,M.BlendMode=z,M.Box3=k,M.BoxGeometry=Z,M.Camera=me,M.CircleGeometry=te,M.ConeGeometry=ie,M.CylinderGeometry=J,M.DirectionalLight=j,M.Environment=ye,M.Euler=pe,M.GLTFLoader=Je,M.LambertMaterial=We,M.Light=fe,M.Matrix3=X,M.Matrix4=A,M.Mesh=q,M.Object3D=N,M.OrbitControls=et,M.OrthographicCamera=ve,M.PerspectiveCamera=He,M.PhongMaterial=$e,M.PlaneGeometry=Q,M.Quaternion=L,M.Renderer=Xe,M.Scene=qe,M.ShadowType=Be,M.SphereGeometry=K,M.StandardMaterial=$,M.Texture=ae,M.TorusGeometry=ee,M.Vector2=U,M.Vector3=b,M.clamp=F,M.degToRad=Se,M.radToDeg=Ce,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
|