var $=Object.defineProperty;var H=(i,e,r)=>e in i?$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):i[e]=r;var g=(i,e,r)=>(H(i,typeof e!="symbol"?e+"":e,r),r);import{aG as G,aU as X,aC as T,e as v,C as c,bf as Q,aX as z,bg as K,bh as Z,j as q,u as J,bi as Y,N,K as w,V as L,B as O,bj as ee,bk as te,bl as re,bm as se,ao as j,bn as ae,bo as ie,a$ as oe,x as ne,bp as le,n as ce,o as de}from"./index-a76b28be.js";import"./index-4d966268.js";import"./postmen-a4b10828.js";import{E as S,b as pe,s as ue}from"./ProxyConfigs-ab5351dd.js";import{I as he}from"./IconPointFilled-4673caaf.js";import{F as fe}from"./index-e599c562.js";import{c as U,E as k,b as Se,g as me,o as ge}from"./ShaderUIScriptAsset-b7befe23.js";G(he,{variants:{checked:{true:{color:"$green10"}}}});const be=X(i=>{const{asset:e}=i;if(e.compileError)return T.jsx(fe,{label:v("shader.inspector.compile-error"),value:e.compileError});const r=[],t={};for(const a of e.properties??[]){const{uiInfo:s}=a;if(!s||s.hide)continue;const o=s.assetType??s.type,n={label:s.label,type:c.PureDisplay,disabled:!0,value:a.bundleType==="macro"?"MACRO":o,property:a.prop};if(s.group){const l=t[a.uiInfo.group]??{children:[],type:c.Group,property:s.group};l.children.push(n),t[s.group]=l}else r.push(n)}for(const a in t)r.push(t[a]);return T.jsxs(T.Fragment,{children:[T.jsx(Q,{inspectorConfig:{property:v("shader.inspector.properties"),type:c.Group,children:r},onModelChange:null,model:e},"Properties"),e.shaderScriptRefId&&T.jsx(z.Item,{model:e,inspectorConfig:{label:v("shader.inspector.included-ui-script"),type:c.Display,disabled:!0,property:"uiScript",value:e.root.assetStore.assets[e.shaderScriptRefId.refId].getRouteString()},onModelChange:null})]})}),Ce={Unlit:{filename:"UnlitShader.shader",uiScriptTemplateType:U.UnlitUIScript,uiScriptFileName:"UnlitScript.ts"},PBR:{filename:"PBRShader.shader",uiScriptTemplateType:U.PbrUIScript,uiScriptFileName:"PBRScript.ts"},Sprite:{filename:"SpriteShader.shader"}},_e=`
      RenderQueueType renderQueueType;
      BlendFactor sourceColorBlendFactor;
      BlendFactor destinationColorBlendFactor;
      BlendFactor sourceAlphaBlendFactor;
      BlendFactor destinationAlphaBlendFactor;
      CullMode rasterStateCullMode;
      Bool blendEnabled;
      Bool depthWriteEnabled;

      DepthState customDepthState {
        WriteEnabled = depthWriteEnabled;
      }

      BlendState customBlendState {
        Enabled = blendEnabled;
        SourceColorBlendFactor = sourceColorBlendFactor;
        DestinationColorBlendFactor = destinationColorBlendFactor;
        SourceAlphaBlendFactor = sourceAlphaBlendFactor;
        DestinationAlphaBlendFactor = destinationAlphaBlendFactor;
      }

      RasterState customRasterState {
        CullMode = rasterStateCullMode;
      }

      DepthState = customDepthState;
      BlendState = customBlendState;
      RasterState = customRasterState;
      RenderQueueType = renderQueueType;
`,ye=i=>`Shader "${i}" {
    SubShader "Default" {
      Pass "Pass0" {
        DepthState customDepthState {
          WriteEnabled = false;
        }

        BlendState customBlendState {
          Enabled = true;
          SourceColorBlendFactor = BlendFactor.SourceAlpha;
          DestinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
          SourceAlphaBlendFactor = BlendFactor.One;
          DestinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
          ColorBlendOperation = BlendOperation.Add;
          AlphaBlendOperation = BlendOperation.Add;
        }

        RasterState customRasterState {
          CullMode = CullMode.Off;
        }

        RenderQueueType = Transparent;
        DepthState = customDepthState;
        BlendState = customBlendState;
        RasterState = customRasterState;

        struct Attributes {
          vec3 POSITION;
          vec2 TEXCOORD_0;
          vec4 COLOR_0;
        };
      
        struct Varyings {
          vec2 uv;
          vec4 color;
        };

        #include "Common.glsl"
        #include "Transform.glsl"

        sampler2D renderer_SpriteTexture;

        VertexShader = vert;
        FragmentShader = frag;

        Varyings vert(Attributes attr) {
          Varyings v;
          gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0);
          v.uv = attr.TEXCOORD_0;
          v.color = attr.COLOR_0;

          return v;
        }
      
        void frag(Varyings v) {
          vec4 baseColor = texture2DSRGB(renderer_SpriteTexture, v.uv);
          gl_FragColor = baseColor * v.color;
        }
    }
  }
}`,Ie=(i,e)=>`Shader "${i}" {
    Editor {
      Properties {
        /**
          * @language zh
          * 主颜色
        */

        /**
        * @language en
        * Main Color
        */
        material_BaseColor("Main Color", Color) = (0, 0, 0, 1);
        material_BaseTexture("Texture", Texture2D);
        material_AlphaCutoff("Alpha Cutoff", Range(0, 1, 0.01)) = 0;

        Header("Common"){
          isTransparent("Transparent", Boolean) = false;
          renderFace("Render Face", Enum(Front:0, Back:1, Double:2)) = 0;
          blendMode("Blend Mode", Enum(Normal:0, Additive:1)) = 0;
        }
      }

      UIScript "${e}";
    }

    SubShader "Default" {
      UsePass "pbr/Default/ShadowCaster"

      Pass "Pass0" {
        ${_e}
      
        struct Attributes {
          vec3 POSITION;
          vec2 TEXCOORD_0;
          vec4 JOINTS_0;
          vec4 WEIGHTS_0;
        };
      
        struct Varyings {
          vec2 uv;
        };

        #include "Common.glsl"
        #include "Skin.glsl"
        #include "Transform.glsl"

        vec4 material_BaseColor;
        float material_AlphaCutoff;
        sampler2D material_BaseTexture;
      
        VertexShader = vert;
        FragmentShader = frag;
      
        Varyings vert(Attributes attr) {
          Varyings v;

          vec4 position = vec4(attr.POSITION, 1.0);

          // Skin
          #ifdef RENDERER_HAS_SKIN
            mat4 skinMatrix = getSkinMatrix(attr);
            position = skinMatrix * position;
          #endif

          gl_Position = renderer_MVPMat * position;
          v.uv = attr.TEXCOORD_0;

          return v;
        }
      
        void frag(Varyings v) {
          vec4 baseColor = material_BaseColor;

          #ifdef MATERIAL_HAS_BASETEXTURE
              vec4 textureColor = texture2D(material_BaseTexture, v.uv);
              baseColor *= textureColor;
          #endif
      
          #ifdef MATERIAL_IS_ALPHA_CUTOFF
              if( baseColor.a < material_AlphaCutoff ) {
                  discard;
              }
          #endif
      
          gl_FragColor = baseColor;
        }
    }
  }
}`,Me=(i,e)=>K.replace("PBRShaderName",i).replace("UIScriptPath",e);function Re(i,e){switch(e.template){case"PBR":return Me(i,e.uiScriptPath);case"Unlit":return Ie(i,e.uiScriptPath);case"Sprite":return ye(i)}}var W=Object.defineProperty,Be=Object.getOwnPropertyDescriptor,Te=(i,e,r)=>e in i?W(i,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):i[e]=r,P=(i,e,r,t)=>{for(var a=t>1?void 0:t?Be(e,r):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(a=(t?o(e,r,a):o(a))||a);return t&&a&&W(e,r,a),a},B=(i,e,r)=>(Te(i,typeof e!="symbol"?e+"":e,r),r);Z();var xe=(i=>(i.Color="Color",i.Vector4="Vector4",i.Vector3="Vector3",i.Vector2="Vector2",i.Int="Int",i.Float="Float",i.Range="Range",i.Texture2D="Texture2D",i.TextureCube="TextureCube",i.Boolean="Boolean",i.Null="Null",i.HDRColor="HDRColor",i))(xe||{});class x{constructor(e,r,t){g(this,"min");g(this,"max");g(this,"dragStep");this.min=e,this.max=r,this.dragStep=t}static create(e){const r=/Range\(\s*(.+?)\)/,t=e.match(r);if(!t)throw`invalid range type ${e}`;const a=t[1].split(",").map(Number);return new x(...a)}}class A{constructor(e,r){this.data=e,this.type=r}static create(e){const t=e.slice(5,-1).split(","),s=t[0].split(":").indexOf(".")===-1?S.Integer:S.Float,o=t.map(n=>{const[l,h]=n.split(":");return{label:l.trim(),value:Number(h)}});return new A(o,s)}}let d=class extends q{constructor(e){super(e);g(this,"_shaderSource");g(this,"_shaderScriptRefId");g(this,"includePath");g(this,"builtinShaderName");g(this,"_compileError");g(this,"properties",[]);g(this,"_referencedMaterialList",[]);J(this)}get compileError(){return this._compileError}get shaderSource(){return this._shaderSource}get shaderScriptRefId(){return this._shaderScriptRefId}async initByMeta(e){await super.initByMeta(e),this.builtinShaderName=e.builtinShaderName}addReferencedMaterial(e){this._referencedMaterialList.findIndex(r=>r.id===e.id)===-1&&this._referencedMaterialList.push(e)}removeReferencedMaterial(e){if(!this._referencedMaterialList)return;const r=this._referencedMaterialList.findIndex(t=>t.id===e.id);r!==-1&&this._referencedMaterialList.splice(r,1)}updateShaderSourceName(){this.includePath=this.getRouteString(),this._shaderSource=this._shaderSource.replace(/Shader\s+"[^"]*"\s*{/,`Shader "${this.includePath}" {`),this.updateCode(this._shaderSource),this.saveMainAndMeta()}async rename(e){await super.rename(e),this.updateShaderSourceName();for(const r of this._referencedMaterialList)this.root.assetFacade.persistAssetMain(r.id)}async moveTo(e){await this.moveViaFacade(e),this.updateShaderSourceName();for(const r of this._referencedMaterialList)this.root.assetFacade.persistAssetMain(r.id)}async initByMain(e,r){const t=await e.text();this.includePath=this.getRouteString();const a=Object.values(this.root.assetStore.assets).filter(s=>s.meta.type==="ShaderChunk"||s.meta.subType===k.ShaderUI);await Promise.all(a.map(s=>s.loadMainFilePromise?s.loadMainFilePromise:s.loadMainFile())),t&&this.updateCode(t)}async initByCreation(e,r,t){const a=t==null?void 0:t.template,s=Ce[a];s&&this.setNameByIncrease(s.filename);const{uiScriptTemplateType:o,uiScriptFileName:n}=s;let l;return o&&(l=`./${(await this.root.assetFacade.createAssetByAdd({assetType:"script",params:{template:o,subType:k.ShaderUI},name:n,parentFolderId:this.parentFolderId})).name}`,window.Tracert.click("c351688.d418024",{type:"ShaderUIScript",source:"Shader"})),this._shaderSource=Re(this.getRouteString(),{template:t.template,uiScriptPath:l}),Promise.resolve(this.getMainData())}getMainData(){return this._shaderSource}isBuiltinShader(){return this.builtinShaderName}parseEditorModule(){if(d._editorModuleRegex.test(this._shaderSource)){const e=this.extractPropertyContent("Editor");this.parseShaderScript(e);const r=this.extractPropertyContent("Properties",e);this.parseProperties(r);const t=this.extractPropertyContent("Macros",e);this.parseMacros(t)}else{const e=this.extractPropertyContent("EditorProperties");this.parseProperties(e);const r=this.extractPropertyContent("EditorMacros");this.parseMacros(r)}}parseProperties(e){if(!e)return;const r=e.split(`
`);let t,a;for(let s=0;s<r.length;s++){const o=r[s],n=o.trim();if(n.startsWith("/**")){a=a??{};let h="",b="default";const C=_=>{const u=_.match(d._commentsLineRegex);if(u!=null&&u[1]){const p=u[1].match(d._langSpecification);p!=null&&p[1]?b=p[1]:h+=u[1]+`
`}else h+=u?"":_+`
`};let R=n.substring(2);for(;!R.startsWith("*/");)C(R),R=r[++s].trim();a[b]=h;continue}const l=n.match(d._groupRegex);l?t={type:l[1],title:l[2]}:o&&(this.parsePropertyItem(o,a,t),a=void 0),n.endsWith("}")&&(t=void 0)}}parseMacros(e){if(!e)return;const r=e.split(`
`);let t;for(const a of r){const s=a.trim(),o=s.match(d._groupRegex);o?t={type:o[1],title:o[2]}:this.parseMacroItem(a,t),s.endsWith("}")&&(t=void 0)}}parseShaderScript(e){const r=e.match(d._scriptRegex),t=r==null?void 0:r[1];if(t){const a=this.getRouteString(!1),s=Y(a,t),o=Se.assetsMap.get(s);if(o){if(o.addReferencedShader(this),this._shaderScriptRefId){const n=this.root.assetStore.assets[this._shaderScriptRefId.refId];n==null||n.removeReferencedShader(this)}}else{this._compileError+=`
Not found shader script in ${t}`;return}this._shaderScriptRefId={refId:o.id}}else{const a=this._shaderScriptRefId;if(a){const s=this.root.assetStore.assets[a.refId];s==null||s.removeReferencedShader(this)}this._shaderScriptRefId=void 0}}extractPropertyContent(e,r){let t=0,a=-1,s=-1;const o=r??this._shaderSource;for(let n=0;n<o.length;n++)if(/\W/.test(o[n-1])&&o.substring(n,n+e.length)===e&&(a=n+e.length),!(a<0)){if(o[n]==="{")t++;else if(o[n]==="}"&&--t===0){s=n+1;break}}if(a>=0)return o.substring(a,s+1)}parseMacroItem(e,r){const t=/^\s*?(\[(On|Off)\])?\s*?(\w+)\(\s*?"([\u4e00-\u9fa5_a-zA-Z0-9\s]+)"\s*?(,\s*?(Range\(.+?\)|\w+))?\s*\)(\s*=\s*([^;]+))?/,a=e.match(t);if(a){const[s,o,n,l,h,b,C,R,_]=a;let u;C!=null&&C.trim().startsWith("Range(")?u=x.create(C):u=C??"Null";const p=this._shaderScriptRefId?this.root.assetStore.assets[this._shaderScriptRefId.refId]:void 0,I=this.parsePropertyValueAndUIType(u,!0,_);if(I){const D={prop:l,defaultValue:I.defaultValue,bundleType:"macro",engineType:I.engineType,uiInfo:{label:h,group:r==null?void 0:r.title,...I.uiInfo},macroInfo:{checked:n?n==="On":void 0,switchable:!0,onSwitch:(f,m)=>{var E;const y=m.engineObject.shaderData,M=((E=m.extraData)==null?void 0:E.disabledMacros)??[],F=M.indexOf(l)??-1;f?(y.enableMacro(l),F!==-1&&(M.splice(F,1),this.root.assetFacade.persistAssetMeta(m.id))):(y.disableMacro(l),F===-1&&(M.push(l),m.extraData.disabledMacros=M,this.root.assetFacade.persistAssetMeta(m.id)));const V=p==null?void 0:p.getMacroCallback(l);V&&(V(m.engineObject,f,void 0),m.refreshFormConfig(this.properties,m._getMainData()))}},onChange:async(f,m,y)=>{const M=p==null?void 0:p.getMacroCallback(l);M&&(M(f.engineObject,y,y),f.refreshFormConfig(this.properties,f._getMainData())),f.engineObject.shaderData.enableMacro(l,y)}};this.properties.push(D)}}}parsePropertyItem(e,r,t){const a=/^\s*?(\w+)\(\s*?"([\u4e00-\u9fa5_a-zA-Z0-9\s]+)"\s*?,\s*?(\w+|Range\(.+?\)|Enum\([^()]+\))\s*\)(\s*=\s*([^;]+))?/,o=e.replace(/\/\/.*\n/,"").trim().match(a);if(o){const[n,l,h,b,C,R]=o;let _;b.startsWith("Range(")?_=x.create(b):b.startsWith("Enum(")?_=A.create(b):_=b;const u=this._shaderScriptRefId?this.root.assetStore.assets[this._shaderScriptRefId.refId]:void 0,p=this.parsePropertyValueAndUIType(_,!1,R);p&&this.properties.push({prop:l,defaultValue:p.defaultValue,onChange:async(I,D,f)=>{const m=u==null?void 0:u.getPropertyCallback(D);if(m){let y=f;f!=null&&f.refId&&(y=(await this.root.assetStore.getAssetByRef(f)).engineObject),m(I.engineObject,y),I.refreshFormConfig(this.properties,I._getMainData())}},uiInfo:{label:h,group:t==null?void 0:t.title,collapsible:(t==null?void 0:t.type)==="Collapsible",comments:r,...p.uiInfo},engineType:p.engineType})}}parsePropertyValueAndUIType(e,r,t){if(e instanceof x)return{defaultValue:t?Number(t):void 0,uiInfo:{type:c.Slider,...e},engineType:S.Float};if(e instanceof A)return{defaultValue:t?Number(t):void 0,uiInfo:{type:c.Select,options:e.data},engineType:e.type};const a=s=>{var o;return(o=s.match(/\((.*?)\)/))==null?void 0:o[1]};switch(e){case"Color":return{defaultValue:t?new O(...a(t).split(",").map(Number)):new O,uiInfo:{type:c.Color},engineType:S.Color};case"HDRColor":{const s=a(t).split(",").map(Number);return{defaultValue:t?{r:s[0],g:s[1],b:s[2],a:s[3],intensity:s[4]??Math.max(s[0],s[1],s[2],1)}:{r:0,g:0,b:0,a:1,intensity:1},uiInfo:{type:c.Color,mode:"hdr"},engineType:S.Color}}case"Vector4":return{defaultValue:t?new L(...a(t).split(",").map(Number)):new L,uiInfo:{type:c.Vector4},engineType:S.Vector4};case"Vector3":return{defaultValue:t?new w(...a(t).split(",").map(Number)):new w,uiInfo:{type:c.Vector3},engineType:S.Vector3};case"Vector2":return{defaultValue:t?new N(...a(t).split(",").map(Number)):new N,uiInfo:{type:c.Vector2},engineType:S.Vector2};case"Int":return{defaultValue:t?Number(t):0,uiInfo:{type:c.Number},engineType:S.Integer};case"Float":return{defaultValue:t?Number(t):0,uiInfo:{type:c.Number},engineType:S.Float};case"Texture2D":return{defaultValue:t,uiInfo:{type:c.AssetPicker,assetType:"Texture",customFilter:s=>s.shape!=="Cube"},engineType:S.Texture};case"TextureCube":return{defaultValue:t,uiInfo:{type:c.AssetPicker,assetType:"Texture",customFilter:s=>s.shape==="Cube"},engineType:S.Texture};case"Boolean":return{defaultValue:t==="true",uiInfo:{type:c.Boolean},engineType:S.Boolean};case"Null":return{defaultValue:null,uiInfo:{type:c.Null}};default:throw`not support type ${e}`}}onDoubleClick(){if(this.locked){ee.error("Cannot edit internal Shader");return}const e=me();if(e){const r=te(this);ge(e,this.root.projectStore.id,r);return}re(this.root.projectStore.id,this.id),se()}reCompile(){this.updateCode(this._shaderSource)}updateCode(e){var o;this._shaderSource=e,this._originMainFile=new File([e],this._name);const r=this.isBuiltinShader(),{properties:t}=this;let a;t?(a=Array.from(this.properties),this.properties.length=0):a=[];let s=[];if(r)this.bindEngineObject(j.find(r)),this.properties=pe.filter(n=>n.when?n.when(this.name):!0);else{(o=this.engineObject)==null||o.destroy(!0);const n=j.create(this._shaderSource,ae.GLSLES100,this.includePath);this.bindEngineObject(n),this.parseEditorModule();const l=this.properties;if(!l)s=a;else for(const h of a)l.findIndex(C=>C.prop===h.prop)===-1&&s.push(h)}this.refreshMaterial(s)}destroy(){const e=this.root.assetStore.assets[d.ErrorShaderRefId];for(const r of this._referencedMaterialList)r.bindShaderAsset(e),r.engineObject.shaderData.setColor("material_BaseColor",new O(1,0,1.01,1)),this.root.assetFacade.persistAssetMain(r.id);if(this.properties=null,this._referencedMaterialList=null,this.engineObject&&!this.isBuiltinShader()&&this.engineObject.destroy(!0),this._shaderScriptRefId){const r=this.root.assetStore.assets[this._shaderScriptRefId.refId];if(r){const t=r.referencedShaderList,a=t.findIndex(s=>s.id===this.id);a!==-1&&t.splice(a,1)}}super.destroy()}refreshMaterial(e){for(const r of this._referencedMaterialList)if(!r.engineObject.destroyed){if(e)for(const t of e){const{shaderData:a}=r.engineObject;if(t.bundleType==="macro")a.disableMacro(t.prop);else{const s=ie.getByName(t.prop);t==null||t.onChange(r,t.prop,void 0),ue(r,t.prop,void 0,t.engineType),delete a._propertyValueMap[s._uniqueId]}}r.applyBoundPathChange("shader",c.AssetPicker,this.getCurrentRef()),r.bindShaderAsset(this,r._getMainData()).then(()=>{if(e)for(const t of e)for(const a of this._referencedMaterialList)a[t.prop]=void 0})}}};B(d,"ErrorShaderRefId","0000508");B(d,"_groupRegex",/\b(Header|Collapsible)\s*\(\s*"([\w\s]+)"\s*\)/);B(d,"_scriptRegex",/^\s*UIScript\s+"([\w./]+)"/m);B(d,"_editorModuleRegex",/\bEditor\s*{/);B(d,"_commentsLineRegex",/^\s*\*\s*(.*)?$/);B(d,"_langSpecification",/@language\s+(\w+)/);P([oe()],d.prototype,"builtinShaderName",2);P([ne],d.prototype,"_compileError",2);P([le],d.prototype,"compileError",1);d=P([ce({type:"Shader",label:v("asset.shader.title"),defaultName:"Shader.shader",icon:"shader",extname:"shader",importMenuConfig:{type:de.Add},bundle({content:i}){return{content:new Blob([i],{type:"text/plain; charset=utf-8"})}},customInspector:be})],d);export{xe as E,Ce as S,x as a,A as b,d as c};
