4
$\begingroup$

I can use gpu.shader.from_builtin("2D_UNIFORM_COLOR") to draw a square to a view (the nodeview), and give it a single color, but I want to use a custom shader. Does anyone have an example of POST_VIEW drawing in 2D using vertex_shader and fragment_shader with gpu.types.GPUShader:

vertex_shader = """
    in vec2 pos;

    void main()
    {
        gl_Position = vec4(pos.x, pos.y, 0.0, 1.0);
    }
"""

fragment_shader = """
    void main()
    {
        gl_FragColor = vec4(1.0, 0.8, 0.8, 1.0);
    }
"""
x = 0
y = 0
w = 150
h = 60
background_coords =  [(x, y), (x + w, y), (w + x, y - h), (x, y - h)]
background_indices = [(0, 1, 2), (0, 2, 3)]


shader = gpu.types.GPUShader(vertex_shader, fragment_shader)
# shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
batch = batch_for_shader(shader, 'TRIS', {"pos": background_coords}, indices=background_indices)

shader.bind()
batch.draw(shader)

..which is just about the most basic shader I can come up with.


things i learnt:

  • to get the basic vertex shader working I needed to remove the call to shader.bind() .
  • if your shader gives a message
shader.uniform_float("whatever", ....) not found

it appears to be talking about the constant not being used in the shader, so comment out any shader.uniform_*s that you aren't using.

$\endgroup$

1 Answer 1

2
$\begingroup$

Unlike 3dview, NodeView does not have:

matrix = context.region_data.perspective_matrix

so in the callback one option is to use gpu.matrix.get_projection_matrix(), it looks something like:

def advanced_grid_xy(context, args):

    geom, config = args
    coords, indices = geom.coords, geom.indices

    matrix = gpu.matrix.get_projection_matrix()
    shader = gpu.types.GPUShader(config.grid.vertex_shader, config.grid.fragment_shader)
    batch = batch_for_shader(shader, 'TRIS', {"pos": coords}, indices=indices)

    shader.bind()
    shader.uniform_float("viewProjectionMatrix", matrix)
    ...
    batch.draw(shader)

that works with this vertex_shader

vertex_shader = '''
    in vec2 pos;
    uniform mat4 viewProjectionMatrix;

    void main()
    {
        gl_Position = viewProjectionMatrix * vec4(pos.x, pos.y, 0.0f, 1.0f);
    }

'''

nice.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.