forked from 1hue/StorageBuffersCompute
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompute_shader.glsl
More file actions
49 lines (40 loc) · 2.47 KB
/
compute_shader.glsl
File metadata and controls
49 lines (40 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright (c) 2025 1hue - MIT License
// https://1hue.dev/storage-buffers-compute-shaders-godot
#[compute]
#version 460
// const float CONSTANT_X : These are compile - time constants. Their value is baked directly into the shader code when it s compiled. They can never change unless you edit the shader and recompile.
// layout (constant_id =...) : This is a specialization constant. Its value can be set when the shader pipeline is created on the CPU. This is more flexible than a compile - time constant
// because you can create different specialized versions of the shader(e.g., one for high - quality and one for low - quality settings) without editing the GLSL code itself.However, once the pipeline is created, its value is fixed.
layout(constant_id = 0) const float CONSTANT_0 = 0.0;
layout(constant_id = 1) const float CONSTANT_1 = 0.0;
layout(local_size_x = 4, local_size_y = 2) in;
// Declare a Shader Storage Buffer (SSBO) named DataStorageBuffer
layout(set = 0, binding = 0, std430) buffer DataStorageBuffer {
// Order here is very important for the right byte offsets outside of the shader
uint counter;
// The 'std430' layout requires 'vec2' to be aligned to an 8-byte boundary.
// Since 'counter' is a 4-byte 'uint', the compiler will automatically insert
// 4 bytes of padding here to ensure 'constants' starts at the correct offset (8).
// We don't need to declare this padding ourselves.
vec2 constants;
float storage_data[];
};
// This declares a PushParams block. Push constants are a very fast, but small, block of memory used to pass data to shaders. They are ideal for frequently changing data.
// They are constant in the sense that they will be the same for every invocation launched by one dispatch command.
// So on the very next frame, or for the very next dispatch command, we can "push" a completely new set of values into that same push_data array.
layout(push_constant, std430) uniform PushParams {
float push_data[8];
};
void main() {
uint idx = gl_LocalInvocationIndex;
uint prev = atomicAdd(counter, 1u);
// Each invocation is uniquely identified by idx and touches only its own corresponding array index
storage_data[idx] = push_data[idx];
// With our persistent storage buffer, the data doesn't disappear until we destroy the buffer ourselves,
// so we could keep adding:
//storage_data[idx] += push_data[idx];
// Only run this on invocation 0, don't need to run it 8 times
if (idx == 0) {
constants = vec2(CONSTANT_0, CONSTANT_1);
}
}