gpu_particle_burst_02.py Full Listing#
gpu_particle_burst_02.py#
1"""
2Example showing how to create particle explosions via the GPU.
3"""
4from array import array
5from dataclasses import dataclass
6import arcade
7import arcade.gl
8
9SCREEN_WIDTH = 1024
10SCREEN_HEIGHT = 768
11SCREEN_TITLE = "GPU Particle Explosion"
12
13
14@dataclass
15class Burst:
16 """ Track for each burst. """
17 buffer: arcade.gl.Buffer
18 vao: arcade.gl.Geometry
19
20
21class MyWindow(arcade.Window):
22 """ Main window"""
23 def __init__(self):
24 super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
25 self.burst_list = []
26
27 # Program to visualize the points
28 self.program = self.ctx.load_program(
29 vertex_shader="vertex_shader_v1.glsl",
30 fragment_shader="fragment_shader.glsl",
31 )
32
33 self.ctx.enable_only()
34
35 def on_draw(self):
36 """ Draw everything """
37 self.clear()
38
39 # Set the particle size
40 self.ctx.point_size = 2 * self.get_pixel_ratio()
41
42 # Loop through each burst
43 for burst in self.burst_list:
44
45 # Render the burst
46 burst.vao.render(self.program, mode=self.ctx.POINTS)
47
48 def on_update(self, dt):
49 """ Update everything """
50 pass
51
52 def on_mouse_press(self, x: float, y: float, button: int, modifiers: int):
53 """ User clicks mouse """
54
55 def _gen_initial_data(initial_x, initial_y):
56 """ Generate data for each particle """
57 yield initial_x
58 yield initial_y
59
60 # Recalculate the coordinates from pixels to the OpenGL system with
61 # 0, 0 at the center.
62 x2 = x / self.width * 2. - 1.
63 y2 = y / self.height * 2. - 1.
64
65 # Get initial particle data
66 initial_data = _gen_initial_data(x2, y2)
67
68 # Create a buffer with that data
69 buffer = self.ctx.buffer(data=array('f', initial_data))
70
71 # Create a buffer description that says how the buffer data is formatted.
72 buffer_description = arcade.gl.BufferDescription(buffer,
73 '2f',
74 ['in_pos'])
75 # Create our Vertex Attribute Object
76 vao = self.ctx.geometry([buffer_description])
77
78 # Create the Burst object and add it to the list of bursts
79 burst = Burst(buffer=buffer, vao=vao)
80 self.burst_list.append(burst)
81
82
83if __name__ == "__main__":
84 window = MyWindow()
85 window.center_window()
86 arcade.run()