Debian Codegraph @

contrib/toys/follow_mouse.py

raw symbols SCIP
1 """Code by Richard Jones, released into the public domain.
2
3 Inspired by http://screamyguy.net/lines/index.htm
4
5 This code uses a single drawing buffer so that successive drawing passes
6 may be used to create the line fading effect. The fading is achieved
7 by drawing a translucent black quad over the entire scene before drawing
8 the next line segment.
9
10 Note: when working with a single buffer it is always a good idea to
11 glFlush() when you've finished your rendering.
12 """
13
14
15 import sys
16 import random
17
18 import pyglet
19 from pyglet.gl import (
20 glEnable,
21 glBlendFunc,
22 glFlush,
23 Config,
24 GL_BLEND,
25 GL_LINE_SMOOTH,
26 GL_LINES,
27 GL_SRC_ALPHA,
28 GL_ONE_MINUS_SRC_ALPHA,
29 )
30
31 # open a single-buffered window so we can do cheap accumulation
32 config = Config(double_buffer=False)
33 window = pyglet.window.Window(fullscreen='-fs' in sys.argv, config=config)
34
35
36 class Line:
37 batch = pyglet.graphics.Batch()
38 program = pyglet.shapes.get_default_shader()
39 lines = program.vertex_list(100, GL_LINES, batch=batch, colors=('Bn', (255, 255, 255, 255) * 100))
40 black = pyglet.shapes.Rectangle(0, 0, window.width, window.height, color=(0, 0, 0, 32), batch=batch)
41 unallocated = list(range(100))
42 active = []
43
44 mouse_x = mouse_y = 0
45
46 def __init__(self):
47 self.n = self.unallocated.pop()
48 self.active.append(self)
49 self.x = self.lx = random.randint(0, window.width)
50 self.y = self.ly = random.randint(0, window.height)
51 self.dx = random.randint(-70, 70)
52 self.dy = random.randint(-70, 70)
53 self.damping = random.random() * .15 + .8
54 self.power = random.random() * .1 + .05
55
56 def update(self, dt):
57 # calculate my acceleration based on the distance to the mouse
58 # pointer and my acceleration power
59 dx2 = (self.x - self.mouse_x) / self.power
60 dy2 = (self.y - self.mouse_y) / self.power
61
62 # now figure my new velocity
63 self.dx -= dx2 * dt
64 self.dy -= dy2 * dt
65 self.dx *= self.damping
66 self.dy *= self.damping
67
68 # calculate new line endpoints
69 self.lx = self.x
70 self.ly = self.y
71 self.x += self.dx * dt
72 self.y += self.dy * dt
73
74 @classmethod
75 def on_draw(cls):
76 cls.batch.draw()
77 glFlush()
78
79 @classmethod
80 def on_mouse_motion(cls, x, y, dx, dy):
81 cls.mouse_x, cls.mouse_y = x, y
82
83 @classmethod
84 def tick(cls, dt):
85 if len(cls.active) < 50 and random.random() < .1:
86 cls()
87
88 if len(cls.active) > 10 and random.random() < .01:
89 line = cls.active.pop(0)
90 cls.unallocated.append(line.n)
91
92 # update line positions
93 for n, line in enumerate(cls.active):
94 line.update(dt)
95 cls.lines.position[n*4:n*4+4] = [line.lx, line.ly, line.x, line.y]
96
97
98 glEnable(GL_BLEND)
99 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
100 glEnable(GL_LINE_SMOOTH)
101
102
103 pyglet.clock.schedule_interval(Line.tick, 1/30)
104 window.push_handlers(Line)
105
106 pyglet.app.run()