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