Skip to content

Commit

Permalink
update some moderngl window examples
Browse files Browse the repository at this point in the history
  • Loading branch information
szabolcsdombi committed Jul 1, 2024
1 parent 580fc59 commit 43b0d1f
Show file tree
Hide file tree
Showing 3 changed files with 291 additions and 0 deletions.
114 changes: 114 additions & 0 deletions examples/moderngl_window_empty.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import os

import math
import moderngl_window as mglw


class Example(mglw.WindowConfig):
title = "ModernGL Window"
resizable = False
gl_version = (3, 3)
window_size = (800, 800)
aspect_ratio = 1.0
resource_dir = os.path.normpath(os.path.join(__file__, '../data'))

def __init__(self, **kwargs):
super().__init__(**kwargs)

def render(self, time: float, frame_time: float):
self.ctx.clear(
(math.sin(time) + 1.0) / 2,
(math.sin(time + 2) + 1.0) / 2,
(math.sin(time + 3) + 1.0) / 2,
)

def resize(self, width: int, heigh: int):
"""
Pick window resizes in case we need yo update
internal states when this happens.
"""
print("Window resized to", width, heigh)

def iconify(self, iconify: bool):
"""Window hide/minimize and restore"""
print("Window was iconified:", iconify)

def key_event(self, key, action, modifiers):
keys = self.wnd.keys

# Key presses
if action == keys.ACTION_PRESS:
if key == keys.SPACE:
print("SPACE key was pressed")

# Using modifiers (shift and ctrl)

if key == keys.Z and modifiers.shift:
print("Shift + Z was pressed")

if key == keys.Z and modifiers.ctrl:
print("ctrl + Z was pressed")

# Key releases
elif action == self.wnd.keys.ACTION_RELEASE:
if key == keys.SPACE:
print("SPACE key was released")

if action == keys.ACTION_PRESS:
# Move the window around with AWSD
if key == keys.A:
self.wnd.position = self.wnd.position[0] - 20, self.wnd.position[1]
if key == keys.D:
self.wnd.position = self.wnd.position[0] + 20, self.wnd.position[1]
if key == keys.W:
self.wnd.position = self.wnd.position[0], self.wnd.position[1] - 20
if key == keys.S:
self.wnd.position = self.wnd.position[0], self.wnd.position[1] + 20

# Resize window around with Shift + AWSD
if self.wnd.modifiers.shift and key == keys.A:
self.wnd.size = self.wnd.size[0] - 50, self.wnd.size[1]
if self.wnd.modifiers.shift and key == keys.D:
self.wnd.size = self.wnd.size[0] + 50, self.wnd.size[1]
if self.wnd.modifiers.shift and key == keys.W:
self.wnd.size = self.wnd.size[0], self.wnd.size[1] - 50
if self.wnd.modifiers.shift and key == keys.S:
self.wnd.size = self.wnd.size[0], self.wnd.size[1] + 50

# toggle cursor
if key == keys.C:
self.wnd.cursor = not self.wnd.cursor

# Shuffle window title
if key == keys.T:
title = list(self.wnd.title)
random.shuffle(title)
self.wnd.title = ''.join(title)

# Toggle mouse exclusivity
if key == keys.M:
self.wnd.mouse_exclusivity = not self.wnd.mouse_exclusivity

def mouse_position_event(self, x, y, dx, dy):
print("Mouse position pos={} {} delta={} {}".format(x, y, dx, dy))

def mouse_drag_event(self, x, y, dx, dy):
print("Mouse drag pos={} {} delta={} {}".format(x, y, dx, dy))

def mouse_scroll_event(self, x_offset, y_offet):
print("mouse_scroll_event", x_offset, y_offet)

def mouse_press_event(self, x, y, button):
print("Mouse button {} pressed at {}, {}".format(button, x, y))
print("Mouse states:", self.wnd.mouse_states)

def mouse_release_event(self, x: int, y: int, button: int):
print("Mouse button {} released at {}, {}".format(button, x, y))
print("Mouse states:", self.wnd.mouse_states)

def unicode_char_entered(self, char):
print("unicode_char_entered:", char)


if __name__ == '__main__':
Example.run()
84 changes: 84 additions & 0 deletions examples/moderngl_window_fractal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import os

import glm
import moderngl
import moderngl_window as mglw


class Example(mglw.WindowConfig):
title = 'Resource Loading with ModernGL Window'
resizable = False
gl_version = (3, 3)
window_size = (800, 800)
aspect_ratio = 1.0
resource_dir = os.path.normpath(os.path.join(__file__, '../data'))

