"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module WebGL
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createScreenSpaceEffectProgramBuilder = createScreenSpaceEffectProgramBuilder;
const RenderFlags_1 = require("../RenderFlags");
const AttributeMap_1 = require("../AttributeMap");
const ShaderBuilder_1 = require("../ShaderBuilder");
const Fragment_1 = require("./Fragment");
const computePosition = `
  effectMain(rawPos);
  return rawPos;
`;
const textureCoordFromPosition = `
  vec2 textureCoordFromPosition(vec4 pos) {
    return (pos.xy + 1.0) * 0.5;
  }
`;
const computeBaseColor = "  return effectMain();";
const computeBaseColorWithShift = `
  return u_readingPixels ? sampleSourcePixel() : effectMain();
`;
/** @internal */
function createScreenSpaceEffectProgramBuilder(params) {
    const builder = new ShaderBuilder_1.ProgramBuilder(AttributeMap_1.AttributeMap.findAttributeMap(undefined, false));
    if (params.textureCoordFromPosition)
        builder.vert.addFunction(textureCoordFromPosition);
    builder.vert.addFunction(params.source.vertex);
    builder.vert.set(10 /* VertexShaderComponent.ComputePosition */, computePosition);
    if (params.source.sampleSourcePixel)
        builder.frag.addFunction("vec4 sampleSourcePixel()", params.source.sampleSourcePixel);
    builder.frag.addFunction(params.source.fragment);
    builder.addUniform("u_diffuse", 8 /* VariableType.Sampler2D */, (prog) => {
        prog.addProgramUniform("u_diffuse", (uniform, progParams) => {
            const texture = progParams.target.compositor.screenSpaceEffectFbo.getColor(0);
            texture.bindSampler(uniform, RenderFlags_1.TextureUnit.Zero);
        });
    });
    builder.frag.set(18 /* FragmentShaderComponent.AssignFragData */, Fragment_1.assignFragColor);
    if (!params.source.sampleSourcePixel) {
        builder.frag.set(1 /* FragmentShaderComponent.ComputeBaseColor */, computeBaseColor);
    }
    else {
        builder.frag.set(1 /* FragmentShaderComponent.ComputeBaseColor */, computeBaseColorWithShift);
        builder.frag.addUniform("u_readingPixels", 0 /* VariableType.Boolean */, (prog) => {
            prog.addProgramUniform("u_readingPixels", (uniform, progParams) => {
                uniform.setUniform1i(progParams.target.isReadPixelsInProgress ? 1 : 0);
            });
        });
    }
    return builder;
}
//# sourceMappingURL=ScreenSpaceEffect.js.map