Debian Codegraph @

experimental/instancing/sprite_instance.py

raw symbols SCIP
1 import pyglet
2 import random
3
4 from pyglet.graphics.instance import InstanceGenerator
5
6 window = pyglet.window.Window(800, 600, vsync=False)
7
8 # Set example resource path.
9 pyglet.resource.path = ['../resources']
10 pyglet.resource.reindex()
11
12 # Load example image from resource path.
13 # Avoid using pyglet.image.load as it creates multiple textures.
14 # Resource will load images into a texture atlas, allowing significantly faster performance.
15 image = pyglet.resource.image("pyglet.png")
16
17 # Anchor point on an image is bottom left corner by default.
18 # Set to center point with anchor properties.
19 image.anchor_x = image.width // 2
20 image.anchor_y = image.height // 2
21
22 # Batching allows rendering groups of objects all at once instead of drawing one by one.
23 batch = pyglet.graphics.Batch()
24
25 scales = [1.0, 0.75, 0.5, 0.25]
26
27 sprites = []
28 # Create 1000 sprites at various scales.
29 sprite = pyglet.sprite.Sprite(image,
30 x=random.randint(0, window.width),
31 y=random.randint(0, window.height),
32 batch=batch)
33
34 instance_generator = InstanceGenerator(sprite, ('translate', 'colors'))
35 instance = instance_generator.create(translate=(100, 50, 0), colors=(255, 255, 255, 255))
36
37 for i in range(1000):
38 sprite_instance = instance_generator.create(
39 translate=(random.randint(0, window.width), random.randint(0, window.height), 0),
40 colors=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 255),
41 )
42
43 # Add sprites to keep in memory, like a list. Otherwise they will get GC'd when out of scope.
44 sprites.append(sprite_instance)
45
46 #fps = pyglet.window.FPSDisplay(window)
47
48 @window.event
49 def on_key_press(symbol, modifiers):
50 if symbol == pyglet.window.key.SPACE:
51 instance.translate = (random.randint(0, window.width), random.randint(0, window.height), 0)
52 # instance.translate[:] = (random.randint(0, window.width), random.randint(0, window.height), 0)
53 elif symbol == pyglet.window.key.DELETE:
54 del_instance = instance_sprite.pop()
55 sprites.remove(del_instance)
56 elif symbol == pyglet.window.key.INSERT:
57 sprite_instance = instance_sprite.create(
58 translate=(random.randint(0, window.width), random.randint(0, window.height), 0),
59 colors=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 255),
60 )
61 sprites.append(sprite_instance)
62
63 @window.event
64 def on_draw():
65 window.clear()
66 batch.draw()
67 #fps.draw()
68
69
70 pyglet.app.run(0)