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