def __init__(self, **kwargs):
super().__init__(**kwargs)

self.program = self.ctx.program(
vertex_shader='''
#version 330 core
vec2 positions[3] = vec2[](
vec2(-1.0, -1.0),
vec2(3.0, -1.0),
vec2(-1.0, 3.0)
);
out vec2 v_uv;
void main() {
gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0);
v_uv = positions[gl_VertexID];
}
''',
fragment_shader='''
#version 330
in vec2 v_uv;
out vec4 f_color;
uniform sampler2D Texture;
uniform vec2 seed;
uniform int iter;
void main() {
vec2 c = seed;
int i;
vec2 z = v_uv * vec2(2.0, 2.0);
for (i = 0; i < iter; i++) {
float x = (z.x * z.x - z.y * z.y) + c.x;
float y = (z.y * z.x + z.x * z.y) + c.y;
if ((x * x + y * y) > 4.0) {
break;
}
z.x = x;
z.y = y;
}
f_color = texture(Texture, vec2((i == iter ? 0.0 : float(i)) / 100.0, 0.0));
}
''',
)

self.texture = self.load_texture_2d('pal.png')
self.sampler = self.ctx.sampler(texture=self.texture)
self.vao = self.ctx.vertex_array(self.program, [])
self.vao.vertices = 3

def render(self, time, frame_time):
self.ctx.clear()
self.program['seed'] = (-0.8, 0.156)
self.program['iter'] = 100
self.sampler.use()
self.vao.render()


if __name__ == '__main__':
Example.run()
93 changes: 93 additions & 0 deletions examples/moderngl_window_resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import os

import glm
import moderngl
import moderngl_window as mglw


class Example(mglw.WindowConfig):
title = 'Resource Loading with ModernGL Window'
resizable = False
gl_version = (3, 3)
window_size = (800, 800)
aspect_ratio = 1.0
resource_dir = os.path.normpath(os.path.join(__file__, '../data'))

def __init__(self, **kwargs):
super().__init__(**kwargs)

self.obj = self.load_scene('sitting_dummy.obj')
self.texture = self.load_texture_2d('wood.jpg')

self.program = self.ctx.program(
vertex_shader='''
#version 330
uniform mat4 Mvp;
in vec3 in_position;
in vec3 in_normal;
in vec2 in_texcoord_0;
out vec3 v_vert;
out vec3 v_norm;
out vec2 v_text;
void main() {
v_vert = in_position;
v_norm = in_normal;
v_text = in_texcoord_0;
gl_Position = Mvp * vec4(in_position, 1.0);
}
''',
fragment_shader='''
#version 330
uniform sampler2D Texture;
uniform vec4 Color;
uniform vec3 Light;
in vec3 v_vert;
in vec3 v_norm;
in vec2 v_text;
out vec4 f_color;
void main() {
float lum = dot(normalize(v_norm), normalize(v_vert - Light));
lum = acos(lum) / 3.14159265;
lum = clamp(lum, 0.0, 1.0);
lum = lum * lum;
lum = smoothstep(0.0, 1.0, lum);
lum *= smoothstep(0.0, 80.0, v_vert.z) * 0.3 + 0.7;
lum = lum * 0.8 + 0.2;
vec3 color = texture(Texture, v_text).rgb;
color = color * (1.0 - Color.a) + Color.rgb * Color.a;
f_color = vec4(color * lum, 1.0);
}
''',
)

# Create a vao from the first root node (attribs are auto mapped)
self.vao = self.obj.root_nodes[0].mesh.vao.instance(self.program)

def camera_matrix(self):
proj = glm.perspective(45.0, self.aspect_ratio, 0.1, 1000.0)
look = glm.lookAt((-85.0, -180.0, 140.0), (0.0, 0.0, 65.0), (0.0, 0.0, 1.0))
return proj * look

def render(self, time, frame_time):
self.ctx.clear(1.0, 1.0, 1.0)
self.ctx.enable(moderngl.DEPTH_TEST)

self.program['Light'] = (-140.0, -300.0, 350.0)
self.program['Color'] = (1.0, 1.0, 1.0, 0.25)
self.program['Mvp'].write(self.camera_matrix())

self.texture.use()
self.vao.render()


if __name__ == '__main__':
Example.run()

0 comments on commit 43b0d1f

Please sign in to comment.