import { Vec4, gfx, postProcess, renderer, rendering } from "cc";
import { MotionBlurSetting } from "./MotionBlurSetting";

export class MotionBlurPass extends postProcess.SettingPass {
    // custom pass name
    name = 'CustomPass'

    // out out slot name
    outputNames: string[] = ['CustomPassColor']

    // reference to post process setting
    get setting() {
        return this.getSetting(MotionBlurSetting);
    }

    // Whether the pass should rendered
    checkEnable(camera: renderer.scene.Camera): boolean {
        let setting = this.setting;
        return setting.material && super.checkEnable(camera);
    }

    params = new Vec4

    render(camera: renderer.scene.Camera, ppl: rendering.Pipeline) {
        const cameraID = this.getCameraUniqueID(camera);

        // clear background to black color
        const context = this.context;
        context.clearBlack()

        // input name from last pass's output slot 0
        const input0 = this.lastPass.slotName(camera, 0);
        // output slot 0 name
        const output = this.slotName(camera, 0);

        // get depth slot name
        const depth = context.depthSlotName;

        // also can get depth slot name from forward pass.
        // let forwardPass = builder.getPass(ForwardPass);
        // depth = forwardPass.slotName(camera, 1);

        // set setting value to material
        const setting = this.setting;
        // this.params.x = setting.blueIntensity
        // this.params.y = setting.showDepth ? 1 : 0;
        // this.params.z = setting.depthRange;
        // setting.material.setProperty('params', this.params);

        context.material = setting.material;
        context
            // update view port
            .updatePassViewPort()
            // add a render pass
            .addRenderPass('post-process', `${this.name}${cameraID}`)
            // set inputs
            .setPassInput(input0, 'inputTexture')
            .setPassInput(depth, 'depthTexture')
            // set outputs
            .addRasterView(output, gfx.Format.RGBA8)
            // final render
            .blitScreen(0)
            // calculate a version
            .version();
    }
}

let builder = rendering.getCustomPipeline('Custom') as postProcess.PostProcessBuilder;
if (builder) {
    // insert CustomPass after a BlitScreenPass
    builder.insertPass(new MotionBlurPass(), postProcess.BlitScreenPass);
}