/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import{copy as e,set as o}from"../core/libs/gl-matrix-2/math/vec2.js";import{create as i}from"../core/libs/gl-matrix-2/factories/vec2f64.js";import{ZEROS as r}from"../core/libs/gl-matrix-2/factories/vec4f64.js";import{RejectBySlice as l}from"../views/3d/webgl-engine/core/shaderLibrary/Slice.glsl.js";import{ObjectAndLayerIdColor as t}from"../views/3d/webgl-engine/core/shaderLibrary/attributes/ObjectAndLayerIdColor.glsl.js";import{AlignPixel as a}from"../views/3d/webgl-engine/core/shaderLibrary/hud/AlignPixel.glsl.js";import{HUD as s}from"../views/3d/webgl-engine/core/shaderLibrary/hud/HUD.glsl.js";import{HUDOcclusionPass as n}from"../views/3d/webgl-engine/core/shaderLibrary/hud/HUDOcclusionPass.glsl.js";import{HUDVisibility as c}from"../views/3d/webgl-engine/core/shaderLibrary/hud/HUDVisibility.glsl.js";import{OutputHighlight as d}from"../views/3d/webgl-engine/core/shaderLibrary/output/OutputHighlight.glsl.js";import{ReadDepth as u}from"../views/3d/webgl-engine/core/shaderLibrary/output/ReadDepth.glsl.js";import{positionOutsideClipSpace as f}from"../views/3d/webgl-engine/core/shaderLibrary/shading/PositionOutsideClipSpace.js";import{VisualVariables as p}from"../views/3d/webgl-engine/core/shaderLibrary/shading/VisualVariables.glsl.js";import{ColorConversion as g}from"../views/3d/webgl-engine/core/shaderLibrary/util/ColorConversion.glsl.js";import{ScreenSizePerspective as m,addScreenSizePerspective as v,addScreenSizePerspectiveAlignment as x}from"../views/3d/webgl-engine/core/shaderLibrary/util/ScreenSizePerspective.glsl.js";import{addPixelRatio as b}from"../views/3d/webgl-engine/core/shaderLibrary/util/View.glsl.js";import{Float2PassUniform as h}from"../views/3d/webgl-engine/core/shaderModules/Float2PassUniform.js";import{Float4BindUniform as w}from"../views/3d/webgl-engine/core/shaderModules/Float4BindUniform.js";import{Float4PassUniform as C}from"../views/3d/webgl-engine/core/shaderModules/Float4PassUniform.js";import{FloatPassUniform as z}from"../views/3d/webgl-engine/core/shaderModules/FloatPassUniform.js";import{If as P,glsl as S}from"../views/3d/webgl-engine/core/shaderModules/glsl.js";import{Texture2DBindUniform as j}from"../views/3d/webgl-engine/core/shaderModules/Texture2DBindUniform.js";import{Texture2DPassUniform as y}from"../views/3d/webgl-engine/core/shaderModules/Texture2DPassUniform.js";import{ShaderBuilder as A}from"../views/webgl/ShaderBuilder.js";import{alphaCutoff as $}from"../webscene/support/AlphaCutoff.js";function O(e){const i=new A;if(i.include(s,e),i.vertex.include(l,e),e.occlusionPass)return i.include(n,e),i;const{output:O,oitPass:B,signedDistanceFieldEnabled:U,visibilityPixelEnabled:T,pixelSnappingEnabled:_,hasEmission:q,hasScreenSizePerspective:H,debugDrawLabelBorder:R,hasVVSize:E,hasVVColor:k,hasRotation:I,occludedFragmentFade:G,sampleSignedDistanceFieldTexelCenter:J}=e;i.include(m),i.include(p,e),i.include(t,e),T&&i.include(c);const{vertex:K,fragment:N}=i;N.include(g),i.varyings.add("vcolor","vec4"),i.varyings.add("vtc","vec2"),i.varyings.add("vsize","vec2");const Q=8===O,W=Q&&T;W&&i.varyings.add("voccluded","float"),K.uniforms.add(new w("viewport",e=>e.camera.fullViewport),new h("screenOffset",(e,i)=>o(L,2*e.screenOffset[0]*i.camera.pixelRatio,2*e.screenOffset[1]*i.camera.pixelRatio)),new h("anchorPosition",e=>F(e)),new C("materialColor",e=>e.color),new z("materialRotation",e=>e.rotation),new y("tex",e=>e.texture)),b(K),U&&(K.uniforms.add(new C("outlineColor",e=>e.outlineColor)),N.uniforms.add(new C("outlineColor",e=>D(e)?e.outlineColor:r),new z("outlineSize",e=>D(e)?e.outlineSize:0))),_&&K.include(a),H&&(v(K),x(K)),R&&i.varyings.add("debugBorderCoords","vec4"),i.attributes.add("uv0","vec2"),i.attributes.add("uvi","vec4"),i.attributes.add("color","vec4"),i.attributes.add("size","vec2"),i.attributes.add("rotation","float"),(E||k)&&i.attributes.add("featureAttribute","vec4"),K.main.add(S`
    ProjectHUDAux projectAux;
    vec4 posProj = projectPositionHUD(projectAux);
    forwardObjectAndLayerIdColor();

    if (rejectBySlice(projectAux.posModel)) {
      gl_Position = ${f};
      return;
    }

    vec2 inputSize;
    ${P(H,S`
        inputSize = screenSizePerspectiveScaleVec2(size, projectAux.absCosAngle, projectAux.distanceToCamera, screenSizePerspective);
        vec2 screenOffsetScaled = screenSizePerspectiveScaleVec2(screenOffset, projectAux.absCosAngle, projectAux.distanceToCamera, screenSizePerspectiveAlignment);`,S`
        inputSize = size;
        vec2 screenOffsetScaled = screenOffset;`)}
    ${P(E,S`inputSize *= vvScale(featureAttribute).xx;`)}

    vec2 combinedSize = inputSize * pixelRatio;
    vec4 quadOffset = vec4(0.0);

    ${P(T,S`
    bool visible = testHUDVisibility(posProj);
    if (!visible) {
      vtc = vec2(0.0);
      ${P(R,"debugBorderCoords = vec4(0.5, 0.5, 1.5 / combinedSize);")}
      return;
    }`)}
    ${P(W,S`voccluded = visible ? 0.0 : 1.0;`)}
  `);const X=S`
      vec2 uv = mix(uvi.xy, uvi.zw, bvec2(uv0));
      vec2 texSize = vec2(textureSize(tex, 0));
      uv = mix(vec2(1.0), uv / texSize, lessThan(uv, vec2(${M})));
      quadOffset.xy = (uv0 - anchorPosition) * 2.0 * combinedSize;

      ${P(I,S`
          float angle = radians(materialRotation + rotation);
          float cosAngle = cos(angle);
          float sinAngle = sin(angle);
          mat2 rotate = mat2(cosAngle, -sinAngle, sinAngle,  cosAngle);

          quadOffset.xy = rotate * quadOffset.xy;
        `)}

      quadOffset.xy = (quadOffset.xy + screenOffsetScaled) / viewport.zw * posProj.w;
  `,Y=_?U?S`posProj = alignToPixelOrigin(posProj, viewport.zw) + quadOffset;`:S`posProj += quadOffset;
if (inputSize.x == size.x) {
posProj = alignToPixelOrigin(posProj, viewport.zw);
}`:S`posProj += quadOffset;`;K.main.add(S`
    ${X}
    ${k?"vcolor = interpolateVVColor(featureAttribute.y) * materialColor;":"vcolor = color / 255.0 * materialColor;"}

    ${P(9===O,S`vcolor.a = 1.0;`)}

    bool alphaDiscard = vcolor.a < ${S.float($)};
    ${P(U,`alphaDiscard = alphaDiscard && outlineColor.a < ${S.float($)};`)}
    if (alphaDiscard) {
      // "early discard" if both symbol color (= fill) and outline color (if applicable) are transparent
      gl_Position = vec4(1e38, 1e38, 1e38, 1.0);
      return;
    } else {
      ${Y}
      gl_Position = posProj;
    }

    vtc = uv;

    ${P(R,S`debugBorderCoords = vec4(uv0, 1.5 / combinedSize);`)}
    vsize = inputSize;
  `),N.uniforms.add(new y("tex",e=>e.texture)),G&&!Q&&(N.include(u),N.uniforms.add(new j("depthMap",e=>e.mainDepth),new z("occludedOpacity",e=>e.occludedFragmentOpacity?.value??1)));const Z=R?S`(isBorder > 0.0 ? 0.0 : ${S.float($)})`:S.float($),ee=S`
    ${P(R,S`float isBorder = float(any(lessThan(debugBorderCoords.xy, debugBorderCoords.zw)) || any(greaterThan(debugBorderCoords.xy, 1.0 - debugBorderCoords.zw)));`)}

    vec2 samplePos = vtc;

    ${P(J,S`
      float txSize = float(textureSize(tex, 0).x);
      float texelSize = 1.0 / txSize;

      // Calculate how much we have to add/subtract to/from each texel to reach the size of an onscreen pixel
      vec2 scaleFactor = (vsize - txSize) * texelSize;
      samplePos += (vec2(1.0, -1.0) * texelSize) * scaleFactor;`)}

    ${U?S`
      vec4 fillPixelColor = vcolor;

      // Get distance in output units (i.e. pixels)

      float sdf = texture(tex, samplePos).r;
      float pixelDistance = sdf * vsize.x;

      // Create smooth transition from the icon into its outline
      float fillAlphaFactor = clamp(0.5 - pixelDistance, 0.0, 1.0);
      fillPixelColor.a *= fillAlphaFactor;

      if (outlineSize > 0.25) {
        vec4 outlinePixelColor = outlineColor;
        float clampedOutlineSize = min(outlineSize, 0.5*vsize.x);

        // Create smooth transition around outline
        float outlineAlphaFactor = clamp(0.5 - (abs(pixelDistance) - 0.5*clampedOutlineSize), 0.0, 1.0);
        outlinePixelColor.a *= outlineAlphaFactor;

        if (
          outlineAlphaFactor + fillAlphaFactor < ${Z} ||
          fillPixelColor.a + outlinePixelColor.a < ${S.float($)}
        ) {
          discard;
        }

        // perform un-premultiplied over operator (see https://en.wikipedia.org/wiki/Alpha_compositing#Description)
        float compositeAlpha = outlinePixelColor.a + fillPixelColor.a * (1.0 - outlinePixelColor.a);
        vec3 compositeColor = vec3(outlinePixelColor) * outlinePixelColor.a +
          vec3(fillPixelColor) * fillPixelColor.a * (1.0 - outlinePixelColor.a);

        ${P(!Q,S`fragColor = vec4(compositeColor, compositeAlpha);`)}
      } else {
        if (fillAlphaFactor < ${Z}) {
          discard;
        }

        ${P(!Q,S`fragColor = premultiplyAlpha(fillPixelColor);`)}
      }

      // visualize SDF:
      // fragColor = vec4(clamp(-pixelDistance/vsize.x*2.0, 0.0, 1.0), clamp(pixelDistance/vsize.x*2.0, 0.0, 1.0), 0.0, 1.0);
      `:S`
          vec4 texColor = texture(tex, samplePos, -0.5);
          if (texColor.a < ${Z}) {
            discard;
          }
          ${P(!Q,S`fragColor = texColor * premultiplyAlpha(vcolor);`)}
          `}

    ${P(G&&!Q,S`
        float zSample = -linearizeDepth(texelFetch(depthMap, ivec2(gl_FragCoord.xy), 0).x);
        float zFragment = -linearizeDepth(gl_FragCoord.z);
        if (zSample < ${S.float(1-V)} * zFragment) {
          fragColor *= occludedOpacity;
        }
        `)}

    ${P(!Q&&R,S`fragColor = mix(fragColor, vec4(1.0, 0.0, 1.0, 1.0), isBorder * 0.5);`)}
  `;switch(O){case 0:i.outputs.add("fragColor","vec4",0),q&&i.outputs.add("fragEmission","vec4",1),1===B&&i.outputs.add("fragAlpha","float",q?2:1),N.main.add(S`
        ${ee}
        ${P(2===B,S`fragColor.rgb /= fragColor.a;`)}
        ${P(q,S`fragEmission = vec4(0.0);`)}
        ${P(1===B,S`fragAlpha = fragColor.a;`)}`);break;case 9:N.main.add(S`
        ${ee}
        outputObjectAndLayerIdColor();`);break;case 8:i.include(d,e),N.main.add(S`
        ${ee}
        outputHighlight(${P(W,S`voccluded == 1.0`,S`false`)});`)}return i}function D(e){return e.outlineColor[3]>0&&e.outlineSize>0}function F(o){return o.textureIsSignedDistanceField?B(o.anchorPosition,o.distanceFieldBoundingBox,L):e(L,o.anchorPosition),L}function B(e,i,r){o(r,e[0]*(i[2]-i[0])+i[0],e[1]*(i[3]-i[1])+i[1])}const L=i(),V=.08,U=32e3,M=S.float(U),T=Object.freeze(Object.defineProperty({__proto__:null,build:O,calculateAnchorPosition:F,fullUV:U},Symbol.toStringTag,{value:"Module"}));export{T as H,O as b,F as c,U as f};
