Étirement de la vidéo de la kinect.
[minwii.git] / src / minwii / widgets / playingscreen.py
1 # -*- coding: utf-8 -*-
2 """
3 Écran de jeu MinWii :
4 bandes arc-en-ciel représentant un clavier.
5
6 $Id$
7 $URL$
8 """
9 import pygame
10 import types
11
12 import kinect.pygamedisplay as kinect
13
14 import minwii.events as events
15 from minwii.log import eventLogger
16 from minwii.eventutils import event_handler, EventDispatcher, EventHandlerMixin
17 from minwii.musicxml import Tone
18 from minwii.config import FRAMERATE
19 from minwii.config import FIRST_HUE
20 from minwii.config import MIDI_VELOCITY_RANGE
21 from minwii.config import MIDI_PAN_RANGE
22 from minwii.config import MIDI_VELOCITY_WRONG_NOTE_ATTN
23 from minwii.config import SCREEN_RESOLUTION
24 from minwii.globals import BACKGROUND_LAYER
25 from minwii.globals import CURSOR_LAYER
26 from minwii.globals import PLAYING_MODES_DICT
27
28 from cursors import WarpingCursor
29 from column import Column
30
31 class PlayingScreenBase(pygame.sprite.LayeredDirty, EventHandlerMixin) :
32
33 def __init__(self, synth, distinctNotes=[], displayNotes=True) :
34 """
35 distinctNotes : notes disctinctes présentes dans la chanson
36 triées du plus grave au plus aigu.
37 """
38 super(PlayingScreenBase, self).__init__()
39 self.synth = synth
40 self.distinctNotes = distinctNotes
41 self.displayNotes = displayNotes
42 self.keyboardLength = 0
43 self.keyboardRects = []
44 self.cursor = None
45 self._initRects()
46 self.columns = {}
47 self._initColumns()
48 self._running = False
49 self.kinectRgb = kinect.RGBSprite(alpha=128, size=SCREEN_RESOLUTION)
50 self.add(self.kinectRgb, layer=CURSOR_LAYER)
51 self._initCursor()
52
53
54 def _initRects(self) :
55 """ création des espaces réservés pour
56 afficher les colonnes.
57 """
58 self.keyboardLength = len(self.distinctNotes)
59
60 screen = pygame.display.get_surface()
61
62 self.dispWidth = dispWidth = screen.get_width()
63 self.dispHeight = dispHeight = screen.get_height()
64
65 columnWidth = int(round(float(dispWidth) / self.keyboardLength))
66
67 rects = []
68 for i in range(self.keyboardLength - 1) :
69 upperLeftCorner = (i*columnWidth, 0)
70 rect = pygame.Rect(upperLeftCorner, (columnWidth, dispHeight))
71 rects.append(rect)
72
73 # la dernière colonne à la largeur du reste
74 upperLeftCorner = ((i+1) * columnWidth, 0)
75 rect = pygame.Rect(upperLeftCorner, (dispWidth - (self.keyboardLength - 1) * columnWidth , dispHeight))
76 rects.append(rect)
77
78 self.keyboardRects = rects
79
80 def _initColumns(self) :
81
82 hueStep = FIRST_HUE / (self.keyboardLength - 1)
83 for i, rect in enumerate(self.keyboardRects) :
84 hue = FIRST_HUE - hueStep * i
85 tone = self.distinctNotes[i]
86 c = Column(self, i, hue, rect, tone, displayNote=self.displayNotes)
87 self.add(c, layer=BACKGROUND_LAYER)
88 self.columns[tone.midi] = c
89
90
91 def _initCursor(self) :
92 self.cursor = WarpingCursor(blinkMode=True)
93 self.add(self.cursor, layer=CURSOR_LAYER)
94
95 def run(self):
96 self._running = True
97 clock = pygame.time.Clock()
98 pygame.display.flip()
99 pygame.mouse.set_visible(False)
100 while self._running :
101 EventDispatcher.dispatchEvents()
102 self.kinectRgb.update()
103 dirty = self.draw(pygame.display.get_surface())
104 pygame.display.update(dirty)
105 clock.tick(FRAMERATE)
106
107 def stop(self) :
108 self._running = False
109 self.synth.system_reset()
110 pygame.mouse.set_visible(True)
111 self.cursor._stopBlink()
112
113 @event_handler(pygame.KEYDOWN)
114 def handleKeyDown(self, event) :
115 if event.key in (pygame.K_q, pygame.K_ESCAPE) or \
116 event.unicode == u'q' :
117 self.stop()
118
119 @event_handler(pygame.MOUSEBUTTONDOWN)
120 def onMouseDown(self, event) :
121 # TODO à cleaner : on vire le dernier élément
122 # parce qu'il s'agit du curseur
123 for col in reversed(self.sprites()[:-1]) :
124 if col.rect.collidepoint(*event.pos):
125 self.raiseColDown(col, event)
126 break
127
128 @event_handler(pygame.MOUSEBUTTONUP)
129 def onMouseUp(self, event) :
130 for col in reversed(self.sprites()[:-1]) :
131 if col.rect.collidepoint(*event.pos) :
132 self.raiseColUp(col, event)
133 break
134
135 @event_handler(pygame.MOUSEMOTION)
136 def onMouseMove(self, event) :
137 for col in reversed(self.sprites()[:-1]) :
138 if col.rect.collidepoint(*event.pos) :
139 self.raiseColOver(col, event)
140 break
141
142 def raiseColDown(self, col, mouseEvent) :
143 evt = pygame.event.Event(events.COLDOWN, column=col, pos=mouseEvent.pos)
144 pygame.event.post(evt)
145
146 def raiseColUp(self, col, mouseEvent) :
147 evt = pygame.event.Event(events.COLUP, column=col, pos=mouseEvent.pos)
148 pygame.event.post(evt)
149
150 def raiseColOver(self, col, mouseEvent) :
151 evt = pygame.event.Event(events.COLOVER, column=col, pos=mouseEvent.pos, mouseEvent=mouseEvent)
152 pygame.event.post(evt)
153
154 def getVelocity(self, pos) :
155 vel = (float(self.dispWidth) - pos[1]) / self.dispWidth
156 vel = int(vel * (MIDI_VELOCITY_RANGE[1] - MIDI_VELOCITY_RANGE[0])) + MIDI_VELOCITY_RANGE[0]
157 return vel
158
159 def getPan(self, index) :
160 pan = float(index) / (self.keyboardLength -1)
161 pan = int(pan * (MIDI_PAN_RANGE[1] - MIDI_PAN_RANGE[0])) + MIDI_PAN_RANGE[0]
162 return pan
163
164 def playnote(self, col, pos, vel=None) :
165 pan = self.getPan(col.index)
166 self.synth.cc(0, 10, pan)
167 vel = vel or self.getVelocity(pos)
168 self.synth.noteon(0, col.tone.midi, vel)
169
170 class PlayingScreen(PlayingScreenBase) :
171 "fenêtre de jeu pour improvisation"
172
173 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
174
175 def __init__(self, synth, displayNotes=True) :
176 distinctNotes = []
177 self.currentColumn = None
178 for midi in self.scale :
179 tone = Tone(midi)
180 distinctNotes.append(tone)
181
182 super(PlayingScreen, self).__init__(synth, distinctNotes, displayNotes=displayNotes)
183
184 @event_handler(events.COLDOWN)
185 def noteon(self, event) :
186 col = event.column
187 col.update(True)
188 self.currentColumn = col
189 self.playnote(col, event.pos)
190
191 @event_handler(events.COLUP)
192 def noteoff(self, event) :
193 if self.currentColumn :
194 self.currentColumn.update(False)
195 self.synth.noteoff(0, self.currentColumn.tone.midi)
196
197
198 class SongPlayingScreen(PlayingScreenBase) :
199
200 def __init__(self, synth, song, mode=PLAYING_MODES_DICT['NORMAL'], displayNotes=True, tempoTrim=0) :
201 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes, displayNotes=displayNotes)
202 self.song = song
203 self.quarterNoteDuration = song.quarterNoteDuration
204 self.tempoTrim = tempoTrim
205 self.currentColumn = None
206 self.noteIterator = self.song.iterNotes()
207 self.displayNext()
208 self._plugListeners(mode)
209
210 def _plugListeners(self, mode) :
211 "initialisation des gestionnaires d'événements en fonction du mode"
212
213 if mode == PLAYING_MODES_DICT['BEGINNER'] :
214 EventDispatcher.addEventListener(events.COLOVER, self.handleBeginnerColumnOver)
215
216 elif mode == PLAYING_MODES_DICT['EASY'] :
217 EventDispatcher.addEventListener(events.COLDOWN, self.handleEasyColumnDown)
218 EventDispatcher.addEventListener(events.COLOVER, self.handleEasyColumnOver)
219
220 elif mode == PLAYING_MODES_DICT['NORMAL'] :
221 EventDispatcher.addEventListener(events.COLOVER, self.handleNormalColumnOver)
222 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
223 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
224
225 elif mode == PLAYING_MODES_DICT['ADVANCED'] :
226 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
227 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
228
229 elif mode == PLAYING_MODES_DICT['EXPERT'] :
230 EventDispatcher.addEventListener(events.COLDOWN, self.handleExpertColumnDown)
231 EventDispatcher.addEventListener(events.COLUP, self.handleExpertColumnUp)
232
233
234 # --- HID listeners ---
235 def handleBeginnerColumnOver(self, event) :
236 col = event.column
237 if col.state and not self.currentNotePlayed :
238 self.playnote(col, event.pos)
239 self.setNoteTimeout()
240 self.currentNotePlayed = True
241
242 def handleEasyColumnOver(self, event) :
243 col = event.column
244 if col.state and \
245 self.cursor.pressed and \
246 not self.currentNotePlayed :
247 self.playnote(col, event.pos)
248 self.setNoteTimeout()
249 self.currentNotePlayed = True
250
251
252 def handleNormalColumnOver(self, event) :
253 col = event.column
254 if col.state and \
255 self.cursor.pressed and \
256 not self.currentNotePlayed :
257 self.playnote(col, event.pos)
258 self.currentNotePlayed = True
259
260 def handleColumnDown(self, event) :
261 col = event.column
262 if col.state:
263 self.playnote(col, event.pos)
264 self.currentNotePlayed = True
265
266 def handleEasyColumnDown(self, event) :
267 col = event.column
268 if col.state and \
269 not self.currentNotePlayed :
270 self.playnote(col, event.pos)
271 self.setNoteTimeout()
272 self.currentNotePlayed = True
273
274
275 def handleExpertColumnDown(self, event) :
276 col = event.column
277 if col.state :
278 self.playnote(col, event.pos)
279 self.currentNotePlayed = True
280 else :
281 vel = self.getVelocity(event.pos) * MIDI_VELOCITY_WRONG_NOTE_ATTN
282 vel = int(vel)
283 self.playnote(col, event.pos, vel=vel)
284 self.alternateColumn = col
285 self.currentNotePlayed = False
286
287 def handleColumnUp(self, event) :
288 if self.currentNotePlayed :
289 self.synth.noteoff(0, self.currentColumn.tone.midi)
290 self.displayNext()
291
292 def handleExpertColumnUp(self, event) :
293 if self.currentNotePlayed :
294 self.synth.noteoff(0, self.currentColumn.tone.midi)
295 self.displayNext()
296 else :
297 self.synth.noteoff(0, self.alternateColumn.tone.midi)
298
299 # --- End HID listeners ---
300
301
302 def displayNext(self, event=None) :
303 if self.currentColumn:
304 self.currentColumn.update(False)
305 try :
306 note, verseIndex = self.noteIterator.next()
307 except StopIteration :
308 self.noteIterator = self.song.iterNotes()
309 note, verseIndex = self.noteIterator.next()
310 eventLogger.info(pygame.event.Event(events.SONGEND))
311 try :
312 syllabus = note.lyrics[verseIndex].syllabus()
313 except IndexError :
314 syllabus = u'…'
315
316 column = self.columns[note.midi]
317 column.update(True, syllabus)
318 self.currentColumn = column
319 self.currentNote = note
320 self.currentNotePlayed = False
321
322 @event_handler(events.NOTEEND)
323 def clearTimeOutAndDisplayNext(self, evt) :
324 pygame.time.set_timer(evt.type, 0)
325 self.synth.noteoff(0, self.currentNote.midi)
326 self.displayNext()
327
328 def setNoteTimeout(self) :
329 delay = self.currentNote.duration * self.quarterNoteDuration
330 delay = delay + delay * self.tempoTrim
331 delay = int(delay)
332 if delay < 1 :
333 delay = 1 # durée minimale, car 0 désactiverait le timer.
334 pygame.time.set_timer(events.NOTEEND, delay)
335
336 def tempoTrimUp(self, step=0.1) :
337 self.tempoTrim = round(self.tempoTrim - step, 1)
338
339 def tempoTrimDown(self, step=0.1) :
340 self.tempoTrim = round(self.tempoTrim + step, 1)
341
342 def stop(self) :
343 pygame.time.set_timer(events.NOTEEND, 0)
344 super(SongPlayingScreen, self).stop()
345
346