Skip to content

Instantly share code, notes, and snippets.

@pvcraven
Last active March 28, 2020 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvcraven/fd8a7492e4e67f9c75dfeb66954acaca to your computer and use it in GitHub Desktop.
Save pvcraven/fd8a7492e4e67f9c75dfeb66954acaca to your computer and use it in GitHub Desktop.
Modern GL and frame buffer work
import numpy as np
import moderngl
from moderngl_window import geometry
from ported._example import Example
from pathlib import Path
import os
class SimpleColorTriangle(Example):
gl_version = (3, 3)
aspect_ratio = 16 / 9
title = "Simple Color Triangle"
resource_dir = os.path.dirname(os.path.abspath(__file__))
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.prog = self.ctx.program(
vertex_shader='''
#version 330
in vec2 in_vert;
in vec3 in_color;
out vec3 v_color; // Goes to the fragment shader
void main() {
gl_Position = vec4(in_vert, 0.0, 1.0);
v_color = in_color;
}
''',
fragment_shader='''
#version 330
in vec3 v_color;
out vec4 f_color;
void main() {
// We're not interested in changing the alpha value
f_color = vec4(v_color, 1.0);
}
''',
)
# Point coordinates are put followed by the vec3 color values
vertices = np.array([
# x, y, red, green, blue
0.0, 0.8, 1.0, 0.0, 0.0,
-0.6, -0.8, 0.0, 1.0, 0.0,
0.6, -0.8, 0.0, 0.0, 1.0,
], dtype='f4')
self.vbo = self.ctx.buffer(vertices)
# We control the 'in_vert' and `in_color' variables
self.vao = self.ctx.vertex_array(
self.prog,
[
# Map in_vert to the first 2 floats
# Map in_color to the next 3 floats
(self.vbo, '2f 3f', 'in_vert', 'in_color')
],
)
self.offscreen_color = self.ctx.texture(self.wnd.buffer_size, 4)
self.offscreen = self.ctx.framebuffer(color_attachments=[self.offscreen_color])
self.texture_prog = self.load_program('texture.glsl')
self.quad_fs = geometry.quad_fs()
def render(self, time: float, frame_time: float):
self.offscreen.use()
self.offscreen.clear(1.0, 1.0, 1.0)
self.vao.render()
self.wnd.use()
self.offscreen_color.use(location=0)
self.quad_fs.render(self.texture_prog)
if __name__ == '__main__':
SimpleColorTriangle.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment