// Copyright 2020 Tencent
// SPDX-License-Identifier: BSD-3-Clause

#version 450

layout (constant_id = 0) const int region_type = 0;
layout (constant_id = 1) const int local_size = 0;
layout (constant_id = 2) const float alpha = 0;
layout (constant_id = 3) const float beta = 0;
layout (constant_id = 4) const float bias_constant = 0;

#define shape_constant_id_offset 5
layout (constant_id = shape_constant_id_offset + 0) const int dims = 0;
layout (constant_id = shape_constant_id_offset + 1) const int w = 0;
layout (constant_id = shape_constant_id_offset + 2) const int h = 0;
layout (constant_id = shape_constant_id_offset + 3) const int c = 0;
layout (constant_id = shape_constant_id_offset + 4) const int cstep = 0;

layout (constant_id = shape_constant_id_offset + 5) const int outdims = 0;
layout (constant_id = shape_constant_id_offset + 6) const int outw = 0;
layout (constant_id = shape_constant_id_offset + 7) const int outh = 0;
layout (constant_id = shape_constant_id_offset + 8) const int outc = 0;
layout (constant_id = shape_constant_id_offset + 9) const int outcstep = 0;

layout (binding = 0) readonly buffer square_workspace { float square_workspace_data[]; };
layout (binding = 1) buffer bottom_top_blob { sfpvec8 bottom_top_blob_data[]; };

layout (push_constant) uniform parameter
{
    int dims;
    int w;
    int h;
    int c;
    int cstep;

    int outdims;
    int outw;
    int outh;
    int outc;
    int outcstep;
} p;

void main()
{
    int gx = int(gl_GlobalInvocationID.x);
    int gy = int(gl_GlobalInvocationID.y);
    int gz = int(gl_GlobalInvocationID.z);

    if (gx >= psc(outw) || gy >= psc(outh) || gz >= psc(outc))
        return;

    // support region_type == 0 only

    mat2x4 sum = mat2x4(0.f);

    ivec4 z4 = gz * 8 + ivec4(0, 1, 2, 3);
    ivec4 zz4 = z4 + 4;
    ivec4 v_offset = z4 * psc(cstep) + gy * psc(w) + gx;
    ivec4 vv_offset = zz4 * psc(cstep) + gy * psc(w) + gx;

    for (int z = 0; z < local_size; z++)
    {
        sum[0].r += square_workspace_data[v_offset.r];
        sum[0].g += square_workspace_data[v_offset.g];
        sum[0].b += square_workspace_data[v_offset.b];
        sum[0].a += square_workspace_data[v_offset.a];
        sum[1].r += square_workspace_data[vv_offset.r];
        sum[1].g += square_workspace_data[vv_offset.g];
        sum[1].b += square_workspace_data[vv_offset.b];
        sum[1].a += square_workspace_data[vv_offset.a];

        v_offset += psc(cstep);
        vv_offset += psc(cstep);
    }

    const float alpha_div_size = alpha / local_size;
    afpvec8 scale;
    scale[0] = afpvec4(pow(bias_constant + alpha_div_size * sum[0], vec4(-beta)));
    scale[1] = afpvec4(pow(bias_constant + alpha_div_size * sum[1], vec4(-beta)));

    int gi = gz * psc(outcstep) + gy * psc(outw) + gx;

    afpvec8 v = buffer_ld8(bottom_top_blob_data, gi);

    v[0] *= scale[0];
    v[1] *= scale[1];

    buffer_st8(bottom_top_blob_data, gi, v);
}
