Skip to content

Programming shaders

Hilderin edited this page Nov 12, 2023 · 3 revisions

Shaders are essentials in 3D graphics and are a base feature in MiniEngine. You need a shader to create a pipeline because it will be initialized based on variables used in the shader.

Built-in variables

MiniEngine provides built-in global variables that you (and should) use in your shaders. These variables are automatically initialized and passed to shaders.

Transformations

Name Value Type Access
_matrix_mvp Current model, view, projection matrix. matrix 4x4 push constant

Samplers

Name Value Type Access
_sampler_diffuse Current diffuse texture sampler. If an array, bindless will be used. sampler2D array Uniform

Vertex layout

The vertex layout passed to the vertex shader depend on the internal vertex struct and cannot be customized. Le struct is:

  • position: vector 3
  • texture coordinates: vector 2

In glsl, you should have this in you fragment shader:

layout(location = 0) in vec3 position;
layout(location = 1) in vec2 tex_coord;

Shader exemples

Vertex shader exemple

#version 450

//push constants block
layout( push_constant ) uniform constants
{
	mat4 _matrix_vp;
};

struct object_instance_data
{
    vec3 location;
    vec3 rotation;
    vec3 scale;
    mat4 transform_matrix;
};

struct meshlet_instance_data
{
    uint object_index;
    uint meshlet_index;
    uint texture_index;
};

layout(location = 0) in vec3 position;
layout(location = 1) in vec2 tex_coord;

layout(std430, binding = 2) readonly buffer _objects {
    object_instance_data objects[];
};
layout(std430, binding = 3) readonly buffer _meshlet_instances {
    meshlet_instance_data meshlet_instances[];
};



layout(location = 0) out vec2 frag_tex_coord;
layout(location = 1) flat out uint texture_index;


void main() {
    uint object_index = meshlet_instances[gl_InstanceIndex].object_index;

    gl_Position = _matrix_vp * objects[object_index].transform_matrix * vec4(position, 1.0);
    
    frag_tex_coord = tex_coord;
    texture_index = meshlet_instances[gl_InstanceIndex].texture_index;
}

Fragment shader exemple

#version 450
#extension GL_EXT_nonuniform_qualifier : enable

layout(binding = 1) uniform sampler2D _sampler_diffuse[];

layout(location = 0) in vec2 frag_tex_coord;
layout(location = 1) in flat uint texture_index;

layout(location = 0) out vec4 out_color;




void main() {
    out_color = texture(_sampler_diffuse[texture_index], frag_tex_coord);
}

Clone this wiki locally