forked from defaultxr/cl-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patterns.lisp
2945 lines (2397 loc) · 115 KB
/
patterns.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(in-package #:cl-patterns)
;;; pattern glue
(defun make-default-event ()
"Get `*event*' if it's not nil, or get a fresh empty event."
(or *event* (event)))
(defun set-parents (pattern)
"Loop through PATTERN's slots and set the \"parent\" slot of any patterns to this pattern."
(labels ((set-parent (list parent)
"Recurse through LIST, setting the parent of any pattern found to PARENT."
(cond ((listp list)
(mapc (lambda (x) (set-parent x parent)) list))
((typep list 'pattern)
(setf (slot-value list 'parent) parent)))))
(loop :for slot :in (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pattern)))
:unless (eql slot 'parent) ;; FIX: add tests for this!
:do
(when (slot-boundp pattern slot)
(set-parent (slot-value pattern slot) pattern)))
pattern))
(defparameter *patterns* (list)
"List of the names of all defined pattern types.")
(defmacro defpattern (name superclasses slots &key documentation defun) ;; FIX: should warn if `set-parents' is not called in the creation-function.
"Define a pattern. This macro automatically generates the pattern's class, its pstream class, and the function to create an instance of the pattern, and makes them external in the cl-patterns package.
NAME is the name of the pattern. Typically a word or two that describes its function, prefixed with p.
SUPERCLASSES is a list of superclasses of the pattern. Most patterns just subclass the 'pattern' class.
SLOTS is a list of slots that the pattern and pstreams derived from it have. Each slot can either be just a symbol, or a slot definition a la `defclass'. You can provide a default for the slot with the :default key, and you can set a slot as a state slot (which only appears in the pattern's pstream class) by setting the :state key to t.
DOCUMENTATION is a docstring describing the pattern. We recommend providing at least one example, and a \"See also\" section to refer to similar pattern classes.
DEFUN can either be a full defun form for the pattern, or an expression which will be inserted into the pattern creation function prior to initialization of the instance. Typically you'd use this for inserting `assert' statements, for example."
(let* ((superclasses (or superclasses (list 'pattern)))
(slots (mapcar #'ensure-list slots))
(name-pstream (intern (concatenate 'string (symbol-name name) "-PSTREAM") 'cl-patterns))
(super-pstream (if (eql 'pattern (car superclasses))
'pstream
(intern (concatenate 'string (symbol-name (car superclasses)) "-PSTREAM") 'cl-patterns))))
(labels ((desugar-slot (slot)
"Convert a slot into something appropriate for defclass to handle."
(let ((name (car slot))
(rest (cdr slot)))
(append (list name)
(remove-from-plist rest :default :state)
(unless (position :initarg (keys rest))
(list :initarg (make-keyword name))))))
(optional-slot-p (slot)
"Whether the slot is optional or not. A slot is optional if a default is provided."
(position :default (keys (cdr slot))))
(state-slot-p (slot)
"Whether the slot is a pstream state slot or not. Pstream state slots only appear as slots for the pattern's pstream class and not for the pattern itself."
(position :state (keys (cdr slot))))
(function-lambda-list (slots)
"Generate the lambda list for the pattern's creation function."
(let ((optional-used nil))
(loop :for slot :in slots
:append (unless (state-slot-p slot)
(if (optional-slot-p slot)
(prog1
(append (if (not optional-used)
(list '&optional)
(list))
(list (list (car slot) (getf (cdr slot) :default))))
(setf optional-used t))
(list (car slot)))))))
(make-defun (pre-init)
`(defun ,name ,(function-lambda-list slots)
,documentation
,@(when pre-init (list pre-init))
(set-parents
(make-instance ',name
,@(mapcan (lambda (i) (list (make-keyword (car i)) (car i)))
(remove-if #'state-slot-p slots))))))
(add-doc-to-defun (sexp)
(if (and (listp sexp)
(position (car sexp) (list 'defun 'defmacro))
(not (stringp (nth 3 sexp))))
(append (subseq sexp 0 3) (list documentation) (subseq sexp 3))
sexp)))
`(progn
(defclass ,name ,superclasses
,(mapcar #'desugar-slot (remove-if #'state-slot-p slots))
,@(when documentation
`((:documentation ,documentation))))
,(unless defun ;; FIX: does this work properly for all patterns?
`(defmethod print-object ((,name ,name) stream)
(format stream "#<~s~{ ~s~}>" ',name
(mapcar (lambda (slot) (slot-value ,name slot))
',(mapcar #'car (remove-if (lambda (slot)
(or (state-slot-p slot)
;; FIX: don't show arguments that are set to the defaults?
))
slots))))))
(defclass ,name-pstream (,super-pstream ,name)
,(mapcar #'desugar-slot (remove-if-not #'state-slot-p slots))
(:documentation ,(format nil "pstream for `~a'." (string-downcase (symbol-name name)))))
,(let* ((gen-func-p (or (null defun)
(and (listp defun)
(position (car defun) (list 'assert)))))
(pre-init (when gen-func-p
defun)))
(if gen-func-p
(make-defun pre-init)
(add-doc-to-defun defun)))
(pushnew ',name *patterns*)
(export '(,name ,name-pstream))))))
(defparameter *max-pattern-yield-length* 256
"The default maximum number of events or values that will be used by functions like `next-n' or patterns like `pshift', in order to prevent hangs caused by infinite-length patterns.")
;;; pattern
(defgeneric pstream-count (pattern)
(:documentation "The number of pstreams that have been made of this pattern."))
(defclass pattern ()
((play-quant :initarg :play-quant :documentation "A list of numbers representing when the pattern's pstream can start playing. See `play-quant' and `quant'.")
(end-quant :initarg :end-quant :accessor end-quant :type list :documentation "A list of numbers representing when a pattern can end playing and when a `pdef' can be swapped out for a new definition. See `end-quant' and `quant'.")
(end-condition :initarg :end-condition :initform nil :accessor end-condition :type (or null function) :documentation "Nil or a function that is called by the clock with the pattern as its argument to determine whether the pattern should end or swap to a new definition.")
(parent :initarg :parent :initform nil :documentation "When a pattern is embedded in another pattern, the embedded pattern's parent slot points to the pattern it is embedded in.")
(loop-p :initarg :loop-p :documentation "Whether or not the pattern should loop when played.")
(cleanup-functions :initarg :cleanup-functions :initform (list) :documentation "A list of functions that are run when the pattern ends or is stopped.")
(pstream-count :initform 0 :reader pstream-count :documentation "The number of pstreams that have been made of this pattern.")
(metadata :initarg :metadata :initform (make-hash-table) :type hash-table :documentation "Hash table of additional data associated with the pattern, accessible with the `pattern-metadata' function."))
(:documentation "Abstract pattern superclass."))
(defun pattern-p (object)
"Return true if OBJECT is a pattern, and NIL otherwise."
(typep object 'pattern))
(defun all-patterns ()
"Get a list of the names of all defined pattern classes.
See also: `all-pdefs'"
*patterns*)
(defmethod play-quant ((pattern pattern))
(if (slot-boundp pattern 'play-quant)
(slot-value pattern 'play-quant)
(list 1)))
(defmethod (setf play-quant) (value (pattern pattern))
(setf (slot-value pattern 'play-quant) (ensure-list value)))
(defmethod end-quant ((pattern pattern))
(if (slot-boundp pattern 'end-quant)
(slot-value pattern 'end-quant)
nil))
(defmethod (setf end-quant) (value (pattern pattern))
(setf (slot-value pattern 'end-quant) (ensure-list value)))
(defmethod loop-p ((pattern pattern))
(if (slot-boundp pattern 'loop-p)
(slot-value pattern 'loop-p)
nil))
(defmethod (setf loop-p) (value (pattern pattern))
(setf (slot-value pattern 'loop-p) value))
(defgeneric peek (pattern)
(:documentation "\"Peek\" at the next value of a pstream, without advancing its current position.
See also: `next', `peek-n', `peek-upto-n'"))
(defun peek-n (pstream n)
"Peek at the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-upto-n', `next', `next-n'"
(assert (integerp n) (n) "peek-n's N argument must be an integer.")
(unless (pstream-p pstream)
(return-from peek-n (peek-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:collect (pstream-elt-future pstream (+ number (- future-number) i)))))
(defun peek-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at up to the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-n', `next', `next-upto-n'"
(assert (integerp n) (n) "peek-upto-n's N argument must be an integer.")
(unless (pstream-p pstream)
(return-from peek-upto-n (peek-upto-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:for res := (pstream-elt-future pstream (+ number (- future-number) i))
:until (null res)
:collect res)))
(defgeneric next (pattern)
(:documentation "Get the next value of a pstream, function, or other object, advancing the pstream forward in the process.
See also: `next-n', `next-upto-n', `peek'")
(:method-combination pattern))
(defmethod next ((pattern t))
pattern)
(defmethod next ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((pattern function))
(funcall pattern))
(defun next-n (pattern n)
"Get the next N results of a pattern stream, function, or other object, advancing the pattern stream forward N times in the process.
See also: `next', `next-upto-n', `peek', `peek-n'"
(assert (integerp n) (n) "next-n's N argument must be an integer.")
(let ((pstream (pattern-as-pstream pattern)))
(loop :repeat n
:collect (next pstream))))
(defun next-upto-n (pattern &optional (n *max-pattern-yield-length*))
"Get a list of up to N results from PATTERN. If PATTERN ends after less than N values, then all of its results will be returned.
See also: `next', `next-n', `peek', `peek-upto-n'"
(assert (integerp n) (n) "next-upto-n's N argument must be an integer.")
(let ((pstream (pattern-as-pstream pattern)))
(loop
:for number :from 0 :upto n
:while (< number n)
:for val := (next pstream)
:if (null val)
:do (loop-finish)
:else
:collect val)))
(defgeneric bsubseq (object start-beat &optional end-beat)
(:documentation "\"Beat subseq\" - get a list of all events from OBJECT whose `beat' is START-BEAT or above, and below END-BEAT.
See also: `events-in-range'"))
(defgeneric events-in-range (pstream min max)
(:documentation "Get all the events from PSTREAM whose start beat are MIN or greater, and less than MAX."))
(defmethod events-in-range ((pattern pattern) min max)
(events-in-range (as-pstream pattern) min max))
(defgeneric pattern-metadata (pattern &optional key)
(:documentation "Get the value of PATTERN's metadata for KEY. Returns true as a second value if the metadata had an entry for KEY, or nil if it did not."))
(defmethod pattern-metadata ((pattern pattern) &optional key)
(if key
(gethash key (slot-value pattern 'metadata))
(slot-value pattern 'metadata)))
(defun (setf pattern-metadata) (value pattern key)
(setf (gethash key (slot-value pattern 'metadata)) value))
;;; pstream
(defclass pstream (pattern #+#.(cl:if (cl:find-package "SEQUENCE") '(:and) '(:or)) sequence)
((number :initform 0 :documentation "The number of outputs yielded from this pstream and any sub-pstreams that have ended.") ;; FIX: rename to this-index ?
(pattern-stack :initform (list) :documentation "The stack of pattern pstreams embedded in this pstream.")
(source :initarg :source :documentation "The source object (i.e. pattern) that this pstream was created from.")
(pstream-count :initarg :pstream-count :reader pstream-count :type integer :documentation "How many times a pstream was made of this pstream's source prior to this pstream. For example, if it was the first time `as-pstream' was called on the pattern, this will be 0.")
(beat :initform 0 :reader beat :type number :documentation "The number of beats that have elapsed since the start of the pstream.")
(history :type vector :documentation "The history of outputs yielded by the pstream.")
(history-number :initform 0 :documentation "The number of items in this pstream's history. Differs from the number slot in that all outputs are immediately included in its count.")
(start-beat :initarg :start-beat :initform nil :documentation "The beat number of the parent pstream when this pstream started.")
(future-number :initform 0 :documentation "The number of peeks into the future that have been made in the pstream. For example, if `peek' is used once, this would be 1. If `next' is called after that, future-number decreases back to 0.")
(future-beat :initform 0 :documentation "The current beat including all future outputs (the `beat' slot does not include peeked outputs)."))
(:documentation "\"Pattern stream\". Keeps track of the current state of a pattern in process of yielding its outputs."))
(defmethod print-object ((pstream pstream) stream)
(with-slots (number) pstream
(print-unreadable-object (pstream stream :type t)
(format stream "~s ~s" :number number))))
(defun pstream-p (object)
"Return true if OBJECT is a pstream, and NIL otherwise."
(typep object 'pstream))
(defmethod loop-p ((pstream pstream))
(if (slot-boundp pstream 'loop-p)
(slot-value pstream 'loop-p)
(loop-p (slot-value pstream 'source))))
(defmethod events-in-range ((pstream pstream) min max)
(loop :while (and (<= (beat pstream) max)
(not (ended-p pstream)))
:do (let ((next (next pstream)))
(unless (typep next '(or null event))
(error "events-in-range can only be used on event streams."))))
(loop :for i :across (slot-value pstream 'history)
:if (and i
(>= (beat i) min)
(< (beat i) max))
:collect i
:if (or (null i)
(>= (beat i) max))
:do (loop-finish)))
(defgeneric last-output (pstream)
(:documentation "Returns the last output yielded by PSTREAM.
Example:
;; (defparameter *pstr* (as-pstream (pseq '(1 2 3) 1)))
;; (next *pstr*) ;=> 1
;; (last-output *pstr*) ;=> 1
See also: `ended-p'"))
(defmethod last-output ((pstream pstream))
(with-slots (number future-number) pstream
(let ((idx (- number future-number)))
(when (plusp idx)
(pstream-elt pstream (- idx (if (ended-p pstream) 2 1)))))))
(defgeneric ended-p (pstream)
(:documentation "Returns t if PSTREAM has no more outputs, or nil if outputs remain to be yielded.
Example:
;; (defparameter *pstr* (as-pstream (pseq '(1 2) 1)))
;; (next *pstr*) ;=> 1
;; (ended-p *pstr*) ;=> NIL
;; (next *pstr*) ;=> 2
;; (ended-p *pstr*) ;=> NIL
;; (next *pstr*) ;=> NIL
;; (ended-p *pstr*) ;=> T
See also: `last-output'"))
(defmethod ended-p ((pstream pstream))
(with-slots (number future-number) pstream
(and (not (= 0 (- number future-number)))
(null (pstream-elt pstream -1)))))
(defun value-remaining-p (value)
"Returns true if VALUE represents that a pstream has outputs \"remaining\"; i.e. VALUE is a symbol (i.e. :inf), or a number greater than 0."
(typecase value
(null nil)
(symbol (eql value :inf))
(number (plusp value))
(otherwise nil)))
(defun remaining-p (pattern &optional (repeats-key 'repeats) (remaining-key 'current-repeats-remaining))
"Returns true if PATTERN's REMAINING-KEY slot value represents outputs \"remaining\" (see `value-remaining-p'). If PATTERN's REMAINING-KEY slot is unbound or 0, and REPEATS-KEY is not nil, then it is automatically set to the `next' of PATTERN's REPEATS-KEY slot. Then if that new value is 0 or nil, remaining-p returns nil. Otherwise, :reset is returned as a generalized true value and to indicate that `next' was called on PATTERN's REPEATS-KEY slot."
(labels ((set-next ()
(setf (slot-value pattern remaining-key) (next (slot-value pattern repeats-key)))
(when (value-remaining-p (slot-value pattern remaining-key))
:reset)))
(if (not (slot-boundp pattern remaining-key))
(set-next)
(let ((rem-key (slot-value pattern remaining-key)))
(typecase rem-key
(null nil)
(symbol (eql rem-key :inf))
(number (if (plusp rem-key)
t
(set-next))) ;; if it's already set to 0, it was decf'd to 0 in the pattern, so we get the next one. if the next is 0, THEN we return nil.
(otherwise nil))))))
(defun decf-remaining (pattern &optional (key 'current-repeats-remaining))
"Decrease PATTERN's KEY value."
(when (numberp (slot-value pattern key))
(decf (slot-value pattern key))))
(defmethod peek ((pstream pstream))
(with-slots (number future-number) pstream
(pstream-elt-future pstream (- number future-number))))
(defmethod peek ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next :around ((pstream pstream))
(labels ((get-value-from-stack (pattern)
(with-slots (number pattern-stack) pattern
(if pattern-stack
(let ((popped (pop pattern-stack)))
(if-let ((nv (next popped)))
(progn
(push popped pattern-stack)
nv)
(get-value-from-stack pattern)))
(prog1
(let ((res (call-next-method)))
(typecase res
(pattern
;; if `next' returns a pattern, we push it to the pattern stack as a pstream
(let ((pstr (as-pstream res)))
(setf (slot-value pstr 'start-beat) (beat pattern))
(push pstr pattern-stack))
(get-value-from-stack pattern))
(t res)))
(incf number))))))
(with-slots (number history history-number future-number) pstream
(if (plusp future-number)
(let ((result (elt history (- number future-number))))
(decf future-number)
(when (event-p result)
(incf (slot-value pstream 'beat) (event-value result :delta)))
result)
(let ((result (get-value-from-stack pstream)))
(when (event-p result)
(setf result (copy-event result))
(when (and (null (raw-event-value result :beat))
(null (slot-value pstream 'parent)))
(setf (beat result) (slot-value pstream 'future-beat)))
(incf (slot-value pstream 'beat) (event-value result :delta))
(incf (slot-value pstream 'future-beat) (event-value result :delta)))
(setf (elt history (mod history-number (length (slot-value pstream 'history)))) result)
(incf history-number)
result)))))
(defgeneric as-pstream (thing)
(:documentation "Return THING as a pstream object.
See also: `pattern-as-pstream'"))
(defun pattern-as-pstream (thing)
"Like `as-pstream', but only converts THING to a pstream if it is a pattern."
(if (typep thing 'pattern)
(as-pstream thing)
thing))
(defclass t-pstream (pstream)
((value :initarg :value :initform nil :documentation "The value that is yielded by the t-pstream."))
(:documentation "Pattern stream object that yields its value only once."))
(defun t-pstream (value)
"Make a t-pstream object with the value VALUE."
(make-instance 't-pstream :value value))
(defmethod print-object ((pstream t-pstream) stream)
(print-unreadable-object (pstream stream :type t) (prin1 (slot-value pstream 'value) stream)))
(defmethod as-pstream ((value t))
(t-pstream value))
(defmethod next ((pattern t-pstream))
(when (= 0 (slot-value pattern 'number))
(let ((value (slot-value pattern 'value)))
(if (functionp value)
(funcall value)
value))))
(defmethod as-pstream ((pattern pattern))
(let ((slots (remove 'parent (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pattern))))))
(apply #'make-instance
(intern (concatenate 'string (symbol-name (class-name (class-of pattern))) "-PSTREAM") 'cl-patterns)
(loop :for slot :in slots
:if (slot-boundp pattern slot)
:append (list (make-keyword slot)
(pattern-as-pstream (slot-value pattern slot)))))))
(defmethod as-pstream :around ((pattern pattern))
(let ((pstream (call-next-method)))
(incf (slot-value pattern 'pstream-count))
pstream))
(defmethod as-pstream :around ((object t))
(let ((pstream (call-next-method)))
(with-slots (pstream-count source history) pstream
(setf pstream-count (if (slot-exists-p object 'pstream-count)
(slot-value object 'pstream-count)
0)
source object
history (make-array *max-pattern-yield-length* :initial-element nil)))
(set-parents pstream)
pstream))
(defmethod as-pstream :around ((pstream pstream)) ;; prevent pstreams from being "re-converted" to pstreams
pstream)
(define-condition pstream-out-of-range () ((index :initarg :index :reader pstream-elt-index))
(:report (lambda (condition stream)
(format stream "The index ~d falls outside the scope of the pstream's history." (pstream-elt-index condition)))))
(defun pstream-elt-index-to-history-index (pstream index)
"Given INDEX, an absolute index into PSTREAM's history, return the actual index into the current recorded history of the pstream.
See also: `pstream-history-advance-by'"
(assert (>= index 0) (index))
(with-slots (history) pstream
(mod index (length history))))
(defun pstream-elt (pstream n)
"Get the Nth item in PSTREAM's history. For negative N, get the -Nth most recent item.
Example:
;; (let ((pstream (as-pstream (pseq '(1 2 3)))))
;; (next pstream) ;=> 1
;; (pstream-elt pstream 0) ;=> 1 ;; first item in the pstream's history
;; (next pstream) ;=> 2
;; (pstream-elt pstream 1) ;=> 2 ;; second item in the pstream's history
;; (pstream-elt pstream -1)) ;=> 2 ;; most recent item in the pstream's history
See also: `pstream-elt-future', `phistory'"
(assert (integerp n) (n))
(unless (pstream-p pstream)
(return-from pstream-elt (pstream-elt (as-pstream pstream) n)))
(with-slots (history history-number) pstream
(let ((real-index (if (minusp n)
(+ history-number n)
n)))
(if (and (>= real-index (max 0 (- history-number (length history))))
(< real-index history-number))
(elt history (pstream-elt-index-to-history-index pstream real-index))
(error 'pstream-out-of-range :index n)))))
(defun pstream-history-advance-by (pstream index) ;; FIX: add tests for this
"Convert a history index (i.e. a positive number provided to `pstream-elt-future') to the amount that the history must be advanced by.
If the provided index is before the earliest item in history, the result will be a negative number denoting how far beyond the earliest history the index is.
If the provided index is within the current history, the result will be zero.
If the provided index is in the future, the result will be a positive number denoting how far in the future it is.
See also: `pstream-elt-index-to-history-index'"
(assert (>= index 0) (index))
(with-slots (history history-number) pstream
(let ((history-length (length history)))
(if (< index (- history-number history-length))
(- history-number history-length)
(if (>= index history-number)
(- index (1- history-number))
0)))))
(defun pstream-elt-future (pstream n)
"Get the element N away from the most recent in PSTREAM's history. Unlike `pstream-elt', this function will automatically peek into the future for any positive N.
Example:
;; (let ((pstream (as-pstream (pseq '(1 2 3)))))
;; (pstream-elt-future pstream 0) ;=> 1
;; (next pstream) ;=> 1
;; (pstream-elt-future pstream 1) ;=> 2
;; (next pstream)) ;=> 2
See also: `pstream-elt', `phistory'"
(assert (integerp n) (n))
(unless (pstream-p pstream)
(return-from pstream-elt-future (pstream-elt-future (as-pstream pstream) n)))
(when (minusp n)
(return-from pstream-elt-future (pstream-elt pstream n)))
(with-slots (history history-number future-number) pstream
(let ((advance-by (pstream-history-advance-by pstream n)))
(when (or (minusp advance-by)
(> (+ future-number advance-by) (length history)))
;; the future and history are recorded to the same array.
;; since the array is of finite size, requesting more from the future than history is able to hold would result in the oldest elements of the future being overwritten with the newest, thus severing the timeline...
(error 'pstream-out-of-range :index n))
(let ((prev-future-number future-number))
(setf future-number 0) ;; temporarily set it to 0 so the `next' method runs normally
(loop :repeat advance-by
:for next := (next pstream)
:if (event-p next)
:do (decf (slot-value pstream 'beat) (event-value next :delta)))
(setf future-number (+ prev-future-number advance-by))))
(let ((real-index (pstream-elt-index-to-history-index pstream n)))
(elt history real-index))))
(defgeneric parent-pattern (pattern)
(:documentation "Get the containing pattern of PATTERN, or NIL if there isn't one.
See also: `parent-pbind'"))
(defmethod parent-pattern ((pattern pattern))
(slot-value pattern 'parent))
(defgeneric parent-pbind (pattern)
(:documentation "Get the containing pbind of PATTERN, or NIL if there isn't one.
See also: `parent-pattern'"))
(defmethod parent-pbind ((pattern pattern))
(let ((par (parent-pattern pattern)))
(loop :until (or (null par) (typep par 'pbind))
:do (setf par (slot-value par 'parent)))
par))
;;; pbind
(defvar *pbind-special-init-keys* (list)
"The list of special keys for pbind that alters it during its initialization.
See also: `define-pbind-special-init-key'")
(defvar *pbind-special-wrap-keys* (list)
"The list of special keys for pbind that causes the pbind to be replaced by another pattern during its initialization.
See also: `define-pbind-special-wrap-key'")
(defvar *pbind-special-process-keys* (list)
"The list of special keys for pbind that alter the outputs of the pbind.
See also: `define-pbind-special-process-key'")
(defclass pbind (pattern)
((pairs :initarg :pairs :initform (list) :documentation "The pattern pairs of the pbind; a plist mapping its keys to their values."))
(:documentation "Please refer to the `pbind' documentation."))
(defun pbind (&rest pairs)
"pbind yields events determined by its PAIRS, which are a list of keys and values. Each key corresponds to a key in the resulting events, and each value is treated as a pattern that is evaluated for each step of the pattern to generate the value for its key.
Example:
;; (next-n (pbind :foo (pseq '(1 2 3)) :bar :hello) 4)
;;
;; ;=> ((EVENT :FOO 1 :BAR :HELLO) (EVENT :FOO 2 :BAR :HELLO) (EVENT :FOO 3 :BAR :HELLO) NIL)
See also: `pmono', `pb'"
(assert (evenp (length pairs)) (pairs) "pbind's input must be provided as a list of key/value pairs.")
(when (> (count :pdef (keys pairs)) 1)
(warn "More than one :pdef key detected in pbind."))
(let* ((res-pairs (list))
(pattern-chain (list))
(pattern (make-instance 'pbind)))
(doplist (key value pairs)
(when (pattern-p value)
(setf (slot-value value 'parent) pattern))
(cond ((position key *pbind-special-init-keys*)
(when-let ((result (funcall (getf *pbind-special-init-keys* key) value pattern)))
(appendf res-pairs result)))
((position key *pbind-special-wrap-keys*)
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs)
(setf res-pairs (list)))
(unless (null pattern-chain)
(setf pattern (apply #'pchain (append pattern-chain (list pattern))))
(setf pattern-chain (list)))
(setf pattern (funcall (getf *pbind-special-wrap-keys* key) value pattern)))
(t
(unless (typep pattern 'pbind)
(appendf pattern-chain (list pattern))
(setf pattern (make-instance 'pbind)))
(appendf res-pairs (list key (if (and (eql key :embed)
(typep value 'symbol))
(pdef value)
value))))))
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs))
(appendf pattern-chain (list pattern))
(unless (length= 1 pattern-chain)
(setf pattern (apply #'pchain pattern-chain)))
;; process quant keys.
(doplist (k v pairs)
(when (member k (list :quant :play-quant :end-quant))
(funcall (fdefinition (list 'setf (reintern k 'cl-patterns))) (next v) pattern)))
;; process :pdef key.
(when-let ((pdef-name (getf pairs :pdef)))
(pdef pdef-name pattern))
pattern))
(setf (documentation 'pbind 'type) (documentation 'pbind 'function))
(defmethod print-object ((pbind pbind) stream)
(format stream "(~s~{ ~s ~s~})" 'pbind (slot-value pbind 'pairs)))
;; FIX: should automatically convert +, *, -, /, etc to their equivalent patterns.
;; FIX: allow keys to be lists, in which case results are destructured, i.e. (pb (list :foo :bar) (pcycles (a 1!4))) results in four (EVENT :FOO 1 :DUR 1/4)
(defmacro pb (key &body pairs)
"pb is a convenience macro, wrapping the functionality of `pbind' and `pdef'. KEY is the name of the pattern (same as pbind's :pdef key or `pdef' itself), and PAIRS is the same as in regular pbind. If PAIRS is only one element, pb operates like `pdef', otherwise it operates like `pbind'.
See also: `pbind', `pdef'"
(if (length= 1 pairs)
`(pdef ,key ,@pairs)
`(pbind :pdef ,key ,@pairs)))
(defclass pbind-pstream (pbind pstream)
())
(defmethod print-object ((pbind pbind-pstream) stream)
(print-unreadable-object (pbind stream :type t)
(format stream "~{~s ~s~^ ~}" (slot-value pbind 'pairs))))
(defmethod as-pstream ((pbind pbind))
(let ((slots (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pbind)))))
(apply #'make-instance
(intern (concatenate 'string (symbol-name (class-name (class-of pbind))) "-PSTREAM") 'cl-patterns)
(loop :for slot :in slots
:for slot-kw := (make-keyword slot)
:for bound := (slot-boundp pbind slot)
:if bound
:collect slot-kw
:if (eql :pairs slot-kw)
:collect (mapcar 'pattern-as-pstream (slot-value pbind 'pairs))
:if (and bound (not (eql :pairs slot-kw)))
:collect (slot-value pbind slot)))))
(defmacro define-pbind-special-init-key (key &body body)
"Define a special key for pbind that alters the pbind during its initialization, either by embedding a plist into its pattern-pairs or in another way. These functions are called once, when the pbind is created, and must return a plist if the key should embed values into the pbind pairs, or NIL if it should not."
(let ((keyname (make-keyword key)))
`(setf (getf *pbind-special-init-keys* ,keyname)
(lambda (value pattern)
(declare (ignorable value pattern))
,@body))))
;; (define-pbind-special-init-key inst ;; FIX: this should be part of event so it will affect the event as well. maybe just rename to 'synth'?
;; (list :instrument value))
(define-pbind-special-init-key loop-p
(setf (loop-p pattern) value)
nil)
(defmacro define-pbind-special-wrap-key (key &body body)
"Define a special key for pbind that replaces the pbind with another pattern during the pbind's initialization. Each encapsulation key is run once on the pbind after it has been initialized, altering the type of pattern returned if the return value of the function is non-NIL."
(let ((keyname (make-keyword key)))
`(setf (getf *pbind-special-wrap-keys* ,keyname)
(lambda (value pattern)
(declare (ignorable value pattern))
,@body))))
(define-pbind-special-wrap-key parp
(parp pattern value))
(define-pbind-special-wrap-key pfin
(pfin pattern value))
(define-pbind-special-wrap-key pfindur
(pfindur pattern value))
(define-pbind-special-wrap-key psync
(destructuring-bind (quant &optional maxdur) (ensure-list value)
(psync pattern quant (or maxdur quant))))
(define-pbind-special-wrap-key pdurstutter
(pdurstutter pattern value))
(define-pbind-special-wrap-key pr
(pr pattern value))
(define-pbind-special-wrap-key pn
(pn pattern value))
(define-pbind-special-wrap-key ptrace
(if value
(if (eql t value)
(ptrace pattern)
(pchain pattern
(pbind :- (ptrace value))))
pattern))
(define-pbind-special-wrap-key pmeta
(if (eql t value)
(pmeta pattern)
pattern))
(define-pbind-special-wrap-key pparchain
(pparchain pattern value))
(defmacro define-pbind-special-process-key (key &body body)
"Define a special key for pbind that alters the pattern in a nonstandard way. These functions are called for each event created by the pbind and must return an event if the key should embed values into the event stream, or NIL if the pstream should end."
(let ((keyname (make-keyword key)))
`(setf (getf *pbind-special-process-keys* ,keyname)
(lambda (value)
,@body))))
(define-pbind-special-process-key embed
value)
(defmethod next ((pbind pbind-pstream))
(labels ((accumulator (pairs)
(let ((key (car pairs))
(val (cadr pairs)))
(when (and (pstream-p val)
(null (slot-value val 'start-beat)))
(setf (slot-value val 'start-beat) (beat pbind)))
(when-let ((next-val (next val)))
(if (position key (keys *pbind-special-process-keys*))
(setf *event* (combine-events *event*
(funcall (getf *pbind-special-process-keys* key) next-val)))
(setf (event-value *event* key) next-val))
(if-let ((cddr (cddr pairs)))
(accumulator cddr)
*event*)))))
(let ((*event* (make-default-event)))
(setf (slot-value *event* '%beat) (+ (or (slot-value pbind 'start-beat) 0) (beat pbind)))
(if-let ((pairs (slot-value pbind 'pairs)))
(accumulator pairs)
*event*))))
(defmethod as-pstream ((item pbind-pstream))
item)
;;; pmono
(defun pmono (instrument &rest pairs)
"pmono defines a mono instrument event pstream. It's effectively the same as `pbind' with its :type key set to :mono.
See also: `pbind'"
(assert (evenp (length pairs)) (pairs))
(apply #'pbind
:instrument instrument
:type :mono
pairs))
;;; pseq
(defpattern pseq (pattern)
(list
(repeats :default :inf)
(offset :default 0)
(current-repeats-remaining :state t))
:documentation "Sequentially yield items from LIST, repeating the whole list REPEATS times. OFFSET is the offset to index into the list.
Example:
;; (next-n (pseq '(5 6 7) 2) 7)
;; ;=> (5 6 7 5 6 7 NIL)
;;
;; (next-upto-n (pseq '(5 6 7) 2 1))
;; ;=> (6 7 5 6 7 5)
See also: `pser'")
(defmethod as-pstream ((pattern pseq))
(with-slots (repeats list offset) pattern
(make-instance 'pseq-pstream
:list (next list)
:repeats (as-pstream repeats)
:offset (pattern-as-pstream offset))))
(defmethod next ((pseq pseq-pstream))
(with-slots (number list offset) pseq
(when (and (plusp number)
(= 0 (mod number (length list))))
(decf-remaining pseq 'current-repeats-remaining))
(when-let ((off (next offset)))
(when (and (remaining-p pseq)
list)
(elt-wrap list (+ off number))))))
;;; pser
(defpattern pser (pattern)
(list
(length :default :inf)
(offset :default 0)
(current-repeats-remaining :state t)
(current-index :state t))
:documentation "Sequentially yield values from LIST, yielding a total of LENGTH values.
Example:
;; (next-n (pser '(5 6 7) 2) 3)
;;
;; ;=> (5 6 NIL)
See also: `pseq'")
(defmethod as-pstream ((pser pser))
(with-slots (list length offset) pser
(make-instance 'pser-pstream
:list (next list)
:length (as-pstream length)
:offset (pattern-as-pstream offset))))
(defmethod next ((pser pser-pstream))
(with-slots (list offset current-index) pser
(when-let ((remaining (remaining-p pser 'length))
(off (next offset)))
(decf-remaining pser 'current-repeats-remaining)
(when (eql :reset remaining)
(setf current-index 0))
(prog1
(elt-wrap list (+ off current-index))
(incf current-index)))))
;;; pk
(defpattern pk (pattern)
(key
(default :default 1))
:documentation "Yield the value of KEY in the current `*event*' context, returning DEFAULT if that value is nil.
Example:
;; (next-upto-n (pbind :foo (pseq '(1 2 3) 1) :bar (pk :foo)))
;; ;=> ((EVENT :FOO 1 :BAR 1) (EVENT :FOO 2 :BAR 2) (EVENT :FOO 3 :BAR 3))
See also: `pbind', `event-value', `*event*'")
(defmethod as-pstream ((pattern pk))
(with-slots (key default) pattern
(make-instance 'pk-pstream
:key key
:default default)))
(defmethod next ((pk pk-pstream))
(with-slots (key default) pk
(or (event-value *event* key)
(if (string= :number key)
(slot-value pk 'number)
default))))
;;; prand
(defpattern prand (pattern)
(list
(length :default :inf)
(current-repeats-remaining :state t))
:documentation "Yield random values from LIST.
Example:
;; (next-n (prand '(1 2 3) 5) 6)
;; ;=> (3 2 2 1 1 NIL)
See also: `pxrand', `pwrand', `pwxrand'")
(defmethod as-pstream ((pattern prand))
(with-slots (list length) pattern
(make-instance 'prand-pstream
:list (next list)
:length (as-pstream length))))
(defmethod next ((pattern prand-pstream))
(when (remaining-p pattern 'length)
(decf-remaining pattern 'current-repeats-remaining)
(random-elt (slot-value pattern 'list))))
;;; pxrand
(defpattern pxrand (pattern)
(list
(length :default :inf)
(last-result :state t)
(current-repeats-remaining :state t))
:documentation "Yield random values from LIST, never repeating equal values twice in a row.
Example:
;; (next-upto-n (pxrand '(1 2 3) 4))
;; ;=> (3 1 2 1)
See also: `prand', `pwrand', `pwxrand'"
:defun (assert (position-if-not (lambda (i) (eql i (car list))) list) (list)
"pxrand's input list must have at least two non-eql elements."))
(defmethod as-pstream ((pxrand pxrand))
(with-slots (list length) pxrand
(make-instance 'pxrand-pstream
:list (next list)
:length (as-pstream length))))
(defmethod next ((pxrand pxrand-pstream))
(with-slots (list last-result) pxrand
(when (remaining-p pxrand 'length)
(decf-remaining pxrand 'current-repeats-remaining)
(setf last-result (loop :for res := (random-elt list)
:if (or (not (slot-boundp pxrand 'last-result))
(not (eql res last-result)))
:return res)))))
;;; pwrand
(defpattern pwrand (pattern)
(list
(weights :default (make-list (length list) :initial-element 1))
(length :default :inf)
(current-repeats-remaining :state t))
:documentation "Yield random elements from LIST weighted by respective values from WEIGHTS.
Example:
;; (next-upto-n (pwrand '(1 2 3) '(7 5 3) 10))
;; ;=> (1 1 2 2 2 1 2 1 1 3)
See also: `prand', `pxrand', `pwxrand'")
(defmethod as-pstream ((pattern pwrand))
(with-slots (list weights length) pattern
(make-instance 'pwrand-pstream
:list (next list)
:weights (next weights)
:length (as-pstream length))))
(defmethod next ((pattern pwrand-pstream))
(with-slots (list weights) pattern
(when (remaining-p pattern 'length)
(decf-remaining pattern 'current-repeats-remaining)
(let* ((cweights (cumulative-list (normalized-sum weights)))
(num (random 1.0)))
(nth (index-of-greater-than num cweights) list)))))
;;; pwxrand
(defpattern pwxrand (pattern)
(list
(weights :default (make-list (length list) :initial-element 1))
(length :default :inf)
(last-result :state t)
(current-repeats-remaining :state t))
:documentation "Yield random elements from LIST weighted by respective values from WEIGHTS, never repeating equivalent values twice in a row. This is effectively `pxrand' and `pwrand' combined.
Example:
;; (next-upto-n (pwxrand '(1 2 3) '(7 5 3) 10))
;; ;=> (1 2 1 2 1 3 1 2 1 2)