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

#version 450

#extension GL_GOOGLE_include_directive: enable
#include "vulkan_activation.comp"

layout (constant_id = 0) const int bias_term = 0;
layout (constant_id = 1) const int activation_type = 0;
layout (constant_id = 2) const float activation_param_0 = 0;
layout (constant_id = 3) const float activation_param_1 = 0;

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

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

layout (binding = 0) readonly buffer bottom_blob { sfpvec4 bottom_blob_data[]; };
layout (binding = 1) writeonly buffer top_blob { sfpvec4 top_blob_data[]; };
layout (binding = 2) readonly buffer weight_blob { sfp weight_data[]; };
layout (binding = 3) readonly buffer bias_blob { sfp bias_data[]; };

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

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

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

    if (gx * 4 >= psc(outcstep) || gy >= psc(outc))
        return;

    afpvec4 sum;

    if (bias_term == 1)
    {
        sum = afpvec4(buffer_ld1(bias_data, gy));
    }
    else
    {
        sum = afpvec4(0.f);
    }

    int w_offset = gy * psc(c);
    int v_offset = gx;

    for (int z = 0; z < psc(c); z++)
    {
        sum += buffer_ld1(weight_data, w_offset) * buffer_ld4(bottom_blob_data, v_offset);

        w_offset += 1;
        v_offset += psc(cstep) / 4;
    }

    sum = activation_afpvec4(sum, activation_type, activation_param_0, activation_param_1);

    const int gi = gy * psc(outcstep) / 4 + gx;

    buffer_st4(top_blob_data, gi, sum);
}
