@kairotic/app 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,58 @@
1
+ // Generated by packages/build.mjs
2
+ export default {
3
+ "package": "@kairotic/io",
4
+ "version": "0.2.5",
5
+ "api": 1,
6
+ "author": "bonuoq",
7
+ "license": "MPL-2.0",
8
+ "components": [
9
+ {
10
+ "class": "control",
11
+ "license": "MPL-2.0",
12
+ "doc": "One control of a controller, out of the events that midiin, gamepad, motion, oscin or serial send (on their event outlet): its value, every time it moves. cc 74 [channel] a MIDI controller (0…1); note [n] a key (its loudness on, 0 off); bend the pitch of a glided note (Hz); pad lx · pad a · pad a3 a stick or button of a gamepad (by name, or a0 b3); tilt x · tilt y a phone's tilt (0…1); shake; osc /synth/cut the first number of an OSC address (* and ? allowed); serial pot · serial 0 a board's key, or the nth number of its lines. Into scale, to bring it to the range of what it moves — which is what learn makes.",
13
+ "source": ";; control · one control of a controller, out of the events of midiin, gamepad, motion, oscin or serial\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135.\n(let [num (fn [s] (let [n (js/parseFloat s)] (when (js/isFinite n) n)))\n ;; an OSC address pattern, only * and ? (the rest as it is)\n osc-re (fn [p] (js/RegExp. (str \"^\" (-> p (.replace (js/RegExp. \"[.+^${}()|[\\\\]\\\\\\\\]\" \"g\") \"\\\\$&\") (.replaceAll \"*\" \"[^/]*\") (.replaceAll \"?\" \"[^/]\")) \"$\")))\n ;; the spec, from the words after the class: [kind & words]\n ;; (a word such as /synth/cut is read as a keyword with an empty namespace: put its / back)\n spec-of (fn [args] (mapv (fn [a] (cond (and (keyword? a) (re-find #\"/\" (str a))) (subs (str a) 1)\n (keyword? a) (name a)\n :else (str a)))\n args))\n ;; the value of the event for the spec, or nil if the event is not that control\n pick (fn [[kind a b] e]\n (case kind\n \"cc\" (when (and (= :cc (:type e)) (= (num a) (:cc e)) (or (nil? b) (= (num b) (:ch e)))) (:value e))\n \"note\" (when (and (= :note (:type e)) (or (nil? a) (= (num a) (:note e))))\n (if (:gate e) (or (:amp e) 1) 0))\n \"bend\" (when (= :glide (:type e)) (:freq e))\n \"pad\" (when (and (#{:axis :button} (:type e))\n (or (= a (some-> (:name e) name))\n (= a (str (if (= :axis (:type e)) \"a\" \"b\") (or (:axis e) (:button e))))))\n (:value e))\n \"tilt\" (when (= :tilt (:type e)) (if (= a \"y\") (:y e) (:x e)))\n \"shake\" (when (= :shake (:type e)) (:value e))\n \"osc\" (when (and a (:address e) (.test (osc-re a) (:address e)))\n (let [v (first (:args e))] (when (number? v) v)))\n \"serial\" (when (= :serial (:type e))\n (cond (and (:key e) (= a (:key e))) (:value e)\n (and (:values e) (num a)) (get (:values e) (js/Math.round (num a)))))\n nil))]\n {;; ── about ──\n :class \"control\"\n :license \"MPL-2.0\"\n :doc \"One control of a controller, out of the events that midiin, gamepad, motion, oscin or serial send (on their event outlet): its value, every time it moves. cc 74 [channel] a MIDI controller (0…1); note [n] a key (its loudness on, 0 off); bend the pitch of a glided note (Hz); pad lx · pad a · pad a3 a stick or button of a gamepad (by name, or a0 b3); tilt x · tilt y a phone's tilt (0…1); shake; osc /synth/cut the first number of an OSC address (* and ? allowed); serial pot · serial 0 a board's key, or the nth number of its lines. Into scale, to bring it to the range of what it moves — which is what learn makes.\"\n :usage \"control kind [which] [channel]\"\n :io [1 1]\n :size [110 24]\n :help {:inlets [\"the events of midiin, gamepad, motion, oscin or serial\"]\n :outlets [\"the value of that one control, when it moves\"]\n :example \"(box :b1 \\\"midiin\\\" 40 30)\\n(box :b2 \\\"control cc 1\\\" 40 80)\\n(box :b3 \\\"scale 0 1 200 2000 log\\\" 40 120)\\n(box :b4 \\\"print\\\" 40 160)\\n(connect :b1 2 :b2 0)\\n(connect :b2 0 :b3 0)\\n(connect :b3 0 :b4 0)\"\n :try \"Press ▶ and move the modulation wheel (CC 1) of a MIDI keyboard: 200 to 2000, in tune with the ear.\"\n :see [\"scale\" \"midiin\" \"gamepad\" \"motion\" \"oscin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (if-let [v (and (map? value) (pick (spec-of args) value))]\n {:out [[0 v]] :show {:v v}}\n {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}]\n (let [s (str \"control \" (apply str (interpose \" \" (spec-of args))))]\n {:label (if (number? (:v shown)) (str s \" · \" (api/nice (:v shown))) s)}))\n :view [[:rect {:x 1 :y 1 :w 108 :h 22 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 6 :y 16 :size 10.5} :$label]]})\n"
14
+ },
15
+ {
16
+ "class": "gamepad",
17
+ "license": "MPL-2.0",
18
+ "doc": "A game controller while ▶ runs (press a button to wake it): each button pressed or let go is {:type :button :pad :button :name :value :gate}, a trigger that moves without crossing is the same without :gate, and a stick {:type :axis :pad :axis :name :value −1…1}, with its dead zone (deadzone, 0.12) taken out. With the standard mapping they have names: :a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home, and :lx :ly :rx :ry. pad (-1, all) keeps one. Out: every event, and [name value] for a route or a number box.",
19
+ "source": ";; gamepad · a game controller's buttons and sticks as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [buttons [:a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home]\n axes [:lx :ly :rx :ry]\n r3 (fn [x] (/ (js/Math.round (* x 1000)) 1000))\n ;; a stick's value without its dead zone (its rest is never exactly 0), still −1…1 outside it\n dead (fn [v dz] (if (< (js/Math.abs v) dz) 0 (* (js/Math.sign v) (/ (- (js/Math.abs v) dz) (- 1 dz)))))\n ;; one pad now against the same pad before: the events between them\n pad-diff (fn [i before pad dz]\n (let [std? (= \"standard\" (:mapping pad))\n ev (fn [m] (assoc m :src :gamepad :pad i))\n ax (mapv (fn [v] (r3 (dead v dz))) (:axes pad))\n axis-evs (for [[k v] (map-indexed vector ax)\n :let [old (get-in before [:axes k] 0)]\n :when (or (>= (js/Math.abs (- v old)) 0.01) (and (zero? v) (not (zero? old))))]\n (ev (cond-> {:type :axis :axis k :value v} (and std? (< k 4)) (assoc :name (nth axes k)))))\n btn-evs (for [[k [p v]] (map-indexed vector (:buttons pad))\n :let [[op ov] (get-in before [:buttons k] [false 0]) v (r3 v)]\n :when (or (not= (boolean p) (boolean op)) (>= (js/Math.abs (- v ov)) 0.01))]\n (ev (cond-> {:type :button :button k :value v}\n (and std? (< k 17)) (assoc :name (nth buttons k))\n (not= (boolean p) (boolean op)) (assoc :gate (boolean p)))))]\n [{:axes ax :buttons (mapv (fn [[p v]] [(boolean p) (r3 v)]) (:buttons pad))} (vec (concat btn-evs axis-evs))]))\n read-pads (fn []\n (let [raw (or (.-kairoticFakePads js/window) (when (.-getGamepads js/navigator) (.getGamepads js/navigator)) #js [])]\n (vec (for [p (js/Array.from raw) :when p]\n {:index (.-index p) :id (.-id p) :mapping (.-mapping p) :axes (vec (js/Array.from (.-axes p)))\n :buttons (mapv (fn [b] [(.-pressed b) (.-value b)]) (js/Array.from (.-buttons p)))}))))]\n {;; ── about ──\n :class \"gamepad\"\n :license \"MPL-2.0\"\n :doc \"A game controller while ▶ runs (press a button to wake it): each button pressed or let go is {:type :button :pad :button :name :value :gate}, a trigger that moves without crossing is the same without :gate, and a stick {:type :axis :pad :axis :name :value −1…1}, with its dead zone (deadzone, 0.12) taken out. With the standard mapping they have names: :a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home, and :lx :ly :rx :ry. pad (-1, all) keeps one. Out: every event, and [name value] for a route or a number box.\"\n :usage \"gamepad [pad] [deadzone]\"\n :io [0 2]\n :size [96 30]\n :args [[:pad -1] [:deadzone 0.12]]\n :help {:inlets []\n :outlets [\"every event, as a map\" \"[name value]: (:a 1), (:lx -0.4)…\"]\n :example \"(box :b1 \\\"gamepad\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 1 :b2 0)\"\n :try \"Press ▶, then any button of a controller to wake it: print shows the buttons and sticks by name.\"\n :see [\"motion\" \"midiin\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value args]}]\n (if (and (= inlet :audio) (:event value))\n (let [e (:event value)]\n (if (and (>= (:pad args) 0) (:pad e) (not= (:pad args) (:pad e)))\n {}\n {:out (cond-> [[0 e]] (#{:button :axis} (:type e)) (conj [1 [(or (:name e) (if (= :axis (:type e)) (:axis e) (:button e))) (:value e)]]))\n :show {:label (case (:type e)\n :connect (str \"pad \" (:pad e))\n :disconnect \"no pad\"\n (str (name (or (:name e) (:type e))) \" \" (api/nice (:value e))))}}))\n {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"gamepad\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the pads, read on every frame while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [dz (let [n (js/parseFloat (nth (.split (.trim (str (:text b))) #\"\\s+\") 2 \"\"))] (if (js/isNaN n) 0.12 n))\n node {:alive (atom true) :last (atom {}) :inlets [] :outlets []}\n report (fn [e] (api/report! (:id b) {:event e} nil))\n poll (fn poll [& _]\n (when @(:alive node)\n (let [pads (into {} (map (fn [p] [(:index p) p]) (read-pads)))\n before @(:last node)]\n (doseq [i (keys before) :when (not (contains? pads i))] (report {:src :gamepad :type :disconnect :pad i}))\n (reset! (:last node)\n (into {} (for [[i p] (sort-by key pads)]\n (let [[after es] (pad-diff i (get before i) p dz)]\n (when-not (contains? before i) (report {:src :gamepad :type :connect :pad i :name (:id p)}))\n (doseq [e es] (report e))\n [i after])))))\n (js/requestAnimationFrame poll)))]\n (poll)\n node))\n :dispose (fn [node] (reset! (:alive node) false))}})\n"
20
+ },
21
+ {
22
+ "class": "midiin",
23
+ "license": "MPL-2.0",
24
+ "doc": "MIDI from every input of the page (a keyboard, a controller, another program) as Kairotic events, while ▶ runs: a note is {:type :note :id :ch :note :freq :amp :gate}, a pitch bend moves the notes of its channel ({:type :glide :id :freq}), and controllers, pressure, program changes and the clock come as {:type :cc :ch :cc :value 0…1}, {:type :pressure …}, {:type :clock}…. Pitch travels as :freq in Hz: a bend, or an MPE controller (a channel per note; its bend range, RPN 0, is read), is only a different :freq. Out: the Hz of the notes sounding (with [:gain amp] just before a note starts) and their voice ids, as a keyboard or a player sends them, for synth~ or a polyphonic faust~; and every event. channel (0, all) keeps one; range (2) is the bend range of a controller that does not say its own. :clear (or :stop) lets every held note go. Chrome, Edge and Firefox ask once to use MIDI; Safari has no MIDI.",
25
+ "source": ";; midiin · MIDI from a keyboard, a controller or another program, as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [;; ── the page's MIDI, asked once and shared by every midi box (Chrome, Edge, Firefox; not Safari) ──\n access (fn []\n (or (.-kairoticMidi js/window)\n (let [p (if (.-requestMIDIAccess js/navigator)\n (.requestMIDIAccess js/navigator #js {:sysex false})\n (js/Promise.reject (js/Error. \"this browser has no Web MIDI (Chrome, Edge or Firefox; not Safari)\")))]\n (set! (.-kairoticMidi js/window) p)\n ;; refused: ask again next time\n (.catch p (fn [_] (set! (.-kairoticMidi js/window) nil)))\n p)))\n r3 (fn [x] (/ (js/Math.round (* x 1000)) 1000))\n r4 (fn [x] (/ (js/Math.round (* x 10000)) 10000))\n ;; ── bytes → messages ──\n decode (fn [[s a b]]\n (let [hi (bit-and (or s 0) 0xF0) ch (inc (bit-and (or s 0) 0x0F))]\n (case hi\n 0x80 {:type :note-off :ch ch :note a}\n 0x90 (if (zero? b) {:type :note-off :ch ch :note a} {:type :note-on :ch ch :note a :vel b})\n 0xA0 {:type :poly :ch ch :note a :value b}\n 0xB0 {:type :cc :ch ch :cc a :value b}\n 0xC0 {:type :program :ch ch :value a}\n 0xD0 {:type :pressure :ch ch :value a}\n 0xE0 {:type :bend :ch ch :value (- (+ a (* 128 b)) 8192)}\n 0xF0 (case s 0xF8 {:type :clock} 0xFA {:type :start} 0xFB {:type :continue} 0xFC {:type :stop} nil)\n nil)))\n ;; ── messages → events, with the state of what is held ──\n ;; a voice id names a note on a channel: the same key on two MPE channels is two voices\n voice-id (fn [ch note] (+ note (* 128 (dec ch))))\n fresh (fn [range0] {:range0 range0 :ranges {} :bends {} :rpn {} :held {} :order []})\n freq-of (fn [st ch note] (api/midi->hz (+ note (* (get (:bends st) ch 0) (get (:ranges st) ch (:range0 st))))))\n ev (fn [m] (assoc m :src :midi))\n step (fn [st m]\n (let [ch (:ch m)]\n (case (:type m)\n :note-on (let [id (voice-id ch (:note m)) f (r3 (freq-of st ch (:note m))) a (r3 (/ (:vel m) 127))\n offs (when (get (:held st) id) [(ev {:type :note :id id :ch ch :note (:note m) :freq f :gate false})])]\n [(-> st (assoc-in [:held id] {:ch ch :note (:note m) :freq f})\n (update :order (fn [o] (vec (cons id (remove #(= % id) o))))))\n (conj (vec offs) (ev {:type :note :id id :ch ch :note (:note m) :freq f :amp a :gate true}))])\n :note-off (let [id (voice-id ch (:note m)) h (get (:held st) id)]\n (if h\n [(-> st (update :held dissoc id) (update :order (fn [o] (vec (remove #(= % id) o)))))\n [(ev {:type :note :id id :ch ch :note (:note m) :freq (:freq h) :gate false})]]\n [st []]))\n :bend (let [st (assoc-in st [:bends ch] (/ (:value m) (if (neg? (:value m)) 8192 8191)))]\n (reduce (fn [[st out] id]\n (let [{:keys [note]} (get (:held st) id) f (r3 (freq-of st ch note))]\n [(assoc-in st [:held id :freq] f) (conj out (ev {:type :glide :id id :ch ch :note note :freq f}))]))\n [st []] (filter #(= ch (:ch (get (:held st) %))) (:order st))))\n ;; RPN 0 (CC 101 = 0, CC 100 = 0, then CC 6) is the bend range an MPE controller announces: read, not sent\n :cc (let [n (:cc m) rpn (get (:rpn st) ch {})]\n (cond (= n 101) [(assoc-in st [:rpn ch :msb] (:value m)) []]\n (= n 100) [(assoc-in st [:rpn ch :lsb] (:value m)) []]\n (and (= n 6) (= 0 (:msb rpn)) (= 0 (:lsb rpn))) [(assoc-in st [:ranges ch] (:value m)) []]\n (= n 38) [st []]\n :else [st [(ev {:type :cc :ch ch :cc n :value (r4 (/ (:value m) 127))})]]))\n :pressure (let [id (first (filter #(= ch (:ch (get (:held st) %))) (:order st)))]\n [st [(ev (cond-> {:type :pressure :ch ch :value (r4 (/ (:value m) 127))} id (assoc :id id)))]])\n :poly [st [(ev {:type :pressure :ch ch :id (voice-id ch (:note m)) :value (r4 (/ (:value m) 127))})]]\n :program [st [(ev {:type :program :ch ch :value (:value m)})]]\n (:clock :start :stop :continue) [st [(ev {:type (:type m)})]]\n [st []])))\n sounding (fn [st] [(:order st) (mapv #(:freq (get (:held st) %)) (:order st))])\n label (fn [e] (case (:type e)\n :note (str (api/midi-name (:note e)) (if (:gate e) (str \" \" (js/Math.round (* 127 (or (:amp e) 0)))) \" off\"))\n :glide (str (api/nice (:freq e)) \" Hz\")\n :cc (str \"cc \" (:cc e) \" \" (api/nice (:value e)))\n (name (:type e))))]\n {;; ── about ──\n :class \"midiin\"\n :license \"MPL-2.0\"\n :doc \"MIDI from every input of the page (a keyboard, a controller, another program) as Kairotic events, while ▶ runs: a note is {:type :note :id :ch :note :freq :amp :gate}, a pitch bend moves the notes of its channel ({:type :glide :id :freq}), and controllers, pressure, program changes and the clock come as {:type :cc :ch :cc :value 0…1}, {:type :pressure …}, {:type :clock}…. Pitch travels as :freq in Hz: a bend, or an MPE controller (a channel per note; its bend range, RPN 0, is read), is only a different :freq. Out: the Hz of the notes sounding (with [:gain amp] just before a note starts) and their voice ids, as a keyboard or a player sends them, for synth~ or a polyphonic faust~; and every event. channel (0, all) keeps one; range (2) is the bend range of a controller that does not say its own. :clear (or :stop) lets every held note go. Chrome, Edge and Firefox ask once to use MIDI; Safari has no MIDI.\"\n :usage \"midiin [channel] [range]\"\n :io [1 3]\n :size [96 30]\n :args [[:channel 0] [:range 2]]\n :help {:inlets [\":clear (or :stop): every held note goes\"]\n :outlets [\"the Hz of the notes sounding, most recent first ([:gain amp] before a note starts)\" \"their voice ids (note + 128 per channel above the first)\" \"every event, as a map\"]\n :example \"(box :b1 \\\"midiin\\\" 40 30)\\n(box :b2 \\\"synth~\\\" 40 90)\\n(box :b3 \\\"dac~\\\" 40 140)\\n(box :b4 \\\"print\\\" 160 90)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b2 1)\\n(connect :b2 0 :b3 0)\\n(connect :b2 0 :b3 1)\\n(connect :b1 2 :b4 0)\"\n :try \"Press ▶ and play a MIDI keyboard: synth~ plays it and print shows every event. Bend a note: it glides.\"\n :see [\"midiout\" \"keyboard\" \"synth~\" \"oscin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state (fresh (api/clamp (:range args) 1 96)))]\n (cond\n (and (= inlet :audio) (:error value)) {:effects [[:print (:error value)]] :show {:label \"no MIDI\"}}\n (and (= inlet :audio) (:ports value)) {:state st :show {:label (if (pos? (:ports value)) (str \"midi · \" (:ports value) \" in\") \"no MIDI input\")}}\n (and (= inlet :audio) (:bytes value))\n (let [m (decode (:bytes value))\n ch (:channel args)]\n (if (or (nil? m) (and (pos? ch) (:ch m) (not= ch (:ch m))))\n {:state st}\n (let [[st2 es] (step st m)]\n (if (empty? es)\n {:state st2}\n (let [[ids hz] (sounding st2)\n notes? (some #(#{:note :glide} (:type %)) es)\n on (first (filter #(and (= :note (:type %)) (:gate %)) es))]\n {:state st2\n :show {:label (label (last es))}\n :out (vec (concat (when notes? [[1 ids]])\n (when on [[0 [:gain (:amp on)]]])\n (when notes? [[0 hz]])\n (map (fn [e] [2 e]) es)))})))))\n (#{:clear :stop} value)\n (let [offs (for [id (:order st) :let [h (get (:held st) id)]]\n {:src :midi :type :note :id id :ch (:ch h) :note (:note h) :freq (:freq h) :gate false})]\n {:state (fresh (:range0 st)) :out (vec (concat [[1 []] [0 []]] (map (fn [e] [2 e]) offs)))})\n :else {:state st})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"midiin\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the inputs, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [node {:alive (atom true) :ins (atom []) :inlets [] :outlets []}\n on-msg (fn [e] (when @(:alive node) (api/report! (:id b) {:bytes (vec (js/Array.from (.-data e)))} nil)))\n wire! (fn [m]\n (doseq [i @(:ins node)] (.removeEventListener i \"midimessage\" on-msg))\n (let [ins (vec (js/Array.from (.values (.-inputs m))))]\n (doseq [i ins] (.addEventListener i \"midimessage\" on-msg))\n (reset! (:ins node) ins)\n (api/report! (:id b) {:ports (count ins)} nil)))]\n (assoc node :unwire (fn [] (doseq [i @(:ins node)] (.removeEventListener i \"midimessage\" on-msg)))\n :ready (-> (access)\n (.then (fn [m] (when @(:alive node)\n (wire! m)\n (.addEventListener m \"statechange\" (fn [_] (when @(:alive node) (wire! m)))))))\n (.catch (fn [e] (api/report! (:id b) {:error (str \"midiin: \" (.-message e))} nil)))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:unwire node)))}})\n"
26
+ },
27
+ {
28
+ "class": "midiout",
29
+ "license": "MPL-2.0",
30
+ "doc": "Notes and events to a MIDI port, while ▶ runs. On the left, what sounds as a player, a keyboard or a reader send it — the Hz of the notes (after their voice ids on the right, and [:gain amp] for the next ones) —, or an event from midiin, oscin or a room ({:type :note :freq :amp :gate}, :glide, :cc…). With mpe, each note gets a channel of its own (2…16) and its exact frequency as a key plus a pitch bend of that channel (range 48 semitones): microtones, just intervals and glides reach the synthesizer without rounding; at ▶ it announces the zone and the range (the MPE configuration message). Without it, one channel (channel, 1) and the nearest key. port (1) is which output of the page. :clear (or :stop) ends every note.",
31
+ "source": ";; midiout · Kairotic events and notes to a MIDI port, plain or MPE (microtones without rounding)\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [access (fn []\n (or (.-kairoticMidi js/window)\n (let [p (if (.-requestMIDIAccess js/navigator)\n (.requestMIDIAccess js/navigator #js {:sysex false})\n (js/Promise.reject (js/Error. \"this browser has no Web MIDI (Chrome, Edge or Firefox; not Safari)\")))]\n (set! (.-kairoticMidi js/window) p)\n (.catch p (fn [_] (set! (.-kairoticMidi js/window) nil)))\n p)))\n clamp (fn [x lo hi] (max lo (min hi x)))\n ;; ── messages → bytes ──\n encode (fn [{:keys [type ch note vel value cc]}]\n (let [c (dec (or ch 1)) b7 (fn [x] (clamp (js/Math.round x) 0 127))]\n (case type\n :note-on [(+ 0x90 c) (b7 note) (b7 vel)]\n :note-off [(+ 0x80 c) (b7 note) 0]\n :cc [(+ 0xB0 c) (b7 cc) (b7 value)]\n :pressure [(+ 0xD0 c) (b7 value)]\n :bend (let [v (+ 8192 (clamp (js/Math.round value) -8192 8191))] [(+ 0xE0 c) (bit-and v 127) (bit-shift-right v 7)])\n :clock [0xF8] :start [0xFA] :continue [0xFB] :stop [0xFC]\n nil)))\n ;; ── events → messages: plain (one channel, rounded) or MPE (a member channel per note) ──\n fresh (fn [mpe ch r] {:mode (if mpe :mpe :plain) :ch ch :range r :voices {} :free (vec (range 2 17)) :n 0})\n bend-of (fn [semis r] (clamp (js/Math.round (* (/ semis r) (if (neg? semis) 8192 8191))) -8192 8191))\n key-and-bend (fn [hz r]\n (let [m (api/hz->midi hz) k (clamp (js/Math.round m) 0 127)\n k (if (> (js/Math.abs (- m k)) r) (clamp (js/Math.round (- m (* (js/Math.sign (- m k)) r))) 0 127) k)]\n [k (bend-of (- m k) r)]))\n vel-of (fn [e] (clamp (js/Math.round (* 127 (or (:amp e) 0.8))) 1 127))\n off (fn [st id]\n (if-let [v (get-in st [:voices id])]\n [(-> st (update :voices dissoc id) (update :free #(if (= :mpe (:mode st)) (conj % (:ch v)) %)))\n [{:type :note-off :ch (:ch v) :note (:key v)}]]\n [st []]))\n on (fn [st e]\n (let [id (or (:id e) (js/Math.round (api/hz->midi (:freq e))))\n [st pre] (off st id)]\n (if (= :mpe (:mode st))\n (let [[st ch pre] (if (seq (:free st))\n [st (first (:free st)) pre]\n ;; every channel busy: the oldest voice gives its own\n (let [[oid v] (apply min-key (fn [[_ v]] (:n v)) (:voices st))]\n [(update st :voices dissoc oid) (:ch v) (conj pre {:type :note-off :ch (:ch v) :note (:key v)})]))\n [k b] (key-and-bend (:freq e) (:range st))]\n [(-> st (update :free #(vec (remove #{ch} %))) (assoc-in [:voices id] {:ch ch :key k :n (:n st)}) (update :n inc))\n (into pre [{:type :bend :ch ch :value b} {:type :note-on :ch ch :note k :vel (vel-of e)}])])\n (let [k (clamp (js/Math.round (api/hz->midi (:freq e))) 0 127)]\n [(-> st (assoc-in [:voices id] {:ch (:ch st) :key k :n (:n st)}) (update :n inc))\n (conj pre {:type :note-on :ch (:ch st) :note k :vel (vel-of e)})]))))\n out-step (fn [st e]\n (let [e (if (and (nil? (:freq e)) (number? (:note e))) (assoc e :freq (api/midi->hz (:note e))) e)]\n (case (:type e)\n (:note nil) (cond (false? (:gate e)) (off st (:id e))\n (and (number? (:freq e)) (pos? (:freq e))) (on st e)\n :else [st []])\n :glide (let [v (get-in st [:voices (:id e)])]\n (if (and v (= :mpe (:mode st)) (number? (:freq e)))\n [st [{:type :bend :ch (:ch v) :value (bend-of (- (api/hz->midi (:freq e)) (:key v)) (:range st))}]]\n [st []]))\n :cc [st [{:type :cc :ch (or (:ch e) (:ch st)) :cc (:cc e) :value (* 127 (:value e))}]]\n :pressure [st (if-let [v (get-in st [:voices (:id e)])] [{:type :pressure :ch (:ch v) :value (* 127 (:value e))}] [])]\n (:clock :start :stop :continue) [st [{:type (:type e)}]]\n [st []])))\n events (fn [st es] (reduce (fn [[st ms] e] (let [[st m] (out-step st e)] [st (into ms m)])) [st []] es))\n ;; a snapshot of what sounds (Hz and voice ids, as a player or a keyboard sends them) against the one before\n diff (fn [before after amp]\n (let [pairs (fn [{:keys [hz ids]}] (into {} (map vector (or (seq ids) (map #(js/Math.round (api/hz->midi %)) hz)) hz)))\n a (pairs before) b (pairs after)]\n (vec (concat (for [[id _] a :when (not (contains? b id))] {:type :note :id id :gate false})\n (for [[id f] b :when (and (contains? a id) (not= f (get a id)))] {:type :glide :id id :freq f})\n (for [[id f] (reverse (seq b)) :when (not (contains? a id))] {:type :note :id id :freq f :amp amp :gate true})))))\n setup (fn [r] (vec (concat [{:type :cc :ch 1 :cc 101 :value 0} {:type :cc :ch 1 :cc 100 :value 6} {:type :cc :ch 1 :cc 6 :value 15}]\n (mapcat (fn [ch] [{:type :cc :ch ch :cc 101 :value 0} {:type :cc :ch ch :cc 100 :value 0}\n {:type :cc :ch ch :cc 6 :value r} {:type :cc :ch ch :cc 101 :value 127} {:type :cc :ch ch :cc 100 :value 127}])\n (range 2 17)))))\n send (fn [st ms] (if (seq ms) {:state st :effects [[:send (vec (keep encode ms))]] :show {:n (count ms)}} {:state st}))]\n {;; ── about ──\n :class \"midiout\"\n :license \"MPL-2.0\"\n :doc \"Notes and events to a MIDI port, while ▶ runs. On the left, what sounds as a player, a keyboard or a reader send it — the Hz of the notes (after their voice ids on the right, and [:gain amp] for the next ones) —, or an event from midiin, oscin or a room ({:type :note :freq :amp :gate}, :glide, :cc…). With mpe, each note gets a channel of its own (2…16) and its exact frequency as a key plus a pitch bend of that channel (range 48 semitones): microtones, just intervals and glides reach the synthesizer without rounding; at ▶ it announces the zone and the range (the MPE configuration message). Without it, one channel (channel, 1) and the nearest key. port (1) is which output of the page. :clear (or :stop) ends every note.\"\n :usage \"midiout [mpe] [channel] [port] [range]\"\n :io [2 0]\n :size [96 30]\n :args [[:mpe false] [:channel 1] [:port 1] [:range 48]]\n :help {:inlets [\"the Hz of the notes sounding (a list), [:gain amp], an event map, or :clear (or :stop)\" \"the voice ids of the Hz that follow\"]\n :outlets []\n :example \"(box :b1 \\\"keyboard\\\" 40 30)\\n(box :b2 \\\"midiout mpe\\\" 40 120)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b2 1)\"\n :try \"Press ▶ and play the keyboard: the notes go to the first MIDI output of the page. With an MPE synthesizer, a freqt read by a reader~ glides there without steps.\"\n :see [\"midiin\" \"synth~\" \"player\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:enc (fresh (:mpe args) (api/clamp (:channel args) 1 16) (api/clamp (:range args) 1 96)) :snap {:hz [] :ids []} :ids nil :amp 0.8})\n enc (:enc st)]\n (cond\n (and (= inlet :audio) (:error value)) {:state st :effects [[:print (:error value)]] :show {:label \"no MIDI\"}}\n (and (= inlet :audio) (contains? value :port)) {:state st :show {:label (or (:port value) \"no MIDI output\")}}\n (= inlet :audio) {:state st}\n (= inlet 1) {:state (assoc st :ids (when (sequential? value) (vec value)))}\n (and (vector? value) (= :gain (first value)) (number? (second value))) {:state (assoc st :amp (api/clamp (second value) 0 1))}\n (#{:clear :stop} value)\n (let [[e2 ms] (events enc (map (fn [id] {:type :note :id id :gate false}) (keys (:voices enc))))]\n (send (assoc st :enc e2 :snap {:hz [] :ids []}) ms))\n (map? value) (let [[e2 ms] (out-step enc value)] (send (assoc st :enc e2) ms))\n (or (number? value) (sequential? value))\n (let [hz (vec (filter number? (if (number? value) [value] value)))\n snap {:hz hz :ids (when (= (count (:ids st)) (count hz)) (:ids st))}\n [e2 ms] (events enc (diff (:snap st) snap (:amp st)))]\n (send (assoc st :enc e2 :snap snap) ms))\n :else {:state st})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"midiout\" (when (:mpe args) \" mpe\")))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the port, while ▶ runs ──\n :audio {:create (fn [ac b _]\n (let [words (rest (.split (.trim (str (:text b))) #\"\\s+\"))\n mpe (some #{\"mpe\"} words)\n nums (keep #(let [n (js/parseFloat %)] (when-not (js/isNaN n) n)) words)\n port-n (or (second nums) 1)\n r (or (nth nums 2 nil) 48)\n node {:ac ac :port (atom nil) :alive (atom true) :inlets [] :outlets []}]\n (-> (access)\n (.then (fn [m]\n (when @(:alive node)\n (let [outs (vec (js/Array.from (.values (.-outputs m))))\n p (get outs (dec port-n))]\n (reset! (:port node) p)\n (api/report! (:id b) {:port (when p (str \"→ \" (.-name p)))} nil)\n (when (and p mpe) (doseq [msg (setup r)] (.send p (clj->js (encode msg)))))))))\n (.catch (fn [e] (api/report! (:id b) {:error (str \"midiout: \" (.-message e))} nil))))\n node))\n :effects {:send (fn [node bytes at]\n (when-let [p @(:port node)]\n (let [ac (:ac node)\n ;; at the time of the message on the audio clock, as a time of the page\n ts (+ (js/performance.now) (* 1000 (max 0 (- (or at 0) (.-currentTime ac)))))]\n (doseq [b bytes] (.send p (clj->js b) ts)))))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n ;; nothing left sounding on the synthesizer\n (when-let [p @(:port node)]\n (doseq [ch (range 16)] (.send p #js [(+ 0xB0 ch) 123 0]))))}})\n"
32
+ },
33
+ {
34
+ "class": "motion",
35
+ "license": "MPL-2.0",
36
+ "doc": "A phone's (or a tablet's) motion while ▶ runs: its tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat — smoothed, and sent only when it moves —; and a shake, when it is shaken harder than shake (14 m/s²), once with a pause after it. Out: [x y], the strength of each shake, and the events ({:type :tilt :x :y :alpha :beta :gamma}, {:type :shake :value}) for oscout or a room. smooth (0.3) is how much of the last value stays at each reading. iOS asks for permission at ▶. Open the work on the phone (Share/Export, Release/Perform) to play with it.",
37
+ "source": ";; motion · a phone's tilt and shake as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [r (fn [x d] (let [k (js/Math.pow 10 d)] (/ (js/Math.round (* x k)) k)))\n clamp (fn [x lo hi] (max lo (min hi x)))\n ;; the tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat\n tilt-xy (fn [beta gamma] [(clamp (/ (+ gamma 90) 180) 0 1) (clamp (/ (+ (clamp beta -90 90) 90) 180) 0 1)])\n mag (fn [[x y z]] (js/Math.sqrt (+ (* x x) (* y y) (* z z))))\n ;; a reading: smoothed, and sent only when it moves (sensors read ~60 times a second, moving or not);\n ;; a shake is one event, with a pause after it\n step (fn [st t rd smooth shake]\n (cond\n (number? (:gamma rd))\n (let [[tx ty] (tilt-xy (or (:beta rd) 0) (:gamma rd))\n x (if (:x st) (+ (* smooth (:x st)) (* (- 1 smooth) tx)) tx)\n y (if (:y st) (+ (* smooth (:y st)) (* (- 1 smooth) ty)) ty)\n [sx sy] (:sent st) st (assoc st :x x :y y)]\n (if (and sx (< (js/Math.abs (- x sx)) 0.004) (< (js/Math.abs (- y sy)) 0.004))\n [st nil]\n [(assoc st :sent [x y])\n (cond-> {:src :motion :type :tilt :x (r x 3) :y (r y 3) :beta (r (or (:beta rd) 0) 1) :gamma (r (:gamma rd) 1)}\n (number? (:alpha rd)) (assoc :alpha (r (:alpha rd) 1)))]))\n (or (:acc rd) (:accg rd))\n (let [m (if (:acc rd) (mag (:acc rd)) (js/Math.abs (- (mag (:accg rd)) 9.81)))]\n (if (and (> m shake) (or (nil? (:last-shake st)) (>= (- t (:last-shake st)) 0.3)))\n [(assoc st :last-shake t) {:src :motion :type :shake :value (r m 1)}]\n [st nil]))\n :else [st nil]))]\n {;; ── about ──\n :class \"motion\"\n :license \"MPL-2.0\"\n :doc \"A phone's (or a tablet's) motion while ▶ runs: its tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat — smoothed, and sent only when it moves —; and a shake, when it is shaken harder than shake (14 m/s²), once with a pause after it. Out: [x y], the strength of each shake, and the events ({:type :tilt :x :y :alpha :beta :gamma}, {:type :shake :value}) for oscout or a room. smooth (0.3) is how much of the last value stays at each reading. iOS asks for permission at ▶. Open the work on the phone (Share/Export, Release/Perform) to play with it.\"\n :usage \"motion [smooth] [shake]\"\n :io [0 3]\n :size [96 30]\n :args [[:smooth 0.3] [:shake 14]]\n :help {:inlets []\n :outlets [\"[x y], 0…1 each, when the tilt moves\" \"the strength of a shake (m/s²)\" \"every event, as a map\"]\n :example \"(box :b1 \\\"motion\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Open this on a phone, press ▶, and tilt it.\"\n :see [\"gamepad\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args at]}]\n (if (and (= inlet :audio) (map? value))\n (if (:error value)\n {:effects [[:print (:error value)]] :show {:label \"no motion\"}}\n (let [[st e] (step (or state {}) (or at 0) value (api/clamp (:smooth args) 0 0.95) (api/clamp (:shake args) 2 60))]\n (cond\n (nil? e) {:state st}\n (= :tilt (:type e)) {:state st :out [[0 [(:x e) (:y e)]] [2 e]] :show {:x (:x e) :y (:y e)}}\n :else {:state st :out [[1 (:value e)] [2 e]] :show (assoc (select-keys st [:x :y]) :shake true)})))\n {}))\n\n ;; ── view: where the tilt is ──\n :derive (fn [{:keys [shown]}] {:cx (+ 60 (* 30 (- (or (:x shown) 0.5) 0.5) 2)) :cy (+ 15 (* 10 (- 0.5 (or (:y shown) 0.5)) 2))\n :dot (if (:shake shown) :kairos :accent)})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 6 :y 19 :size 10 :fill :soft} \"motion\"]\n [:rect {:x 46 :y 4 :w 46 :h 22 :r 2 :stroke :grid :fill :bg}]\n [:circle {:cx :$cx :cy :$cy :r 4 :stroke :$dot :fill :$dot}]]\n\n ;; ── outside: the sensors, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [node {:alive (atom true) :inlets [] :outlets []}\n report (fn [rd] (when @(:alive node) (api/report! (:id b) rd nil)))\n on-tilt (fn [e] (when (number? (.-gamma e)) (report {:alpha (.-alpha e) :beta (.-beta e) :gamma (.-gamma e)})))\n on-move (fn [e] (let [a (.-acceleration e) g (.-accelerationIncludingGravity e)]\n (cond (and a (number? (.-x a))) (report {:acc [(.-x a) (.-y a) (.-z a)]})\n (and g (number? (.-x g))) (report {:accg [(.-x g) (.-y g) (.-z g)]}))))\n listen! (fn [] (.addEventListener js/window \"deviceorientation\" on-tilt)\n (.addEventListener js/window \"devicemotion\" on-move))\n ask (some-> (.-DeviceOrientationEvent js/window) .-requestPermission)]\n ;; iOS asks first, and only from a gesture: ▶ is one\n (if (fn? ask)\n (-> (ask) (.then (fn [r] (if (= r \"granted\") (listen!) (report {:error \"motion: refused\"}))))\n (.catch (fn [e] (report {:error (str \"motion: \" (.-message e))}))))\n (listen!))\n (assoc node :off (fn [] (.removeEventListener js/window \"deviceorientation\" on-tilt)\n (.removeEventListener js/window \"devicemotion\" on-move)))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
38
+ },
39
+ {
40
+ "class": "oscin",
41
+ "license": "MPL-2.0",
42
+ "doc": "OSC in, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine), while ▶ runs: what SuperCollider, Max, Pd or TouchOSC send to the relay's port (57121) arrives here. The addresses oscout writes are events again (/kairotic/note id freq amp gate is {:type :note …}, /kairotic/glide, /kairotic/cc, /kairotic/tilt…); any other one is {:type :osc :address \"/x\" :args […] :from \"host:port\"}. pattern takes only the addresses that match it (OSC patterns: ? * [a-z] [!a] {note,glide}): oscin /synth/*/cutoff. Out: the event, and its values alone (the args of an OSC message; the Hz of a note) for a number box. [:relay \"ws://…\"] changes the bridge for the whole page.",
43
+ "source": ";; oscin · OSC in, through a relay's bridge: from SuperCollider, Max, Pd, TouchOSC… as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [default-url \"ws://localhost:8765/osc\"\n relay-url (fn [] (or (try (.getItem js/localStorage \"kairotic-osc-relay\") (catch :default _ nil)) default-url))\n ;; the same shared sockets as oscout (one per address, for every osc box of the page)\n socket (fn [url]\n (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))\n s (aget all url)]\n (if (and s (< (.. s -ws -readyState) 2))\n s\n (let [ws (js/WebSocket. url)\n s #js {:ws ws :listeners #js [] :queue #js []}]\n (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))\n (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]\n (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))\n (aset all url s)\n s))))\n r4 (fn [x] (if (number? x) (/ (js/Math.round (* x 10000)) 10000) x))\n ;; ── the /kairotic/… addresses are events again; any other address arrives as it is ──\n osc->event (fn [{:keys [address args from]}]\n (let [a (vec args)]\n (merge (cond-> {:src :osc} from (assoc :from from))\n (case address\n \"/kairotic/note\" (cond-> {:type :note :id (nth a 0 0) :gate (not= 0 (nth a 3 1))}\n (number? (get a 1)) (assoc :freq (r4 (get a 1)))\n (and (number? (get a 2)) (not= 0 (nth a 3 1))) (assoc :amp (r4 (get a 2))))\n \"/kairotic/glide\" {:type :glide :id (nth a 0 0) :freq (r4 (nth a 1 0))}\n \"/kairotic/cc\" {:type :cc :ch (nth a 0 1) :cc (nth a 1 0) :value (r4 (nth a 2 0))}\n \"/kairotic/pressure\" {:type :pressure :id (nth a 0 0) :value (r4 (nth a 1 0))}\n \"/kairotic/tilt\" {:type :tilt :x (r4 (nth a 0 0.5)) :y (r4 (nth a 1 0.5))}\n \"/kairotic/shake\" {:type :shake :value (r4 (nth a 0 0))}\n (\"/kairotic/clock\" \"/kairotic/start\" \"/kairotic/stop\" \"/kairotic/continue\") {:type (keyword (subs address 10))}\n {:type :osc :address address :args (mapv r4 a)}))))\n ;; ── OSC address patterns (OSC 1.0): ? * [a-z] [!a] {foo,bar}, none of them across a / ──\n re-esc (fn [s] (.replace s (js/RegExp. \"[.*+?^${}()|[\\\\]\\\\\\\\]\" \"g\") \"\\\\$&\"))\n pattern-re (fn [p]\n (loop [cs (seq p) out \"^\"]\n (if-not cs\n (js/RegExp. (str out \"$\"))\n (let [c (first cs)]\n (case c\n \"?\" (recur (next cs) (str out \"[^/]\"))\n \"*\" (recur (next cs) (str out \"[^/]*\"))\n \"[\" (let [body (take-while #(not= \"]\" %) (next cs)) neg (= \"!\" (first body))\n body (apply str (if neg (rest body) body))]\n (recur (next (drop-while #(not= \"]\" %) (next cs)))\n (str out \"[\" (when neg \"^\") (.replace body (js/RegExp. \"[\\\\\\\\^]\" \"g\") \"\\\\$&\") \"]\")))\n \"{\" (let [body (apply str (take-while #(not= \"}\" %) (next cs)))]\n (recur (next (drop-while #(not= \"}\" %) (next cs)))\n (str out \"(?:\" (apply str (interpose \"|\" (map re-esc (.split body \",\")))) \")\")))\n (recur (next cs) (str out (re-esc c))))))))\n matches? (fn [p address] (or (empty? p) (boolean (.test (pattern-re p) address))))]\n {;; ── about ──\n :class \"oscin\"\n :license \"MPL-2.0\"\n :doc \"OSC in, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine), while ▶ runs: what SuperCollider, Max, Pd or TouchOSC send to the relay's port (57121) arrives here. The addresses oscout writes are events again (/kairotic/note id freq amp gate is {:type :note …}, /kairotic/glide, /kairotic/cc, /kairotic/tilt…); any other one is {:type :osc :address \\\"/x\\\" :args […] :from \\\"host:port\\\"}. pattern takes only the addresses that match it (OSC patterns: ? * [a-z] [!a] {note,glide}): oscin /synth/*/cutoff. Out: the event, and its values alone (the args of an OSC message; the Hz of a note) for a number box. [:relay \\\"ws://…\\\"] changes the bridge for the whole page.\"\n :usage \"oscin [pattern]\"\n :io [1 2]\n :size [110 30]\n :help {:inlets [\"[:relay \\\"ws://…/osc\\\"]\"]\n :outlets [\"every message that matches, as an event\" \"its values: the args of an OSC message, or the Hz of a note\"]\n :example \"(box :b1 \\\"oscin /kairotic/*\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Run npx @kairotic/relay --osc, press ▶, and from SuperCollider: NetAddr(\\\"127.0.0.1\\\", 57121).sendMsg(\\\"/kairotic/note\\\", 1, 440, 0.5, 1).\"\n :see [\"oscout\" \"midiin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (cond\n (and (= inlet :audio) (:event value))\n (let [e (:event value)]\n {:out [[1 (if (= :osc (:type e)) (:args e) (or (:freq e) (:value e) (:x e)))] [0 e]]\n :show {:label (or (:address e) (str \"/kairotic/\" (name (:type e))))}})\n (and (= inlet :audio) (:status value)) {:show {:label (:status value)}}\n (and (vector? value) (= :relay (first value)) (string? (second value)))\n {:effects [[:relay (second value)]] :show {:label \"relay set: ▶ again\"}}\n :else {}))\n :tasks {:relay (fn [url _] (try (.setItem js/localStorage \"kairotic-osc-relay\" url) (catch :default _ nil)) (js/Promise.resolve url))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"oscin\")})\n :view [[:rect {:x 1 :y 1 :w 108 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the bridge, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [pattern (or (second (.split (.trim (str (:text b))) #\"\\s+\")) \"\")\n node {:alive (atom true) :inlets [] :outlets []}\n s (socket (relay-url))\n l (fn [f] (when (and @(:alive node) (.-address f) (matches? pattern (.-address f)))\n (api/report! (:id b) {:event (osc->event (js->clj f :keywordize-keys true))} nil)))]\n (.push (.-listeners s) l)\n (set! (.. s -ws -onerror)\n (fn [_] (api/report! (:id b) {:status \"no relay: npx @kairotic/relay --osc\"} nil)))\n (assoc node :off (fn [] (set! (.-listeners s) (.filter (.-listeners s) (fn [x & _] (not= x l))))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
44
+ },
45
+ {
46
+ "class": "oscout",
47
+ "license": "MPL-2.0",
48
+ "doc": "OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \"ws://…\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶.",
49
+ "source": ";; oscout · Kairotic events and messages as OSC, through a relay's bridge (SuperCollider, Max, Pd, TouchOSC…)\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [;; ── the bridge: one socket per address, shared by every osc box of the page ──\n ;; A page cannot send UDP: the relay started with --osc does it (npx @kairotic/relay --osc).\n default-url \"ws://localhost:8765/osc\"\n relay-url (fn [] (or (try (.getItem js/localStorage \"kairotic-osc-relay\") (catch :default _ nil)) default-url))\n socket (fn [url]\n (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))\n s (aget all url)]\n (if (and s (< (.. s -ws -readyState) 2))\n s\n (let [ws (js/WebSocket. url)\n s #js {:ws ws :listeners #js [] :queue #js []}]\n (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))\n (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]\n (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))\n (aset all url s)\n s))))\n send! (fn [url m] (let [s (socket url) ws (.-ws s) j (js/JSON.stringify (clj->js m))]\n (if (= 1 (.-readyState ws)) (.send ws j) (.push (.-queue s) j))))\n num (fn [x] (if (number? x) x 0))\n ;; ── an event as OSC: /kairotic/<type> with its values in a fixed order, for a SynthDef or a Max patch ──\n event->osc (fn [e]\n (case (:type e)\n :note {:address \"/kairotic/note\" :types \"iffi\" :args [(num (:id e)) (num (:freq e)) (num (or (:amp e) (when (:gate e) 0.8))) (if (:gate e) 1 0)]}\n :glide {:address \"/kairotic/glide\" :types \"if\" :args [(num (:id e)) (num (:freq e))]}\n :cc {:address \"/kairotic/cc\" :types \"iif\" :args [(num (:ch e)) (num (:cc e)) (num (:value e))]}\n :pressure {:address \"/kairotic/pressure\" :types \"if\" :args [(num (:id e)) (num (:value e))]}\n :tilt {:address \"/kairotic/tilt\" :types \"ff\" :args [(:x e) (:y e)]}\n :shake {:address \"/kairotic/shake\" :types \"f\" :args [(:value e)]}\n (:button :axis) {:address (str \"/kairotic/pad/\" (if (:name e) (name (:name e)) (str (if (= :axis (:type e)) \"a\" \"b\") (or (:axis e) (:button e)))))\n :args (if (some? (:gate e)) [(:value e) (if (:gate e) 1 0)] [(:value e)])}\n :serial (cond (:values e) {:address \"/kairotic/serial\" :args (vec (:values e))}\n (number? (:value e)) {:address (str \"/kairotic/serial/\" (:key e)) :args [(:value e)]}\n :else {:address \"/kairotic/serial\" :types \"s\" :args [(str (:text e))]})\n (:clock :start :stop :continue) {:address (str \"/kairotic/\" (name (:type e))) :args []}\n nil))\n ;; a list that starts with an address: (/synth/freq 440) → /synth/freq 440\n address? (fn [x] (let [s (cond (string? x) x (keyword? x) (str (when (namespace x) (str (namespace x) \"/\")) (name x)) (symbol? x) (str x))]\n (when (and s (= \"/\" (subs s 0 1))) s)))\n clean (fn [x] (cond (keyword? x) (name x) (or (number? x) (string? x) (boolean? x)) x :else (str x)))]\n {;; ── about ──\n :class \"oscout\"\n :license \"MPL-2.0\"\n :doc \"OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \\\"ws://…\\\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶.\"\n :usage \"oscout [target]\"\n :io [1 0]\n :size [96 30]\n :args [[:target nil]]\n :help {:inlets [\"an event map, a list (address args…), or [:relay \\\"ws://…/osc\\\"]\"]\n :outlets []\n :example \"(box :b1 \\\"msg /kairotic/hello 1 2.5\\\" 40 30)\\n(box :b2 \\\"oscout\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Run npx @kairotic/relay --osc on this machine and click the message: SuperCollider (sclang, port 57120) receives /kairotic/hello 1 2.5.\"\n :see [\"oscin\" \"midiout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (cond\n (and (vector? value) (= :relay (first value)) (string? (second value)))\n {:effects [[:relay (second value)]] :show {:label \"relay set\"}}\n (and (map? value) (not= :osc (:src value)))\n (if-let [m (event->osc value)]\n {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}}\n {})\n (and (sequential? value) (address? (first value)))\n (let [m {:address (address? (first value)) :args (mapv clean (rest value))}]\n {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}})\n :else {}))\n ;; with or without ▶: OSC is a message, not a sound\n :tasks {:osc (fn [m _] (send! (relay-url) m) (js/Promise.resolve true))\n :relay (fn [url _] (try (.setItem js/localStorage \"kairotic-osc-relay\" url) (catch :default _ nil)) (js/Promise.resolve url))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"oscout\" (when (:target args) (str \" \" (name (:target args))))))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]})\n"
50
+ },
51
+ {
52
+ "class": "serial",
53
+ "license": "MPL-2.0",
54
+ "doc": "A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\"512 300 1\", or with commas) go out as a list on the left; key:value pairs (\"pot:512 light=300\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \"pot\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \"open\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari.",
55
+ "source": ";; serial · a board on a serial port (an Arduino, an ESP32…): its lines of text as values and events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [number-of (fn [s] (when (re-matches #\"[-+]?(\\d+\\.?\\d*|\\.\\d+)([eE][-+]?\\d+)?\" s) (js/parseFloat s)))\n ;; a line: \"512 300 1\" (or with commas) → values; \"pot:512 light=300\" → one event per key; else text\n line-events (fn [line]\n (let [line (.trim line) ev (fn [m] (merge {:src :serial :type :serial} m))\n words (remove empty? (.split line (js/RegExp. \"[\\\\s,;]+\")))]\n (cond\n (empty? line) []\n (every? number-of words) [(ev {:values (mapv number-of words)})]\n (every? #(re-matches #\"[^:=]+[:=][^:=]+\" %) words)\n (vec (for [w words :let [[k v] (.split w (js/RegExp. \"[:=]\"))]]\n (ev (if-let [n (number-of v)] {:key k :value n} {:key k :text v}))))\n :else [(ev {:text line})])))\n ;; text comes in pieces that do not respect lines: what follows the last newline waits for the next\n chunk (fn [buf text]\n (let [lines (.split (str buf text) (js/RegExp. \"\\\\r?\\\\n\"))\n rest-buf (last lines)]\n [(if (> (count rest-buf) 512) \"\" rest-buf) (vec (mapcat line-events (butlast lines)))]))]\n {;; ── about ──\n :class \"serial\"\n :license \"MPL-2.0\"\n :doc \"A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\\\"512 300 1\\\", or with commas) go out as a list on the left; key:value pairs (\\\"pot:512 light=300\\\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \\\"pot\\\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \\\"open\\\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari.\"\n :usage \"serial [baud]\"\n :io [1 2]\n :size [96 30]\n :args [[:baud 115200]]\n :help {:inlets [\":open (asks for the port), :close, or a line to send to the board\"]\n :outlets [\"the numbers of a line (a list), or [key value] for each key:value\" \"every line, as events\"]\n :example \"(box :b1 \\\"msg :open\\\" 40 30)\\n(box :b2 \\\"serial 9600\\\" 40 70)\\n(box :b3 \\\"print\\\" 40 120)\\n(connect :b1 0 :b2 0)\\n(connect :b2 0 :b3 0)\"\n :try \"Press ▶, click open and choose the board's port: what it prints arrives as numbers.\"\n :see [\"motion\" \"gamepad\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [buf (or (:buf state) \"\")]\n (cond\n (and (= inlet :audio) (:error value)) {:state state :effects [[:print (:error value)]] :show {:label \"no port\"}}\n (and (= inlet :audio) (:status value)) {:state state :show {:label (:status value)}}\n (and (= inlet :audio) (string? (:text value)))\n (let [[b2 es] (chunk buf (:text value))]\n (cond-> {:state (assoc state :buf b2)\n :out (vec (mapcat (fn [e] [(cond (:values e) [0 (:values e)]\n (contains? e :value) [0 [(:key e) (:value e)]]\n :else [0 (or (:text e) \"\")])\n [1 e]])\n es))\n }\n (seq es) (assoc :show {:label (let [e (last es)] (cond (:values e) (str (:values e)) (:key e) (str (:key e) \" \" (or (:value e) (:text e))) :else (:text e)))})))\n (#{:open} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}\n (#{:close} value) {:effects [[:close true]]}\n (string? value) {:effects [[:write value]]}\n (sequential? value) {:effects [[:write (apply str (interpose \" \" (map #(if (keyword? %) (name %) (str %)) value)))]]}\n :else {})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"serial\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the port, while ▶ runs ──\n :audio {:create (fn [_ b _] {:id (:id b) :port (atom nil) :writer (atom nil) :reader (atom nil) :alive (atom true) :inlets [] :outlets []})\n :effects {:open (fn [node baud _]\n (let [report (fn [v] (when @(:alive node) (api/report! (:id node) v nil)))]\n (if-not (.-serial js/navigator)\n (report {:error \"serial: this browser has no Web Serial (Chrome, Edge or Firefox 151+)\"})\n (-> (.requestPort (.-serial js/navigator))\n (.then (fn [port] (.then (.open port #js {:baudRate baud}) (fn [_] port))))\n (.then (fn [port]\n (reset! (:port node) port)\n (reset! (:writer node) (.getWriter (.-writable port)))\n (report {:status (str \"open · \" baud)})\n (let [dec (js/TextDecoderStream.)\n _ (.catch (.pipeTo (.-readable port) (.-writable dec)) (fn [_] nil))\n reader (.getReader (.-readable dec))]\n (reset! (:reader node) reader)\n ((fn step []\n (-> (.read reader)\n (.then (fn [r] (if (.-done r)\n (report {:status \"closed\"})\n (do (report {:text (.-value r)}) (step)))))\n (.catch (fn [_] (report {:status \"closed\"})))))))))\n (.catch (fn [e] (report {:error (str \"serial: \" (.-message e))})))))))\n :write (fn [node line _]\n (when-let [w @(:writer node)] (.write w (.encode (js/TextEncoder.) (str line \"\\n\")))))\n :close (fn [node _ _]\n (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))\n (when-let [w @(:writer node)] (.releaseLock w))\n (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50))\n (reset! (:port node) nil) (reset! (:writer node) nil))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))\n (when-let [w @(:writer node)] (try (.releaseLock w) (catch :default _ nil)))\n (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50)))}})\n"
56
+ }
57
+ ]
58
+ };
@@ -0,0 +1,28 @@
1
+ // Generated by packages/build.mjs
2
+ export default {
3
+ "package": "@kairotic/net",
4
+ "version": "0.1.4",
5
+ "api": 1,
6
+ "author": "bonuoq",
7
+ "license": "MPL-2.0",
8
+ "components": [
9
+ {
10
+ "class": "pulse",
11
+ "license": "MPL-2.0",
12
+ "doc": "The room's beat, while ▶ runs: the count of each pulse (0 at the start of the tempo) on the left, on the audio clock, divided (1, beats; 2, eighths; 0.25, bars of four); on the right, the bpm when the tempo starts or changes, and 0 when it stops. The tempo is one for the whole room — the same beat on every page, from the room's clock, whatever each computer's clock says —; start [bpm], stop and bpm n (which keeps the beat where it is) change it for everyone, as the Room tab does. Outside a room it is this page's tempo.",
13
+ "source": ";; pulse · the room's beat: one tempo for everyone in the room, the same beat on every page\n;; Part of @kairotic/net. Written against the Kairotic API (api/…). Discussion #135.\n(let [room (fn [] (.-kairoticRoom js/window))]\n {;; ── about ──\n :class \"pulse\"\n :license \"MPL-2.0\"\n :doc \"The room's beat, while ▶ runs: the count of each pulse (0 at the start of the tempo) on the left, on the audio clock, divided (1, beats; 2, eighths; 0.25, bars of four); on the right, the bpm when the tempo starts or changes, and 0 when it stops. The tempo is one for the whole room — the same beat on every page, from the room's clock, whatever each computer's clock says —; start [bpm], stop and bpm n (which keeps the beat where it is) change it for everyone, as the Room tab does. Outside a room it is this page's tempo.\"\n :usage \"pulse [division]\"\n :io [1 2]\n :size [96 30]\n :args [[:division 1]]\n :help {:inlets [\":start [bpm] · :stop · :bpm n: the tempo of the whole room\"]\n :outlets [\"the count of each pulse, on its beat\" \"the bpm (0 when it stops)\"]\n :example \"(box :b1 \\\"msg :start 100\\\" 40 30)\\n(box :b2 \\\"msg :stop\\\" 140 30)\\n(box :b3 \\\"pulse\\\" 40 80)\\n(box :b4 \\\"print\\\" 40 130)\\n(connect :b1 0 :b3 0)\\n(connect :b2 0 :b3 0)\\n(connect :b3 0 :b4 0)\"\n :try \"Press ▶ and click start 100: a count every beat, a second later. In a shared room, every page with a pulse box counts the same beat.\"\n :see [\"share\" \"shared\" \"metro\" \"player\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (cond\n (and (= inlet :audio) (number? (:count value))) {:out [[0 (:count value)]] :show {:count (:count value)}}\n (and (= inlet :audio) (contains? value :bpm)) {:out [[1 (or (:bpm value) 0)]] :show {:bpm (:bpm value)}}\n (= inlet :task) {}\n (#{:stop} value) {:effects [[:tempo [:stop]]]}\n (#{:start} value) {:effects [[:tempo [:start 120]]]}\n (and (sequential? value) (#{:start} (first value))) {:effects [[:tempo [:start (or (api/num-of (rest value)) 120)]]]}\n (and (sequential? value) (#{:bpm} (first value)) (api/num-of (rest value))) {:effects [[:tempo [:bpm (api/num-of (rest value))]]]}\n :else {}))\n :tasks {:tempo (fn [[op x] _]\n (if-let [r (room)]\n (do (case op :start ((.-start r) x) :bpm ((.-bpm r) x) :stop ((.-stop r))) (js/Promise.resolve true))\n (js/Promise.reject (js/Error. \"pulse: this page has no room layer\"))))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (cond (number? (:count shown)) (str \"pulse \" (:count shown))\n (:bpm shown) (str \"pulse · \" (api/nice (:bpm shown)) \" bpm\")\n :else \"pulse\")\n :dot (if (number? (:count shown)) :kairos :grid)})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :kairos :fill :bg}]\n [:circle {:cx 84 :cy 15 :r 5 :stroke :$dot :fill :$dot}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the room's tempo, read every 25 ms, each pulse reported 100 ms ahead on the audio clock ──\n :audio {:create (fn [ac b _]\n (let [div (let [n (js/parseFloat (second (.split (.trim (str (:text b))) #\"\\s+\")))] (if (and (js/isFinite n) (pos? n)) n 1))\n node {:alive (atom true) :until (atom nil) :tempo (atom :none) :inlets [] :outlets []}\n tick (fn []\n (when-let [r (room)]\n (let [t ((.-tempo r)) t (when t (js->clj t :keywordize-keys true)) n ((.-now r))]\n (when (not= t @(:tempo node))\n (reset! (:tempo node) t) (reset! (:until node) nil)\n (api/report! (:id b) {:bpm (:bpm t)} nil))\n (when-let [{:keys [t0 bpm]} t]\n (let [per (/ 60000 (* bpm div))\n from (max n (or @(:until node) n)) to (+ n 100)]\n (doseq [k (range (js/Math.ceil (/ (- from t0) per)) (inc (js/Math.floor (/ (- to t0) per))))\n :let [at (+ t0 (* k per))] :when (and (>= k 0) (>= at from) (< at to))]\n (api/report! (:id b) {:count k} (+ (.-currentTime ac) (/ (- at n) 1000))))\n (reset! (:until node) to))))))\n timer (js/setInterval (fn [] (when @(:alive node) (tick))) 25)]\n (assoc node :timer timer)))\n :dispose (fn [node] (reset! (:alive node) false) (js/clearInterval (:timer node)))}})\n"
14
+ },
15
+ {
16
+ "class": "share",
17
+ "license": "MPL-2.0",
18
+ "doc": "Shares what arrives with everyone in the room, on a channel (main if none): every shared box of the room listening to that channel sends it out — on every page, this one too. Any value: a number, a list, an event from midiin or motion, a map. It goes on the room's reliable channel, in order, with or without ▶. Outside a shared room it reaches the shared boxes of this page only. It is a message of the moment, not a gesture: the history does not keep it.",
19
+ "source": ";; share · a value to everyone in the room, on a channel\n;; Part of @kairotic/net. Written against the Kairotic API (api/…). Discussion #135.\n(let [room (fn [] (.-kairoticRoom js/window))]\n {;; ── about ──\n :class \"share\"\n :license \"MPL-2.0\"\n :doc \"Shares what arrives with everyone in the room, on a channel (main if none): every shared box of the room listening to that channel sends it out — on every page, this one too. Any value: a number, a list, an event from midiin or motion, a map. It goes on the room's reliable channel, in order, with or without ▶. Outside a shared room it reaches the shared boxes of this page only. It is a message of the moment, not a gesture: the history does not keep it.\"\n :usage \"share [channel]\"\n :io [1 0]\n :size [96 30]\n :args [[:channel nil]]\n :help {:inlets [\"any value: it goes to everyone in the room\"]\n :outlets []\n :example \"(box :b1 \\\"msg 60 64 67\\\" 40 30)\\n(box :b2 \\\"share chords\\\" 40 80)\\n(box :b3 \\\"shared chords\\\" 200 30)\\n(box :b4 \\\"print\\\" 200 80)\\n(connect :b1 0 :b2 0)\\n(connect :b3 0 :b4 0)\"\n :try \"Press ▶ and click the message: print shows it, and so does every page of the room with a shared chords box.\"\n :see [\"shared\" \"pulse\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value args]}]\n (if (= inlet :task)\n {}\n {:effects [[:share [(if (:channel args) (name (:channel args)) \"main\") value]]]\n :show {:label (let [s (pr-str value)] (if (> (count s) 14) (str (subs s 0 13) \"…\") s))}}))\n :tasks {:share (fn [[ch v] _]\n (if-let [r (room)]\n (do ((.-share r) ch v) (js/Promise.resolve true))\n (js/Promise.reject (js/Error. \"share: this page has no room layer\"))))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"share \" (if (:channel args) (name (:channel args)) \"main\")))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :kairos :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]})\n"
20
+ },
21
+ {
22
+ "class": "shared",
23
+ "license": "MPL-2.0",
24
+ "doc": "What anyone in the room shares on a channel (main if none) with a share box — this page included —, while ▶ runs: the value on the left, the name of who shared it on the right. A midiin on one page and a shared box feeding synth~ on another is playing someone else's instrument; an event map from motion on a phone moves a knob on the computer.",
25
+ "source": ";; shared · what is shared in the room on a channel\n;; Part of @kairotic/net. Written against the Kairotic API (api/…). Discussion #135.\n(let [room (fn [] (.-kairoticRoom js/window))]\n {;; ── about ──\n :class \"shared\"\n :license \"MPL-2.0\"\n :doc \"What anyone in the room shares on a channel (main if none) with a share box — this page included —, while ▶ runs: the value on the left, the name of who shared it on the right. A midiin on one page and a shared box feeding synth~ on another is playing someone else's instrument; an event map from motion on a phone moves a knob on the computer.\"\n :usage \"shared [channel]\"\n :io [0 2]\n :size [96 30]\n :args [[:channel nil]]\n :help {:inlets []\n :outlets [\"the value shared\" \"who shared it\"]\n :example \"(box :b1 \\\"shared notes\\\" 40 30)\\n(box :b2 \\\"synth~\\\" 40 80)\\n(box :b3 \\\"dac~\\\" 40 130)\\n(connect :b1 0 :b2 0)\\n(connect :b2 0 :b3 0)\\n(connect :b2 0 :b3 1)\"\n :try \"In a shared room, press ▶: what someone sends to a share notes box, you hear.\"\n :see [\"share\" \"pulse\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (cond\n (and (= inlet :audio) (contains? value :v))\n {:out [[1 (str (:from value))] [0 (:v value)]] :show {:label (str (:from value) \" → \" (let [s (pr-str (:v value))] (if (> (count s) 10) (str (subs s 0 9) \"…\") s)))}}\n (and (= inlet :audio) (:error value)) {:effects [[:print (:error value)]]}\n :else {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"shared \" (if (:channel args) (name (:channel args)) \"main\")))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :kairos :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the room's channel, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [ch (or (second (.split (.trim (str (:text b))) #\"\\s+\")) \"main\")\n node {:alive (atom true) :inlets [] :outlets []}]\n (if-let [r (room)]\n (assoc node :off ((.-onShare r) ch (fn [v from] (when @(:alive node) (api/report! (:id b) {:v v :from from} nil)))))\n (do (api/report! (:id b) {:error \"shared: this page has no room layer\"} nil) (assoc node :off (fn [] nil))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
26
+ }
27
+ ]
28
+ };
@@ -0,0 +1,34 @@
1
+ // Generated by packages/build.mjs
2
+ export default {
3
+ "package": "@kairotic/patterns",
4
+ "version": "0.2.1",
5
+ "api": 1,
6
+ "author": "bonuoq",
7
+ "license": "MPL-2.0",
8
+ "components": [
9
+ {
10
+ "class": "pattern",
11
+ "license": "MPL-2.0",
12
+ "doc": "A pattern as code: a Clojure expression that returns a sequence of event maps (phrases inside are flattened) or one map, read as a pbind. Its randomness is seeded by the box (pattern 7: the same for everyone), and pbind, pseq, pwhite, pchoose, pshuffle, pseries and pwalk give lazy sequences, as in Overtone. It sends its pattern whenever it changes, for a player. In a shared room it runs only after (trust-scripts true); a pbind needs no trust.",
13
+ "source": ";; pattern · a pattern as code: a Clojure expression that returns events, its randomness seeded\n;; Part of @kairotic/patterns. Written against the Kairotic API (api/…).\n;; Its source is evaluated (like a script), so in a shared room it does not run until this tab allows it:\n;; (trust-scripts true). Inside it, rand, rand-int, rand-nth and shuffle are seeded by the box (pattern 7),\n;; and pbind, pseq, pwhite, pchoose, pshuffle, pseries and pwalk are at hand.\n(let [opts-of (fn [args source]\n {:seed (or (:seed args) 0) :source source\n :repeat (if (:loop args) :inf (max 1 (js/Math.round (or (:repeat args) 1))))})\n pattern-of (fn [data args]\n (let [r (api/compiled \"pattern\" (:source data))]\n (when (= :ok (:status r)) (api/code-pattern (:value r) (opts-of args (:source data))))))]\n {;; ── about ──\n :class \"pattern\"\n :license \"MPL-2.0\"\n :doc \"A pattern as code: a Clojure expression that returns a sequence of event maps (phrases inside are flattened) or one map, read as a pbind. Its randomness is seeded by the box (pattern 7: the same for everyone), and pbind, pseq, pwhite, pchoose, pshuffle, pseries and pwalk give lazy sequences, as in Overtone. It sends its pattern whenever it changes, for a player. In a shared room it runs only after (trust-scripts true); a pbind needs no trust.\"\n :usage \"pattern [seed] [repeat] [loop]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:seed 0] [:repeat 1] [:loop false]]\n\n ;; ── data: its source, with its own history ──\n :display :code\n :language \"pattern\"\n :model api/code-model\n :template \"(pbind {:degree (pwhite 0 7)\\n :dur (pchoose [0.25 0.25 0.5])\\n :octave [5 5 6]}\\n :inf)\"\n\n ;; ── what it sends when it changes ──\n :sends (fn [{:keys [data args]}] (pattern-of data args))\n\n ;; ── logic ──\n :receive (fn [{:keys [data args]}]\n (let [r (api/compiled \"pattern\" (:source data))]\n (cond (= :ok (:status r)) {:out [[0 (pattern-of data args)]] :show :bang}\n (= :compiling (:status r)) {}\n :else {:effects [[:print (str \"pattern: \" (or (:error r) \"empty\"))]]})))})\n"
14
+ },
15
+ {
16
+ "class": "pbind",
17
+ "license": "MPL-2.0",
18
+ "doc": "A pattern as data: an EDN map whose values are sequences (vectors, the shorter ones starting again until the longest ends), constants and generators (#pat/choose [0.25 0.5], #pat/white [0 7], #pat/shuffle, #pat/walk, #pat/series, #pat/hold [4 [:c :g]] one value per 4 beats, #pat/chord [0 4 7]). It sends its pattern whenever it changes, for a player: the seed (pbind 7) makes its randomness the same for everyone, each key with its own. pbind 7 4 repeats it four times, pbind 7 loop for ever. A map on its inlet replaces it, [:set :dur [1 0.5]] one key, [:unset :amp] removes one.",
19
+ "source": ";; pbind · a pattern as data: an EDN map of sequences and #pat/… generators\n;; Part of @kairotic/patterns. Written against the Kairotic API (api/…).\n;; Its source is EDN, read without evaluating anything: safe in a shared room, like a tree box. What it\n;; sends is a pattern value (a factory of streams), never the sequence, so a player makes the events in\n;; each tab from the same source and seed and everyone hears the same.\n(let [;; the seed, the passes and loop, from the box text: pbind 7 · pbind 7 4 · pbind 7 loop\n opts-of (fn [args] {:seed (or (:seed args) 0)\n :repeat (if (:loop args) :inf (max 1 (js/Math.round (or (:repeat args) 1))))})\n spec-of (fn [data] (let [r (api/compiled \"pbind\" (:source data))] (when (= :ok (:status r)) (:value r))))\n ;; a new map for the box: written in its source, one gesture of the history\n rewrite (fn [m now]\n (let [ps (api/pbind-problems m)]\n (cond (seq ps) {:effects [[:print (str \"pbind: \" (first ps))]]}\n (= m now) {} ; the same again: nothing changes\n :else {:effects [[:keep {:source (api/pbind-source m)}]]})))]\n {;; ── about ──\n :class \"pbind\"\n :license \"MPL-2.0\"\n :doc \"A pattern as data: an EDN map whose values are sequences (vectors, the shorter ones starting again until the longest ends), constants and generators (#pat/choose [0.25 0.5], #pat/white [0 7], #pat/shuffle, #pat/walk, #pat/series, #pat/hold [4 [:c :g]] one value per 4 beats, #pat/chord [0 4 7]). It sends its pattern whenever it changes, for a player: the seed (pbind 7) makes its randomness the same for everyone, each key with its own. pbind 7 4 repeats it four times, pbind 7 loop for ever. A map on its inlet replaces it, [:set :dur [1 0.5]] one key, [:unset :amp] removes one.\"\n :usage \"pbind [seed] [repeat] [loop]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:seed 0] [:repeat 1] [:loop false]]\n\n ;; ── data: its source, with its own history ──\n :display :code\n :language \"pbind\"\n :model api/code-model\n :template \"{:degree [0 2 4 7 4 2]\\n :dur [0.5 0.5 0.5 0.5 1 1]\\n :amp #pat/white [0.2 0.4]}\"\n\n ;; ── what it sends when it changes ──\n :sends (fn [{:keys [data args]}]\n (when-let [m (spec-of data)] (api/pbind-pattern m (opts-of args))))\n\n ;; ── logic ──\n :receive (fn [{:keys [value data args]}]\n (let [r (api/compiled \"pbind\" (:source data))\n m (when (= :ok (:status r)) (:value r))]\n (cond\n (and (map? value) (not (api/pattern? value))) (rewrite value m)\n (and (vector? value) (= :set (first value)) (keyword? (second value)) (= 3 (count value)))\n (if m (rewrite (assoc m (second value) (nth value 2)) m) {:effects [[:print \"pbind: its source does not read yet\"]]})\n (and (vector? value) (= :unset (first value)) (keyword? (second value)))\n (if m (rewrite (dissoc m (second value)) m) {})\n m {:out [[0 (api/pbind-pattern m (opts-of args))]] :show :bang}\n (= :compiling (:status r)) {}\n :else {:effects [[:print (str \"pbind: \" (or (:error r) \"empty\"))]]})))})\n"
20
+ },
21
+ {
22
+ "class": "player",
23
+ "license": "MPL-2.0",
24
+ "doc": "Plays a pattern (from a pbind or a pattern box, on its right inlet) in one of three ways, chosen by what arrives on the left: start / stop — its own clock, every event lasting its :dur in beats at its bpm (quant: start on a multiple of that many beats); bang — one step, the next event now; a number — a position in beats (a ramp, a counter, a number you drag), where every event is a span from its onset to its end that sounds while the position is inside it: forwards it is entered at its onset, backwards at its end (:dir :back), and the spans passed over in one step sound within it; seek p, or a step more than jump (8) times the one before it or longer than limit (8) beats, goes there at once, sounding what contains p (with edges, only what starts at p); with spread, what a step passes keeps its rhythm, one step later. Out: the Hz of the notes sounding, their voice ids (for synth~ or a polyphonic faust~), the whole event (:beat :hz :ids added) and the beat; an event with :amp (0…1) sends [:gain amp] on the Hz outlet just before its notes, the loudness of the notes that start (synth~, a polyphonic faust~). A new pattern while it plays goes on from the same beat; the same pattern again changes nothing. Pitch: :freq, :note (MIDI, \"c4\", :c4), or :degree with :scale :root :octave; :dur, :legato or :sustain; :rest (or nil) is a silence.",
25
+ "source": ";; player · plays a pattern: by its own clock, one step at a time, or at a position in beats\n;; Part of @kairotic/patterns. Written against the Kairotic API (api/…).\n;; Like a reader: the pattern comes in on the right (as the buffer does) and time on the left, so one\n;; pattern can feed several players that move through it each in its own way.\n;; start / stop its own clock: every event lasts its :dur in beats, at `player bpm`\n;; bang one step: the next event, now (from a metro, an onset~, a key…)\n;; a number a position in beats (a ramp, a counter…): every event is a span that sounds\n;; while the position is inside it, entered at its onset going forwards and at its\n;; end going backwards; a jump (seek p, or a step far larger than the ones before)\n;; is there at once\n;; Out: the Hz of the notes sounding (left) after their voice ids (second), as mt play and reader do\n;; (for synth~ and a polyphonic faust~), the whole event (third) and the beat (right).\n;; Its logic is pure: the stream it plays is kept in its state, in this tab; nothing of it is in the work.\n(let [eps 1e-9\n burst 64 ; events in one instant, at most (a chord, a jump)\n spb (fn [st] (/ 60 (:bpm st))) ; seconds per beat\n word (fn [v] (cond (keyword? v) v\n (string? v) (keyword v)\n (and (vector? v) (keyword? (first v)) (= 1 (count v))) (first v)\n :else nil))\n ;; the loudness of an event's notes, for synth~ and a polyphonic faust~: [:gain a] on the Hz outlet,\n ;; just before the notes (only when the event has :amp or :gain)\n gain-out (fn [e hz] (let [a (or (:amp e) (:gain e))] (if (and (number? a) (seq hz)) [[0 [:gain a]]] [])))\n ;; the stream it plays: kept behind a function, so that printing its state (or the engine's) never\n ;; walks an endless sequence\n evs (fn [st] (when-let [f (:evs st)] (f)))\n with-evs (fn [st s] (assoc st :evs (constantly s)))\n ;; a new stream of its pattern, from the beginning\n fresh (fn [st] (if-let [p (:pattern st)] (-> st (with-evs (api/pattern-events p)) (assoc :beat 0)) (dissoc st :evs)))\n ;; [event onset st-after] for the next event, or nil\n take-next (fn [st] (when-let [e (first (evs st))]\n [e (:beat st) (-> st (with-evs (rest (evs st))) (update :beat + (api/event-dur e)))]))\n ;; leaves out the events that start before beat b (a new pattern, a jump)\n skip-to (fn [st b]\n (loop [st st i 0]\n (let [e (first (evs st))]\n (if (and e (< (:beat st) (- b eps)) (< i 100000))\n (recur (-> st (with-evs (rest (evs st))) (update :beat + (api/event-dur e))) (inc i))\n st))))\n ;; what sounds: [[id hz until-beat] …] → ids (sent first) and Hz\n sound-outs (fn [st] [[1 (mapv first (:sounding st))] [0 (mapv second (:sounding st))]])\n ;; plays one event that starts on beat `onset` at time `at`: its notes join what sounds; the event\n ;; goes out whole (with its :beat, :hz and :ids); a clock or a step lets its notes go after their\n ;; sustain, a position when it passes their end\n play (fn [st e onset at]\n (if (api/rest-event? e)\n [st [] []]\n (let [hz (or (api/event-hz e) [])\n n0 (:n st)\n ids (mapv (fn [i] (keyword (str \"p\" (+ n0 i 1)))) (range (count hz)))\n sus (api/event-sustain e)\n st (-> st (assoc :n (+ n0 (count hz)))\n (update :sounding into (map vector ids hz (repeat (+ onset sus)))))\n ev (cond-> (assoc e :beat onset) (seq hz) (assoc :hz hz :ids ids))]\n [st (into [[2 ev]] (gain-out e hz))\n (if (and (seq ids) (not= :pos (:mode st))) [[(+ at (* sus (spb st))) 0 [:off ids]]] [])])))\n ;; plays every event that starts on or before beat b (and after the last one played)\n play-until (fn [st b at]\n (loop [st st outs [] later [] k 0]\n (let [nx (take-next st)]\n (if (and nx (<= (second nx) (+ b eps)) (< k burst))\n (let [[e onset st2] nx [st3 o l] (play st2 e onset at)]\n (recur st3 (into outs o) (into later l) (inc k)))\n [st outs later]))))\n ;; everything that sounds goes silent\n silence (fn [st] [(assoc st :sounding []) (if (seq (:sounding st)) [[1 []] [0 []]] [])])\n ;; what goes out after some events were played: them, then what sounds if it changed, then the beat\n result (fn [before st outs later b]\n {:state st :later later :show b\n :out (vec (concat outs (when (not= (:sounding before) (:sounding st)) (sound-outs st)) (when b [[3 b]])))})\n ;; its own clock: the tick of the events that start on beat (:tick st)\n tick (fn [st at]\n (let [[st2 outs later] (play-until st (:tick st) at)\n more? (some? (first (evs st2)))\n nb (:beat st2)]\n (result st (if more? (assoc st2 :tick nb) (assoc st2 :mode nil :tick nil)) outs\n (if more? (conj later [(+ (:t0 st2) (* nb (spb st2))) 0 [:tick (:gen st2)]]) later)\n (:tick st))))\n start (fn [st at args]\n (let [[st0 off] (silence st)\n q (:quant args)\n b (/ at (spb st0)) ; the beat of the AudioContext clock now\n sb (if (and (number? q) (pos? q)) (* q (js/Math.ceil (- (/ b q) eps))) b)\n t0 (* sb (spb st0))\n g (inc (:gen st0))\n st1 (-> st0 fresh (assoc :mode :clock :gen g :t0 t0 :tick 0 :waiting false))]\n {:state st1 :out off :later [[t0 0 [:tick g]]]}))\n ;; ── a position in beats: every event is a span, [onset, onset + sustain), and sounds while the\n ;; position is inside it, whichever way the position moves: forwards it is entered at its onset,\n ;; backwards at its end (and then goes out with :dir :back). Spans passed over in one step sound and\n ;; end within it; an event of no length sounds when it is crossed, either way.\n ;; The events made so far are kept in a window (the same ones every time: the seed), so moving back\n ;; does not make the stream again; it holds `cap` events, and only going back further than it does.\n cap 4096\n new-win (fn [p] {:evs [] :i 0 :from 0 :next 0 :maxlen 0 :rest (api/pattern-events p)})\n win (fn [st] (when-let [f (:win st)] (f)))\n with-win (fn [st w] (assoc st :win (constantly w)))\n ;; makes the events that start up to beat b\n extend (fn [w b]\n (loop [w w k 0]\n (let [s (:rest w) e (first s)]\n (if (and e (<= (:next w) (+ b eps)) (< k 100000))\n (let [on (:next w) idx (:i w)\n w (assoc w :rest (rest s) :next (+ on (api/event-dur e)) :i (inc idx))]\n (recur (if (api/rest-event? e)\n w\n (let [end (+ on (max 0 (api/event-sustain e)))\n v (conj (:evs w) {:i idx :e e :on on :end end})\n v2 (if (> (count v) cap) (subvec v (quot cap 2)) v)]\n (assoc w :evs v2 :from (if (identical? v v2) (:from w) (:on (first v2)))\n :maxlen (max (:maxlen w) (- end on)))))\n (inc k)))\n w))))\n ;; the window with every event that may be between lo and hi (made again from the beginning if it no\n ;; longer reaches back to lo)\n cover (fn [st lo hi]\n (let [w (or (win st) (new-win (:pattern st)))\n w (if (and (pos? (:from w)) (< (- lo (:maxlen w)) (:from w))) (new-win (:pattern st)) w)]\n (with-win st (extend w hi))))\n ;; a note that starts: its id and Hz join what sounds (with the span's end and index), the event goes out\n enter (fn [st x dir]\n (let [hz (or (api/event-hz (:e x)) [])\n n0 (:n st)\n ids (mapv (fn [i] (keyword (str \"p\" (+ n0 i 1)))) (range (count hz)))\n ev (cond-> (assoc (:e x) :beat (:on x))\n (seq hz) (assoc :hz hz :ids ids)\n (= dir :back) (assoc :dir :back))]\n [(-> st (assoc :n (+ n0 (count hz)))\n (update :sounding into (map (fn [id h] [id h (:end x) (:i x)]) ids hz)))\n ev (gain-out (:e x) hz)]))\n leave (fn [st idx] (update st :sounding (fn [s] (vec (remove (fn [[_ _ _ i]] (= i idx)) s)))))\n ;; what goes out at each moment of a step: [[t [[outlet value] …]] …], what sounds after each moment\n frames (fn [st0 moments]\n (loop [st st0 ms (sort-by first moments) acc []]\n (if-let [[t kind x dir] (first ms)]\n (let [[st2 o] (case kind\n :enter (let [[s ev g] (enter st x dir)] [s (into [[2 ev]] g)])\n :leave [(leave st (:i x)) []])\n acc (if (and (seq acc) (= t (first (peek acc))))\n (update-in acc [(dec (count acc)) 1] into o)\n (conj acc [t (vec o)]))\n ;; what sounds, after this moment\n acc (update-in acc [(dec (count acc)) 2] (constantly (:sounding st2)))]\n (recur st2 (rest ms) acc))\n [st acc])))\n ;; frames as outputs now and messages to itself later (:spread)\n deliver (fn [st0 st acc at p]\n (let [outs-of (fn [[_ o sounding] before]\n (concat o (when (not= sounding before) [[1 (mapv first sounding)] [0 (mapv second sounding)]])))\n ;; each frame against what sounded before it\n befores (reductions (fn [b [_ _ s]] s) (:sounding st0) acc)\n now (filter (fn [[t]] (<= t (+ at eps))) (map vector (map first acc) acc befores))\n later (remove (fn [[t]] (<= t (+ at eps))) (map vector (map first acc) acc befores))]\n {:state st :show p\n :out (vec (concat (mapcat (fn [[_ f b]] (outs-of f b)) now) [[3 p]]))\n :later (vec (for [[t f b] later] [t 0 [:frame (:pgen st) (vec (outs-of f b))]]))}))\n ;; moves to p: motion (what it passes sounds) or a seek (it is there at once)\n position (fn [st p at args seek?]\n (let [st (if (= :clock (:mode st)) (update st :gen inc) st)\n prev (when (= :pos (:mode st)) (:pos st))\n step (when prev (- p prev))\n last-step (:last-step st)\n ;; a jump: asked for, the first position, a step longer than limit, or a step more\n ;; than jump times the one before it (only from a sixteenth of a beat on: smaller\n ;; steps are motion whatever their ratio, so a curve leaving rest is not misread)\n jump? (or seek? (nil? prev)\n (> (js/Math.abs step) (or (:limit args) 8))\n (and last-step (> (js/Math.abs last-step) eps) (>= (js/Math.abs step) 0.0625)\n (> (js/Math.abs step) (* (or (:jump args) 8) (js/Math.abs last-step)))))]\n (cond\n ;; the same place again: nothing changes\n (and (not jump?) (< (js/Math.abs step) eps)) {:state st}\n jump?\n ;; there at once, as a difference: what still contains p goes on sounding (it is not\n ;; cut nor started again), what no longer does ends, and what newly contains p starts\n ;; (with :edges, only what starts exactly at p); an event of no length at p sounds\n (let [st (-> st (assoc :mode :pos :pos p :pos-at at :last-step nil :pgen (inc (or (:pgen st) 0)))\n (cover p p))\n xs (:evs (win st))\n inside? (fn [x] (and (<= (:on x) (+ p eps)) (< p (- (:end x) eps))))\n kept (set (keep (fn [[_ _ _ i]] (when (and (some? i) (some (fn [x] (and (= (:i x) i) (inside? x))) xs)) i))\n (:sounding st)))\n st (update st :sounding (fn [s] (vec (filter (fn [[_ _ _ i]] (contains? kept i)) s))))\n here (filter (fn [x] (and (not (contains? kept (:i x)))\n (if (<= (- (:end x) (:on x)) eps)\n (< (js/Math.abs (- (:on x) p)) eps)\n (if (:edges args) (< (js/Math.abs (- (:on x) p)) eps) (inside? x)))))\n xs)\n moments (mapcat (fn [x] (if (<= (- (:end x) (:on x)) eps)\n [[at :enter x :fwd] [at :leave x]]\n [[at :enter x :fwd]]))\n (sort-by :on here))\n [st2 acc] (frames st moments)\n r (deliver st st2 acc at p)]\n ;; what sounds, always (it may differ from what was last sent, a spread step cut short)\n (update r :out (fn [o] (vec (concat (filter (fn [[k]] (= k 2)) o)\n [[1 (mapv first (:sounding st2))] [0 (mapv second (:sounding st2))]]\n (filter (fn [[k]] (= k 3)) o))))))\n :else\n (let [fwd? (pos? step)\n lo (min prev p) hi (max prev p)\n dt (- at (or (:pos-at st) at))\n ;; when a boundary b is reached within the step: now, or (spread) as far into\n ;; the next step as it lies into this one\n t-of (fn [b] (if (and (:spread args) (pos? dt) (< dt 0.5))\n (+ at (* dt (/ (- b prev) step)))\n at))\n st (cover st lo hi)\n xs (:evs (win st))\n moments\n (if fwd?\n (concat\n ;; starts it passes: entered, and ended too if it also passes their end\n (mapcat (fn [x] (if (> (:end x) (+ p eps))\n [[(t-of (:on x)) :enter x :fwd (:on x)]]\n [[(t-of (:on x)) :enter x :fwd (:on x)] [(t-of (:end x)) :leave x nil (:end x)]]))\n (filter (fn [x] (and (> (:on x) (+ prev eps)) (<= (:on x) (+ p eps)))) xs))\n ;; what sounded and ends within the step\n (for [[_ _ end i] (:sounding st) :when (and (some? i) (> end (+ prev eps)) (<= end (+ p eps)))]\n [(t-of end) :leave {:i i} nil end]))\n (concat\n ;; ends it passes going back: entered from its end, and left at its onset if it\n ;; passes that too; an event of no length when its onset is passed\n (mapcat (fn [x] (let [zero? (<= (- (:end x) (:on x)) eps)]\n (if (and (not zero?) (<= (:on x) (+ p eps)))\n [[(t-of (:end x)) :enter x :back (:end x)]]\n [[(t-of (:end x)) :enter x :back (:end x)] [(t-of (:on x)) :leave x nil (:on x)]])))\n (filter (fn [x] (let [zero? (<= (- (:end x) (:on x)) eps)]\n (if zero?\n (and (>= (:on x) (- p eps)) (< (:on x) (- prev eps)))\n (and (> (:end x) (+ p eps)) (<= (:end x) (+ prev eps))))))\n xs))\n ;; what sounded and whose onset it passes going back\n (for [[_ _ _ i] (:sounding st)\n :let [x (first (filter (fn [x] (= (:i x) i)) xs))]\n :when (and x (> (:on x) (+ p eps)) (<= (:on x) (+ prev eps)))]\n [(t-of (:on x)) :leave {:i i} nil (:on x)])))\n ;; in the order it meets them: by time, then by where they are in the direction it\n ;; moves (and an event that starts and ends at one place, first in, then out)\n [st2 acc] (frames st (sort-by (fn [[t kind _ _ b]] [t (if fwd? b (- b)) (if (= kind :enter) 0 1)]) moments))]\n (deliver st (assoc st2 :pos p :last-step step :pos-at at) acc at p)))))\n ;; one step: the next event now (with those of :dur 0 right after it, a chord), going on from where\n ;; its steps or its clock were; at the end, again from the beginning\n step (fn [st at]\n (let [st (cond-> st (= :clock (:mode st)) (update :gen inc))\n st (if (and (:evs st) (#{:step :clock} (:mode st)) (first (evs st))) st (fresh st))\n st (assoc st :mode :step)]\n (if-let [[_ onset _] (take-next st)]\n (let [[st2 outs later] (play-until st onset at)] (result st st2 outs later onset))\n {:state st :out [[3 0]]})))]\n {;; ── about ──\n :class \"player\"\n :license \"MPL-2.0\"\n :doc \"Plays a pattern (from a pbind or a pattern box, on its right inlet) in one of three ways, chosen by what arrives on the left: start / stop — its own clock, every event lasting its :dur in beats at its bpm (quant: start on a multiple of that many beats); bang — one step, the next event now; a number — a position in beats (a ramp, a counter, a number you drag), where every event is a span from its onset to its end that sounds while the position is inside it: forwards it is entered at its onset, backwards at its end (:dir :back), and the spans passed over in one step sound within it; seek p, or a step more than jump (8) times the one before it or longer than limit (8) beats, goes there at once, sounding what contains p (with edges, only what starts at p); with spread, what a step passes keeps its rhythm, one step later. Out: the Hz of the notes sounding, their voice ids (for synth~ or a polyphonic faust~), the whole event (:beat :hz :ids added) and the beat; an event with :amp (0…1) sends [:gain amp] on the Hz outlet just before its notes, the loudness of the notes that start (synth~, a polyphonic faust~). A new pattern while it plays goes on from the same beat; the same pattern again changes nothing. Pitch: :freq, :note (MIDI, \\\"c4\\\", :c4), or :degree with :scale :root :octave; :dur, :legato or :sustain; :rest (or nil) is a silence.\"\n :usage \"player [bpm] [quant] [jump] [limit] [edges] [spread]\"\n :io [2 4]\n\n ;; ── arguments ──\n :args [[:bpm 120] [:quant 0] [:jump 8] [:limit 8] [:edges false] [:spread false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args at]}]\n (let [st (or state {:gen 0 :n 0 :sounding [] :bpm (max 1 (or (:bpm args) 120)) :mode nil})\n w (word value)]\n (try\n (cond\n ;; the pattern, on the right\n (= inlet 1)\n (cond\n (not (api/pattern? value)) {:state st :effects [[:print \"player: its right inlet takes a pattern (from a pbind or a pattern box)\"]]}\n (= (:key value) (:key (:pattern st))) {:state st} ; the same again: nothing changes\n :else\n (let [st (-> st (assoc :pattern value) (dissoc :win))]\n (case (:mode st)\n ;; its own clock: the new events from the beat it is on, without stopping\n :clock (if (:waiting st)\n (start st at args)\n (let [now-beat (/ (- at (:t0 st)) (spb st))\n st (-> st fresh (skip-to now-beat) (update :gen inc))\n nb (:beat st)]\n (if (first (evs st))\n {:state (assoc st :tick nb) :later [[(+ (:t0 st) (* nb (spb st))) 0 [:tick (:gen st)]]]}\n {:state (assoc st :mode nil)})))\n ;; a position: what sounded stops; the new events sound as the position moves on\n :pos (let [[st2 off] (silence st)]\n {:state (-> st2 (dissoc :win) (assoc :last-step nil :pgen (inc (or (:pgen st2) 0)))) :out off})\n ;; steps: the new events from the same beat\n :step {:state (-> st fresh (skip-to (or (:beat st) 0)))}\n {:state (dissoc st :evs)})))\n\n ;; its clock\n (and (vector? value) (= :tick (first value)))\n (if (and (= :clock (:mode st)) (= (second value) (:gen st))) (tick st at) {:state st})\n ;; what a step at a position sends a little later (spread)\n (and (vector? value) (= :frame (first value)))\n (if (and (= :pos (:mode st)) (= (second value) (:pgen st))) {:state st :out (nth value 2)} {:state st})\n ;; notes that end (a clock or steps)\n (and (vector? value) (= :off (first value)))\n (let [ids (set (second value)) st2 (update st :sounding (fn [s] (vec (remove (fn [[id]] (ids id)) s))))]\n (if (= st2 st) {:state st} {:state st2 :out (sound-outs st2)}))\n (and (vector? value) (= :bpm (first value)) (number? (second value)) (pos? (second value)))\n (let [nbpm (second value)]\n (if (= :clock (:mode st))\n ;; the same beat now, at the new tempo: the next tick is moved, nothing jumps\n (let [now-beat (/ (- at (:t0 st)) (spb st))\n st2 (assoc st :bpm nbpm :gen (inc (:gen st)))\n st2 (assoc st2 :t0 (- at (* now-beat (spb st2))))]\n {:state st2 :later [[(+ (:t0 st2) (* (:tick st2) (spb st2))) 0 [:tick (:gen st2)]]]})\n {:state (assoc st :bpm nbpm)}))\n\n (= w :start)\n (if (:pattern st) (start st at args) {:state (assoc st :mode :clock :waiting true)\n :effects [[:print \"player: waiting for a pattern on its right inlet\"]]})\n (= w :stop)\n (let [[st2 off] (silence st)] {:state (assoc st2 :mode nil :gen (inc (:gen st2)) :pgen (inc (or (:pgen st2) 0)) :waiting false) :out off})\n (= w :reset)\n (let [[st2 off] (silence st)] {:state (-> st2 fresh (dissoc :win) (assoc :mode nil :pos nil :gen (inc (:gen st2)) :pgen (inc (or (:pgen st2) 0)))) :out off})\n (= w :bang) (if (:pattern st) (step st at) {:state st :effects [[:print \"player: no pattern yet (on its right inlet)\"]]})\n (number? value) (if (:pattern st) (position st value at args false) {:state st})\n ;; seek p: there at once, without sounding what is in between\n (and (vector? value) (= :seek (first value)) (number? (second value)))\n (if (:pattern st) (position st (second value) at args true) {:state st})\n :else {:state st})\n (catch :default e\n {:state (assoc st :mode nil :gen (inc (:gen st)))\n :effects [[:print (str \"player: the pattern failed while playing: \" (or (.-message e) e))]]}))))})\n"
26
+ },
27
+ {
28
+ "class": "render",
29
+ "license": "MPL-2.0",
30
+ "doc": "Draws a stretch of a pattern (from a pbind or a pattern box) into a freqt: it sends a musical tree, shown live by the freqt (keep! writes it with its recipe; as a score it is quantized). Without a canvas on its right inlet it renders the beats from–to as they are; with one, each stroke of the canvas is a time map (x: beats of the result, y: beats of the pattern) — steeper is faster, going down plays backwards with each note entered from its end, flat holds the note it is in, a vertical step cuts, several strokes are several layers. Each note is drawn with the event's :amp as its weight and :pan as a vertical gradient; tex k and tone k draw key k as a texture or a colour. A bang renders again (after changing the canvas).",
31
+ "source": ";; render · a stretch of a pattern drawn into a freqt, through a time map\n;; Part of @kairotic/patterns. Written against the Kairotic API (api/…).\n;; What a player at a position would play, worked out at once (discussion #93): it sends a musical tree, so\n;; a freqt shows it live, (keep! :bN) writes it with its recipe, and shown as a score it is quantized.\n;; Without a canvas on its right inlet it renders [from, to) as it is; with one, each stroke of the canvas\n;; is a time map — x the beats of the result, y the beats of the pattern — and the notes are where the map\n;; is inside their spans: steeper is faster, down is backwards (each note from its end), flat holds, a\n;; vertical step cuts, several strokes are several layers.\n(let [opts-of (fn [args buffer]\n (cond-> {:from (or (:from args) 0) :to (or (:to args) 16)\n :tex (:tex args) :tone (:tone args)}\n (and buffer (seq (:strokes buffer))) (assoc :maps (api/canvas-maps buffer))))\n word (fn [v] (cond (keyword? v) v (string? v) (keyword v) :else nil))]\n {;; ── about ──\n :class \"render\"\n :license \"MPL-2.0\"\n :doc \"Draws a stretch of a pattern (from a pbind or a pattern box) into a freqt: it sends a musical tree, shown live by the freqt (keep! writes it with its recipe; as a score it is quantized). Without a canvas on its right inlet it renders the beats from–to as they are; with one, each stroke of the canvas is a time map (x: beats of the result, y: beats of the pattern) — steeper is faster, going down plays backwards with each note entered from its end, flat holds the note it is in, a vertical step cuts, several strokes are several layers. Each note is drawn with the event's :amp as its weight and :pan as a vertical gradient; tex k and tone k draw key k as a texture or a colour. A bang renders again (after changing the canvas).\"\n :usage \"render [from] [to] [tex key] [tone key]\"\n :io [2 1]\n :reads-buffer true\n\n ;; ── arguments ──\n :parse (fn [text]\n (let [ws (rest (remove #(= \"\" %) (.split (.trim (str text)) #\"\\s+\")))\n nums (keep (fn [w] (let [n (js/parseFloat w)] (when (js/isFinite n) n))) ws)\n after (fn [k] (some (fn [[a b]] (when (= a k) (keyword (.replace b #\"^:\" \"\")))) (partition 2 1 ws)))]\n {:from (first nums) :to (second nums) :tex (after \"tex\") :tone (after \"tone\")}))\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args buffer]}]\n (let [st (or state {})\n go (fn [p]\n (let [t (api/render-tree p (opts-of args buffer))\n st (assoc st :pattern p :last t)]\n (if (= t (:last state)) {:state st} {:state st :out [[0 t]] :show (str (dec (count t)) \" notes\")})))]\n (cond\n (= inlet 1) {:state st}\n (api/pattern? value) (go value)\n (= (word value) :bang) (if-let [p (:pattern st)] (go p) {})\n :else {})))\n\n :help {:inlets [\"a pattern (from a pbind or a pattern box) · bang: renders again\" \"a canvas: its strokes are time maps (x: result, y: pattern)\"]\n :outlets [\"a musical tree, for a freqt (shown live; keep! writes it with its recipe)\"]\n :messages [[\"render 0 8\" \"the beats 0 to 8 of the pattern, as they are\"]\n [\"a canvas on the right\" \"each stroke is a time map: steeper is faster, down is backwards, flat holds, a vertical step cuts, several strokes are layers\"]\n [\"render 0 16 tex art tone inst\" \"the values of :art drawn as textures, those of :inst as colours\"]\n [\":amp · :pan\" \"the weight of a note · a vertical gradient across it\"]]\n :example \"(box :b1 \\\"pbind 3 loop\\\" 40 30)\\n(code :b1 \\\"{:degree [0 2 4 7 4 2 :rest 9]\\\\n :dur 0.5\\\\n :amp #pat/white [0.1 1]\\\\n :pan [-1 1]}\\\")\\n(box :b2 \\\"render 0 8\\\" 40 130)\\n(box :b3 \\\"freqt\\\" 40 180)\\n(connect :b1 0 :b2 0)\\n(connect :b2 0 :b3 0)\"\n :try \"The pattern appears in the freqt, each note as thick as its :amp and shaded by its :pan. Change the pbind: the drawing follows. (keep! :b3) writes it into the freqt with its recipe.\"\n :steps [{:title \"A time map\"\n :note \"A canvas on the right inlet: each stroke says which beat of the pattern (y) is at each beat of the drawing (x). Down plays backwards, each note from its end; flat holds; two strokes make a canon.\"\n :example \"(box :b4 \\\"canvas\\\" 300 130)\\n(axis :b4 :x 0 16)\\n(axis :b4 :y 0 8)\\n(stroke :b4 [[0 0] [8 8] [12 4] [16 4]])\\n(stroke :b4 [[2 0] [16 7]])\\n(connect :b4 1 :b2 1)\\n(box :b5 \\\"msg :bang\\\" 120 90)\\n(connect :b5 0 :b2 0)\"\n :try \"Click bang: forwards, backwards, held, and a slower second layer under it. Redraw the canvas and click bang again.\"}]\n :see [\"player\" \"pbind\" \"freqt\" \"canvas\" \"reader\"]}})\n"
32
+ }
33
+ ]
34
+ };
@@ -0,0 +1,22 @@
1
+ // Generated by packages/build.mjs
2
+ export default {
3
+ "package": "@kairotic/spatial",
4
+ "version": "0.1.1",
5
+ "api": 1,
6
+ "author": "bonuoq",
7
+ "license": "MPL-2.0",
8
+ "components": [
9
+ {
10
+ "class": "pan~",
11
+ "license": "MPL-2.0",
12
+ "doc": "Stereo panning with equal power: signal on the left inlet, position on the right (−1 left … 1 right). Two outlets: left and right.",
13
+ "source": ";; pan~ · stereo panning with equal power\n;; Part of @kairotic/spatial. Written against the Kairotic API (api/…).\n{;; ── about ──\n :class \"pan~\"\n :license \"MPL-2.0\"\n :doc \"Stereo panning with equal power: signal on the left inlet, position on the right (−1 left … 1 right). Two outlets: left and right.\"\n :usage \"pan~ [position]\"\n :io [2 2]\n\n ;; ── arguments ──\n :args [[:position 0]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (if (and (= 1 inlet) (api/num-of value))\n {:effects [[:pan (api/clamp (api/num-of value) -1 1)]] :show (api/num-of value)}\n {}))\n\n ;; ── audio ──\n :audio {:create (fn [ac b _]\n (let [p (.createStereoPanner ac)]\n (set! (.. p -pan -value) (api/clamp (first (api/padded (:args b) [0])) -1 1))\n {:p p :inlets [[p 0]] :outlets (api/stereo-outlets ac p)}))\n :effects {:pan (fn [node x at] (.setTargetAtTime (.-pan (:p node)) x at 0.01))}\n ;; a new text: the new position, without rebuilding the node\n :update (fn [node b at] (.setTargetAtTime (.-pan (:p node)) (api/clamp (first (api/padded (:args b) [0])) -1 1) at 0.01))}}\n"
14
+ },
15
+ {
16
+ "class": "space~",
17
+ "license": "MPL-2.0",
18
+ "doc": "A sound placed around the listener (binaural, HRTF): drag the dot, or send [x y] (−1…1; y = 1 is in front). Two outlets: left and right, for headphones. Dragging rewrites the box.",
19
+ "source": ";; space~ · a sound placed around the listener (binaural)\n;; Part of @kairotic/spatial. Written against the Kairotic API (api/…).\n(let [pos-of (fn [v] (when (and (sequential? v) (= 2 (count v)) (every? number? v))\n [(api/clamp (first v) -1 1) (api/clamp (second v) -1 1)]))\n ;; An HRTF panner clicks whenever its position changes (it swaps filters), so space~ keeps two:\n ;; the silent one jumps to the new place and they crossfade, at most every `step` seconds; it\n ;; gets its place `settle` seconds before it is heard. A move that comes sooner waits for the\n ;; next crossfade (and the latest one wins). Measured offline: a path every 10 ms clicked 57\n ;; times in 8 s with one panner, none in 20 s like this.\n step 0.05 settle 0.01\n move! (fn [node [x y] at]\n (let [{:keys [a s]} @(:live node) pair (:pair node)\n place! (fn [i t] (let [p (:p (pair i))]\n (doseq [prm [(.-positionX p) (.-positionZ p)]] (.cancelScheduledValues prm t))\n (.setValueAtTime (.-positionX p) (* 2 x) t)\n (.setValueAtTime (.-positionZ p) (* -2 y) t)))]\n (if (< at s)\n (place! a s) ; a crossfade is already waiting: move its target\n (let [t (max at (+ s step)) b (- 1 a)]\n (place! b t)\n (doseq [[i v] [[b 1] [a 0]] :let [g (.-gain (:g (pair i)))]]\n (.cancelScheduledValues g t)\n (.setTargetAtTime g v (+ t settle) (/ step 4)))\n (reset! (:live node) {:a b :s t})))))]\n {;; ── about ──\n :class \"space~\"\n :license \"MPL-2.0\"\n :doc \"A sound placed around the listener (binaural, HRTF): drag the dot, or send [x y] (−1…1; y = 1 is in front). Two outlets: left and right, for headphones. Dragging rewrites the box.\"\n :usage \"space~ [x y]\"\n :io [1 2]\n :size [104 104]\n\n ;; ── arguments ──\n :args [[:x 0] [:y 1]]\n :persist (fn [[x y]] {:x x :y y})\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (if-let [p (pos-of value)]\n {:state p :show p :effects [[:pos p]]}\n (let [p (or state (pos-of [(:x args) (:y args)]) [0 1])]\n (if (= value :bang) {:state p :show p :effects [[:pos p]]} {:state p}))))\n :gesture (fn [{:keys [x y]}]\n [(/ (js/Math.round (* 100 (api/clamp (/ (- x 52) 46) -1 1))) 100)\n (/ (js/Math.round (* 100 (api/clamp (/ (- 52 y) 46) -1 1))) 100)])\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}]\n (let [[x y] (or (pos-of shown) (pos-of [(:x args) (:y args)]) [0 1])]\n {:px (+ 52 (* 46 x)) :py (- 52 (* 46 y))\n :label (str (api/nice x) \" · \" (api/nice y))}))\n :view [[:rect {:x 2 :y 2 :w 100 :h 100 :r 4 :stroke :grid :fill :bg}]\n [:line {:x1 52 :y1 6 :x2 52 :y2 98 :stroke :grid}]\n [:line {:x1 6 :y1 52 :x2 98 :y2 52 :stroke :grid}]\n [:circle {:cx 52 :cy 52 :r 30 :stroke :grid}]\n [:path {:points [[47 50] [52 43] [57 50]] :closed true :fill :soft}]\n [:circle {:cx 52 :cy 52 :r 5 :stroke :soft :fill :bg}]\n [:line {:x1 52 :y1 52 :x2 :$px :y2 :$py :stroke :accent :weight 1}]\n [:circle {:cx :$px :cy :$py :r 6 :fill :accent}]\n [:text {:x 6 :y 98 :size 9 :fill :soft} :$label]]\n\n ;; ── audio ──\n :audio {:create (fn [ac b _]\n (let [[x y] (api/padded (:args b) [0 1])\n in (.createGain ac) out (.createGain ac)\n pair (vec (for [i [0 1]]\n (let [p (.createPanner ac) g (.createGain ac)]\n (set! (.-panningModel p) \"HRTF\")\n (set! (.-distanceModel p) \"inverse\")\n (set! (.-refDistance p) 1)\n (set! (.. p -positionX -value) (* 2 (api/clamp x -1 1)))\n (set! (.. p -positionY -value) 0)\n (set! (.. p -positionZ -value) (* -2 (api/clamp y -1 1)))\n (set! (.. g -gain -value) (if (zero? i) 1 0))\n (.connect in p) (.connect p g) (.connect g out)\n {:p p :g g})))]\n {:pair pair :live (atom {:a 0 :s -1}) :inlets [[in 0]] :outlets (api/stereo-outlets ac out)}))\n :effects {:pos (fn [node xy at] (move! node xy at))}\n ;; a new text (dragging the dot rewrites it): the sound goes to the new place\n :update (fn [node b at] (move! node (pos-of (api/padded (:args b) [0 1])) at))}})\n"
20
+ }
21
+ ]
22
+ };