]> Git — Sourcephile - tmp/julm/arpeggigon.git/blob - src/RMCA/Semantics.hs
Refactored parallel boards.
[tmp/julm/arpeggigon.git] / src / RMCA / Semantics.hs
1 -- Basic Semantics V2 for a Reactive Music Cellular Automaton.
2 -- Inspired by the reacTogon.
3 -- Written by Henrik Nilsson, 2016-05-27
4 -- Based on an earlier version.
5 --
6 -- This gives the semantics of a single RMCA layer. The output is
7 -- a high-level representation of notes for each beat. This is to be
8 -- translated to low-level MIDI message by a subsequent translator
9 -- responsible for merging notes from different layers, ensuring that
10 -- a note off message corresponding to each note on message is always
11 -- emitted after the appropriate time, rendering any embellismnets
12 -- such as slides (while not generating too much MIDI data), etc.
13
14 -- ToDo:
15 -- * Add boolean flag to change direction to indicate start tile
16 -- DONE!
17 -- * Change main routine to generate start play heads from board
18 -- DONE!
19 -- * Add an optional restart facility: Maybe Int, restart every n
20 -- bars.
21 -- DONE!
22 -- * Interpret a negative repeat as repeat indefinitely.
23 -- DONE!
24 -- * Interpret a non-positve duration as mute: don't emit any note.
25 -- DONE!
26 -- * Eliminate Ignore as now almost the same as Absorb with duration 0?
27 -- The only difference is that Absorb mostly overrides the repeat count.
28 -- Absorb = Stop {duration 0, repeat 1}
29 -- And as absorb might be a common case, it might be useful to have
30 -- a distinct graphical representation?
31 -- DECIDED AGAINST FOR NOW
32
33 module RMCA.Semantics where
34
35 import Data.Array
36 import Data.List (intercalate, nub)
37 import Data.Maybe (catMaybes)
38 import RMCA.Auxiliary
39
40
41 ------------------------------------------------------------------------------
42 -- Basic Type Synonyms
43 ------------------------------------------------------------------------------
44
45 -- Unipolar control value; [0, 1]
46 type UCtrl = Double
47
48 -- Bipolar control value; [-1, 1]
49 type BCtrl = Double
50
51 -- Unipolar control values are usually between 0 and 127.
52 toUCtrl :: Int -> UCtrl
53 toUCtrl x = fromIntegral x / 127
54
55 fromUCtrl :: UCtrl -> Int
56 fromUCtrl x = floor $ bound (0,1) x * 127
57
58 -- Bipolar control values are usually between -127 and 127.
59 toBCtrl :: Int -> BCtrl
60 toBCtrl = toUCtrl
61
62 fromBCtrl :: BCtrl -> Int
63 fromBCtrl = fromUCtrl
64
65 ------------------------------------------------------------------------------
66 -- Tempo
67 ------------------------------------------------------------------------------
68
69 type Tempo = Int
70
71 -- LTempo designates a layer tempo. Useful for not transforming twice
72 -- a tempo.
73 type LTempo = Tempo
74
75 ------------------------------------------------------------------------------
76 -- Time and Beats
77 ------------------------------------------------------------------------------
78
79 -- The assumption is that the automaton is clocked by a beat clock and
80 -- thus advances one step per beat. For an automaton working in real time,
81 -- the beat clock would be defined externally, synchronized with other
82 -- layers and possibly external MIDI, and account for tempo, any swing, etc.
83
84 -- Beats and Bars
85
86 -- Beats per Bar: number of beats per bar in the time signature of a layer.
87 -- Non-negative.
88 type BeatsPerBar = Int
89
90 -- The beat number in the time signature of the layer. The first beat is 1.
91 type BeatNo = Int
92
93 nextBeatNo :: BeatsPerBar -> BeatNo -> BeatNo
94 nextBeatNo bpb bn = bn `mod` bpb + 1
95
96
97 {-
98 -- Not needed for individual layers (at present)
99
100 -- Time; [0,+inf)
101 type Time = Double
102 -}
103
104
105 ------------------------------------------------------------------------------
106 -- MIDI
107 ------------------------------------------------------------------------------
108
109 -- This semantics mainly works with a high-level represemntation of notes.
110 -- But it is convenient to express some of the high-level aspects directly
111 -- in the corresponding MIDI terms to facilitate the translation.
112
113 -- MIDI note number; [0,127]
114 type MIDINN = Int
115
116
117 -- Assume MIDI convetion: 60 = "Middle C" = C4
118 middleC :: Int
119 middleC = 60
120 middleCOct :: MIDINN
121 middleCOct = 4
122
123
124 -- MIDI velocity; [0,127]
125 type MIDIVel = Int
126
127
128 -- MIDI Program Change: Program Number; [0,127]
129 type MIDIPN = Int
130
131
132 -- MIDI Control Change: Control Number and Control Value; [0,127]
133 type MIDICN = Int
134 type MIDICV = Int
135
136 -- MIDICVRnd gives the option to pick a control value at random.
137 -- (Handled through subsequent translation to low-level MIDI events.)
138 data MIDICVRnd = MIDICV MIDICV | MIDICVRnd deriving (Eq, Show, Read)
139
140 --
141 ------------------------------------------------------------------------------
142 -- Notes
143 ------------------------------------------------------------------------------
144
145 -- Pitch
146
147 -- We chose to represent pitch by MIDI note number
148 newtype Pitch = Pitch MIDINN deriving Eq
149
150 pitchToMNN :: Pitch -> MIDINN
151 pitchToMNN (Pitch nn) = nn
152
153 instance Show Pitch where
154 show (Pitch nn) = names !! note ++ show oct
155 where
156 nn' = nn - middleC
157 note = nn' `mod` 12
158 oct = nn' `div` 12 + middleCOct
159 names = ["C", "C#", "D", "D#", "E", "F",
160 "F#", "G", "G#", "A", "A#", "B"]
161
162 -- Relative pitch in semi tones. Used for e.g. transposition.
163 type RelPitch = Int
164
165
166 -- Articulation
167
168 -- Each layer has a setting that indicate how strongly the notes
169 -- should normally be played as a percentage of full strength.
170 -- (In the real application, this settig can be set to a fixed value
171 -- or set to be derived from teh last input note, "as played").
172 -- Individual notes can tehn be accented (played more strongly),
173 -- either unconditionally or as a function of the beat count.
174
175 type Strength = UCtrl
176
177 -- This could of course be generalised, e.g. a list of beat numbers to
178 -- accentuate. But this is simple and accounts for the most common patterns.
179 data Articulation = NoAccent
180 | Accent
181 | Accent1
182 | Accent13
183 | Accent14
184 | Accent24
185 deriving (Eq, Show, Read, Enum)
186
187 accentStrength :: Strength
188 accentStrength = 1.2
189
190 -- Articulated strength
191 articStrength :: Strength -> BeatNo -> Articulation -> Strength
192 articStrength st bn art
193 | accentedBeat = st * accentStrength
194 | otherwise = st
195 where
196 accentedBeat =
197 case (bn, art) of
198 (_, NoAccent) -> False
199 (_, Accent) -> True
200 (1, Accent1) -> True
201 (1, Accent13) -> True
202 (3, Accent13) -> True
203 (1, Accent14) -> True
204 (4, Accent14) -> True
205 (1, Accent24) -> True
206 (4, Accent24) -> True
207 _ -> False
208
209
210 -- Duration
211
212 -- Duration in terms of a whole note at the *system* tempo. (Each layer
213 -- is clocked at a layer beat that is a fraction/multiple of the system
214 -- tempo). Note that notes are played a little shorter than their nominal
215 -- duration. This is taken care of by the translation into low-level
216 -- MIDI events. (One might consider adding indications of staccato or
217 -- tenuto.)
218 --
219 -- A non-positive duration is interpreted as mute: no note emitted.
220 type Duration = Rational
221
222
223 -- Ornamentation
224
225 -- Notes can be ornamented. Traditionnally, ornamenting refers to modifications
226 -- of the pitch, such as a trill or a grace note. Here we use the term in
227 -- a generalised sense.
228 -- * A MIDI program change (to be sent before the note).
229 -- * A MIDI Continuous Controler Change (to be sent before the note).
230 -- * A Slide
231 -- One might also consider adding trills, grace notes, MIDI after touch ...
232
233 data Ornaments = Ornaments {
234 ornPC :: Maybe MIDIPN,
235 ornCC :: [(MIDICN, MIDICVRnd)],
236 ornSlide :: SlideType
237 } deriving (Show,Read,Eq)
238
239 data SlideType = NoSlide | SlideUp | SlideDn deriving (Eq, Show, Enum, Read)
240
241 noOrn :: Ornaments
242 noOrn = Ornaments { ornPC = Nothing
243 , ornCC = []
244 , ornSlide = NoSlide
245 }
246
247 -- Notes
248
249 -- Attributes needed to generate a note.
250 -- * The pitch of a note is given by the position on the board
251 -- * The strength is given by the layer strength, beat no., and articulation
252 -- * Duratio and Ornamentatio are stored
253 data NoteAttr = NoteAttr {
254 naArt :: Articulation,
255 naDur :: Duration,
256 naOrn :: Ornaments
257 } deriving (Show,Read,Eq)
258
259
260 -- High level note representation emitted form a layer
261 data Note = Note {
262 notePch :: Pitch,
263 noteStr :: Strength,
264 noteDur :: Duration,
265 noteOrn :: Ornaments
266 } deriving (Show,Eq)
267
268
269 ------------------------------------------------------------------------------
270 -- Board
271 ------------------------------------------------------------------------------
272
273 -- Numbering; row number inside tile, column number below:
274 -- _ _
275 -- _/2\_/2\_
276 -- / \_/1\_/1\
277 -- \_/1\_/1\_/
278 -- / \_/0\_/0\
279 -- \_/0\_/0\_/
280 -- \_/ \_/
281 -- -1 0 1 2
282
283
284 -- Angle measured in multiples of 60 degrees.
285 type Angle = Int
286
287 data Dir = N | NE | SE | S | SW | NW deriving (Enum, Bounded, Eq, Show, Read)
288
289 predDir :: Dir -> Dir
290 predDir d | d == minBound = maxBound
291 | otherwise = pred d
292
293 nextDir :: Dir -> Dir
294 nextDir d | d == maxBound = minBound
295 | otherwise = succ d
296
297 turn :: Dir -> Angle -> Dir
298 turn d a = toEnum ((fromEnum d + a) `mod` 6)
299
300
301 type Pos = (Int, Int)
302
303 -- Position of neighbour in given direction
304 neighbor :: Dir -> Pos -> Pos
305 neighbor N (x,y) = (x, y + 1)
306 neighbor NE (x,y) = (x + 1, y + 1 - x `mod` 2)
307 neighbor SE (x,y) = (x + 1, y - x `mod` 2)
308 neighbor S (x,y) = (x, y - 1)
309 neighbor SW (x,y) = (x - 1, y - x `mod` 2)
310 neighbor NW (x,y) = (x - 1, y + 1 - x `mod` 2)
311
312
313 -- Position and transposition to pitch:
314 -- * Harmonic Table" layout: N = +7; NE = +4; SE = -3
315 -- * (0,0) assumed to be "Middle C"
316 posToPitch :: Pos -> RelPitch -> Pitch
317 posToPitch (x,y) tr =
318 Pitch (y * 7 + x `div` 2 - 3 * (x `mod` 2) + middleC + tr)
319
320
321 -- Actions
322 -- A ChDir counter is optionally a start counter if the Boolean flag is
323 -- set to true.
324 -- Any counter can be made silent by setting the note duration to a
325 -- non-positive number.
326
327 data Action = Inert -- No action, play heads move through.
328 | Absorb -- Remove play head silently.
329 | Stop NoteAttr -- Play note then remove play head.
330 | ChDir Bool NoteAttr Dir -- Play note then change direction.
331 | Split NoteAttr -- Play note then split head into five.
332 deriving (Show,Read,Eq)
333
334
335 -- Cells
336 -- A cell stores an action and a repetition number.
337 -- 0: the cell is completely bypassed, as if it wasn't there.
338 -- 1: the action is carried out once (default)
339 -- n > 1: any note output of the action is repeated (n-1) times before the
340 -- action is carried out.
341 -- n < 0: any note output of the action is repeated indefinitely (oo).
342
343 type Cell = (Action, Int)
344
345
346 -- Make a cell with a default repeat count of 1.
347 mkCell :: Action -> Cell
348 mkCell a = mkCellRpt a 1
349
350
351 -- Make a cell with a non-default repeition number.
352 mkCellRpt :: Action -> Int -> Cell
353 mkCellRpt a n = (a, n)
354
355
356 -- Board extent: south-west corner and north-east corner.
357 -- This covers most of the MIDI range: A#-1 (10) to G7 (103).
358 swc, nec :: Pos
359 swc = (-9, -6)
360 nec = (9, 6)
361
362
363 -- Test if a position is on the board as defined by swc and nec.
364 -- The assumption is that odd columns contain one more cell, as per the
365 -- picture above. Of course, one could opt for a "zig-zag" layout
366 -- with each column having the same number of cells which would be slightly
367 -- simpler.
368 onBoard :: Pos -> Bool
369 onBoard (x,y) = xMin <= x && x <= xMax
370 && yMin <= y
371 && (if even x then
372 y < yMax
373 else
374 y <= yMax)
375 where
376 (xMin, yMin) = swc
377 (xMax, yMax) = case nec of
378 (x, y) | even x -> (x, y + 1)
379 | otherwise -> (x, y)
380
381
382 type Board = Array Pos Cell
383
384
385 -- Build a board from a list specifying the non-empty cells.
386 makeBoard :: [(Pos, Cell)] -> Board
387 makeBoard pcs =
388 array (swc,nec')
389 ([(p, if onBoard p then mkCell Inert else mkCell Absorb)
390 | p <- range (swc, nec')]
391 ++ [(p,c) | (p, c) <- pcs, onBoard p])
392 where
393 -- This is to ensure (neighbor NW nec) is included on the board,
394 -- regardless of whether the column of nec is even or odd.
395 -- Otherwise, due to the "jagged" upper edge, the top row would
396 -- be missing, but every other cell of that *is* on the board.
397 -- The "superfluous" cells are set to Absorb above.
398 nec' = neighbor N nec
399
400
401 -- Look up a cell
402 lookupCell :: Board -> Pos -> Cell
403 lookupCell b p = if onBoard p then b ! p else (Absorb, 1)
404
405
406 ------------------------------------------------------------------------------
407 -- Play Head
408 ------------------------------------------------------------------------------
409
410 -- A play head is characterised by:
411 -- * Current position
412 -- * Number of beats before moving
413 -- * Direction of travel
414 -- If an action involves playing a note, this is repeated once for
415 -- each beat the play head is staying, with the rest of the action
416 -- carried out at the last beat.
417
418 data PlayHead =
419 PlayHead {
420 phPos :: Pos,
421 phBTM :: Int,
422 phDir :: Dir
423 }
424 deriving (Eq, Show)
425
426
427 ------------------------------------------------------------------------------
428 -- Start Heads
429 ------------------------------------------------------------------------------
430
431 startHeads :: Board -> [PlayHead]
432 startHeads bd =
433 [ PlayHead {
434 phPos = p,
435 phBTM = n,
436 phDir = d
437 }
438 | (p, (ChDir True _ d, n)) <- assocs bd ]
439
440
441 ------------------------------------------------------------------------------
442 -- State transition
443 ------------------------------------------------------------------------------
444
445 -- Advance the state of a single play head.
446 --
447 -- The result is a list of heads to be actioned at the *next* beat
448 -- later) and possibly a note to be played at *this* beat.
449
450 advanceHead :: Board -> BeatNo -> RelPitch -> Strength -> PlayHead
451 -> ([PlayHead], Maybe Note)
452 advanceHead bd bn tr st ph = ahAux (moveHead bd ph)
453 where
454 ahAux ph@PlayHead {phPos = p, phBTM = btm, phDir = d} =
455 case fst (lookupCell bd p) of
456 Inert -> ([ph], Nothing)
457 Absorb -> ([], Nothing) -- No point waiting until BTM=0
458 Stop na -> (newPHs [], mkNote p bn tr st na)
459 ChDir _ na d' -> (newPHs [ph {phDir = d'}],
460 mkNote p bn tr st na)
461 Split na -> (newPHs [ PlayHead {
462 phPos = p,
463 phBTM = 0,
464 phDir = d'
465 }
466 | a <- [-2 .. 2],
467 let d' = turn d a
468 ],
469 mkNote p bn tr st na)
470 where
471 newPHs phs = if btm == 0 then phs else [ph]
472
473
474 -- Moves a play head if the BTM counter has reached 0, otherwise decrement BTM.
475 -- Any encountered cells where the repeat count is < 1 are skipped.
476 moveHead :: Board -> PlayHead -> PlayHead
477 moveHead bd (ph@PlayHead {phPos = p, phBTM = btm, phDir = d})
478 | btm == 0 = let
479 p' = neighbor d p
480 btm' = snd (lookupCell bd p')
481 in
482 moveHead bd (ph {phPos = p', phBTM = btm'})
483 | btm > 0 = ph {phBTM = btm - 1}
484 | otherwise = ph -- Repeat indefinitely
485
486 mkNote :: Pos -> BeatNo -> RelPitch -> Strength -> NoteAttr -> Maybe Note
487 mkNote p bn tr st na@NoteAttr {naDur = d}
488 | d <= 0 = Nothing -- Notes of non-positive length are silent.
489 | otherwise = Just
490 Note {
491 notePch = posToPitch p tr,
492 noteStr = articStrength st bn (naArt na),
493 noteDur = naDur na,
494 noteOrn = naOrn na
495 }
496
497
498 -- Advance a list of heads, collecting all resulting heads and notes.
499 -- Any duplicate play heads are eliminated (or their number may uselessly
500 -- grow very quickly), and a cap (50, arbitrary, but should be plenty,
501 -- expecially given the board size) on the number of simultaneous playheads
502 -- per layer is imposed.
503 advanceHeads :: Board -> BeatNo -> RelPitch -> Strength -> [PlayHead]
504 -> ([PlayHead], [Note])
505 advanceHeads bd bn tr st phs =
506 let
507 (phss, mns) = unzip (map (advanceHead bd bn tr st) phs)
508 in
509 (take 50 (nub (concat phss)), catMaybes mns)
510
511
512 -- Given a board with start counters, run a board indefinitely, optionally
513 -- restarting every ri bars.
514 --
515 -- Arguments:
516 -- (1) Board (bd)
517 -- (2) Beats Per Bar (bpb); > 0
518 -- (3) Optioal repeat Interval (mri); In bars.
519 -- (4) Transposition (tr)
520 -- (5) Strength (st)
521 --
522 -- Returns:
523 -- Stream of notes played at each beat.
524 --
525 -- In the real implementation:
526 -- * A layer beat clock would be derived from the system beat (as a
527 -- fraction/multiple, adding any swing) and each clock event be tagged
528 -- with the beat number.
529 -- * The board (bd) would not necessarily be a constant input. (One might
530 -- consider allowing editing a layer while the machine is running)
531 -- * The time signature, and thus the beats per par (bpb), along with
532 -- repeat interval (ri) would likely be static (only changeable while
533 -- automaton is stopped).
534 -- * The transposition (tr) would be dynamic, the sum of a per layer
535 -- transposition that can be set through the user interface and the
536 -- difference between the MIDI note number of the last external
537 -- note received for the layer and middle C (say).
538 -- * The strength (st) would be dynamic, configurable as either the strength
539 -- set through the user interface or the strength of the last external
540 -- note received for the layer (derived from its MIDI velocity).
541
542 runRMCA :: Board -> BeatsPerBar -> Maybe Int -> RelPitch -> Strength
543 -> [[Note]]
544 runRMCA bd bpb mri tr st
545 | bpb > 0 =
546 case mri of
547 Nothing -> nss
548 Just ri
549 | ri > 0 -> cycle (take (ri * bpb) nss)
550 | otherwise -> error "The repeat interval must be at \
551 \least 1 bar."
552 | otherwise = error "The number of beats per bar must be at least 1."
553 where
554 nss = runAux 1 (startHeads bd)
555
556 runAux bn phs = ns : runAux (nextBeatNo bpb bn) phs'
557 where
558 (phs', ns) = advanceHeads bd bn tr st phs
559
560
561 -- Print played notes in a time-stamped (bar, beat), easy-to-read format.
562
563 ppNotes :: BeatsPerBar -> [[Note]] -> IO ()
564 ppNotes bpb nss = ppnAux (zip [(br,bn) | br <- [1..], bn <- [1..bpb]] nss)
565 where ppnAux :: [((Int,BeatsPerBar),[Note])] -> IO ()
566 ppnAux [] = return ()
567 ppnAux ((_, []) : tnss) = ppnAux tnss
568 ppnAux ((t, ns) : tnss) = do
569 putStrLn (leftJustify 10 (show t) ++ ": "
570 ++ intercalate ", " (map show ns))
571 ppnAux tnss
572
573
574 leftJustify :: Int -> String -> String
575 leftJustify w s = replicate (w - length s) ' ' ++ s
576
577 {-
578 ------------------------------------------------------------------------------
579 -- Simple tests
580 ------------------------------------------------------------------------------
581
582 testBoard1 =
583 makeBoard [((0,0), mkCell (ChDir True na1 N)),
584 ((0,1), mkCell (ChDir False na1 SE)),
585 ((1,1), mkCell (Split na1)),
586 ((1,-1), mkCell (Split na1)),
587 ((-1,0), mkCell (ChDir False na2 NE))]
588
589 testBoard1a =
590 makeBoard [((0,0), mkCell (ChDir False na1 N)),
591 ((0,1), mkCell (ChDir False na1 SE)),
592 ((1,1), mkCell (Split na1)),
593 ((1,-1), mkCell (Split na1)),
594 ((-1,0), mkCell (ChDir False na2 NE))]
595
596 testBoard2 =
597 makeBoard [((0,0), mkCell (ChDir True na1 N)),
598 ((0,2), mkCellRpt (ChDir False na2 SE) 3),
599 ((2,1), mkCell (ChDir False na1 SW)),
600 ((1,1), mkCellRpt (ChDir False na1 N) 0) {- Skipped! -},
601 ((0,4), mkCellRpt (ChDir True na1 N) (-1)) {- Rpt indef. -},
602 ((0, -6), mkCell (ChDir True na1 N)),
603 ((0, -2), mkCell (ChDir False na3 S) {- Silent -})]
604
605 testBoard3 =
606 makeBoard [((0,0), mkCell (ChDir True na1 N))]
607
608 na1 = NoteAttr {
609 naArt = Accent13,
610 naDur = 1 % 4,
611 naOrn = Ornaments Nothing [] NoSlide
612 }
613
614 na2 = NoteAttr {
615 naArt = NoAccent,
616 naDur = 1 % 16,
617 naOrn = Ornaments Nothing [(10, MIDICVRnd)] SlideUp
618 }
619
620 na3 = NoteAttr {
621 naArt = Accent13,
622 naDur = 0,
623 naOrn = Ornaments Nothing [] NoSlide
624 }
625
626
627 bpb :: Int
628 bpb = 4
629
630 main = ppNotes bpb (take 50 (runRMCA testBoard3 bpb (Just 2) 0 0.8))
631 -}