DEV Community

fakelaboratory
fakelaboratory

Posted on • Edited on

Modern GL + Google Colab = triangle animation

Rendered not in my PC image:
Image description
*i mean not this gif here in your browser but in colab cloud?

Link to colab:
https://colab.research.google.com/drive/10Ig1Nqbwqd1lF7HAF0rJuxpZpThgjHcB?usp=sharing

This notebook restored from old(2018) google notebook, with some changes in code. Links to references in comments of the notebook.

!pip install moderngl
!pip install moviepy
import moderngl as gl
import numpy as np
from PIL import Image
import moviepy.editor as mpy

ctx = gl.create_context(standalone=True, backend='egl')
print(ctx.info)
Enter fullscreen mode Exit fullscreen mode
prog = ctx.program(
    vertex_shader="""
        #version 330
        in vec2 in_vert;
        in vec3 in_color;
        out vec3 v_color;
        void main() {
            v_color = in_color;
            gl_Position = vec4(in_vert, 0.0, 1.0);
        }
    """,
    fragment_shader="""
        #version 330
        in vec3 v_color;
        out vec3 f_color;
        void main() {
            f_color = v_color;
        }
    """,
)

vertices = np.asarray([

    -0.75, -0.75,  1, 0, 0,
    0.75, -0.75,  0, 1, 0,
    0.0, 0.649,  0, 0, 1

], dtype='f4')
Enter fullscreen mode Exit fullscreen mode
def render_frame(time):
  vbo = ctx.buffer(vertices.tobytes())
  vao = ctx.vertex_array(prog, vbo, "in_vert", "in_color")

  fbo = ctx.framebuffer(
    color_attachments=[ctx.texture((512, 512), 3)]
  )
  fbo.use()
  fbo.clear(0.0+time, 0.0+time, 0.0+time, 1.0)
  vao.render()

  return np.array(Image.frombytes(
    "RGB", fbo.size, fbo.color_attachments[0].read(),
    "raw", "RGB", 0, -1
  ))
Enter fullscreen mode Exit fullscreen mode
clip = mpy.VideoClip(render_frame, duration=2) # 2 seconds
clip.write_gif("anim.gif",fps=15)
#now in files anim.gif
Enter fullscreen mode Exit fullscreen mode

May the new year bless you with health, wealth, and happiness.
from "65 Happy New Year Wishes for Friends and Family 2024" countryliving article

Top comments (1)

Collapse
 
fakelaboratory profile image
fakelaboratory

OpenGL library:
moderngl.readthedocs.io/en/5.8.2/
Speaking about install:
stackoverflow.com/questions/609000...
Triangle example in docs:
moderngl.readthedocs.io/en/latest/...
Issue about output:
github.com/moderngl/moderngl/issue...
Notebook with GL+collab example:
colab.research.google.com/github/t...