SCPattern moved out of GLucose
[SugarCubes.git] / _Internals.pde
CommitLineData
49815cc0 1/**
1ecdb44a
MS
2 * DOUBLE BLACK DIAMOND DOUBLE BLACK DIAMOND
3 *
4 * //\\ //\\ //\\ //\\
5 * ///\\\ ///\\\ ///\\\ ///\\\
6 * \\\/// \\\/// \\\/// \\\///
d12e46b6 7 * \\// \\// \\// \\//H
1ecdb44a
MS
8 *
9 * EXPERTS ONLY!! EXPERTS ONLY!!
10 *
49815cc0
MS
11 * If you are an artist, you may ignore this file! It just sets
12 * up the framework to run the patterns. Should not need modification
13 * for general animation work.
14 */
15
16import glucose.*;
49815cc0
MS
17import heronarts.lx.*;
18import heronarts.lx.effect.*;
b9b7b3d4 19import heronarts.lx.model.*;
49815cc0 20import heronarts.lx.modulator.*;
b8bb2748 21import heronarts.lx.parameter.*;
f3f5a876 22import heronarts.lx.pattern.*;
9fa29818 23import heronarts.lx.transform.*;
49815cc0 24import heronarts.lx.transition.*;
4e6626a9
MS
25import heronarts.lx.ui.*;
26import heronarts.lx.ui.component.*;
27import heronarts.lx.ui.control.*;
49815cc0
MS
28import ddf.minim.*;
29import ddf.minim.analysis.*;
30import processing.opengl.*;
5d70e4d7 31import rwmidi.*;
24fc0330 32import java.lang.reflect.*;
b9b7b3d4
MS
33import java.util.ArrayList;
34import java.util.Collections;
35import java.util.List;
49815cc0
MS
36
37final int VIEWPORT_WIDTH = 900;
38final int VIEWPORT_HEIGHT = 700;
0e3c5542 39
92c06c97 40// The trailer is measured from the outside of the black metal (but not including the higher welded part on the front)
e18b4cb7
MS
41final float TRAILER_WIDTH = 192;
42final float TRAILER_DEPTH = 192;
87998ff3
MS
43final float TRAILER_HEIGHT = 33;
44
51d0d59a 45int targetFramerate = 60;
49815cc0 46int startMillis, lastMillis;
a898d79b
MS
47
48// Core engine variables
49815cc0 49GLucose glucose;
d12e46b6 50LX lx;
34490867 51Model model;
49815cc0 52LXPattern[] patterns;
24fc0330 53Effects effects;
a898d79b 54MappingTool mappingTool;
e037f60f 55GrizzlyOutput[] grizzlies;
e0794d3a 56PresetManager presetManager;
1f974cbc 57MidiEngine midiEngine;
a898d79b
MS
58
59// Display configuration mode
bf551144 60boolean mappingMode = false;
cc9fcf4b 61boolean debugMode = false;
7974acd6 62boolean simulationOn = true;
73678c57 63boolean diagnosticsOn = false;
34327c96 64LXPattern restoreToPattern = null;
4c640acc 65PImage logo;
a41f334c 66float[] hsb = new float[3];
d626bc9b 67
a898d79b 68// Handles to UI objects
d626bc9b 69UIPatternDeck uiPatternA;
a898d79b 70UICrossfader uiCrossfader;
a8d55ade 71UIMidi uiMidi;
d626bc9b
MS
72UIMapping uiMapping;
73UIDebugText uiDebugText;
fa4f822d 74UISpeed uiSpeed;
cc9fcf4b 75
34327c96
MS
76/**
77 * Engine construction and initialization.
78 */
d1dcc4b5 79
dde75983
MS
80LXTransition _transition(LX lx) {
81 return new DissolveTransition(lx).setDuration(1000);
d1dcc4b5
MS
82}
83
dde75983
MS
84LXPattern[] _leftPatterns(LX lx) {
85 LXPattern[] patterns = patterns(lx);
d626bc9b 86 for (LXPattern p : patterns) {
dde75983 87 p.setTransition(_transition(lx));
d626bc9b
MS
88 }
89 return patterns;
90}
91
dde75983
MS
92LXPattern[] _rightPatterns(LX lx) {
93 LXPattern[] patterns = _leftPatterns(lx);
d1dcc4b5
MS
94 LXPattern[] rightPatterns = new LXPattern[patterns.length+1];
95 int i = 0;
dde75983 96 rightPatterns[i++] = new BlankPattern(lx).setTransition(_transition(lx));
d1dcc4b5
MS
97 for (LXPattern p : patterns) {
98 rightPatterns[i++] = p;
99 }
100 return rightPatterns;
101}
24fc0330
MS
102
103LXEffect[] _effectsArray(Effects effects) {
104 List<LXEffect> effectList = new ArrayList<LXEffect>();
105 for (Field f : effects.getClass().getDeclaredFields()) {
106 try {
107 Object val = f.get(effects);
108 if (val instanceof LXEffect) {
109 effectList.add((LXEffect)val);
110 }
111 } catch (IllegalAccessException iax) {}
112 }
113 return effectList.toArray(new LXEffect[]{});
114}
d1dcc4b5 115
34327c96
MS
116void logTime(String evt) {
117 int now = millis();
118 println(evt + ": " + (now - lastMillis) + "ms");
119 lastMillis = now;
120}
121
49815cc0
MS
122void setup() {
123 startMillis = lastMillis = millis();
124
125 // Initialize the Processing graphics environment
126 size(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, OPENGL);
0e3c5542 127 frameRate(targetFramerate);
3f8be614 128 noSmooth();
49815cc0
MS
129 // hint(ENABLE_OPENGL_4X_SMOOTH); // no discernable improvement?
130 logTime("Created viewport");
131
132 // Create the GLucose engine to run the cubes
34490867 133 glucose = new GLucose(this, model = buildModel());
49815cc0 134 lx = glucose.lx;
cc9fcf4b 135 lx.enableKeyboardTempo();
49815cc0 136 logTime("Built GLucose engine");
2bb56822 137
49815cc0 138 // Set the patterns
42a424d7 139 LXEngine engine = lx.engine;
dde75983
MS
140 engine.setPatterns(patterns = _leftPatterns(lx));
141 engine.addDeck(_rightPatterns(lx));
49815cc0 142 logTime("Built patterns");
dde75983 143 glucose.setTransitions(transitions(lx));
a898d79b 144 logTime("Built transitions");
24fc0330 145 glucose.lx.addEffects(_effectsArray(effects = new Effects()));
49815cc0 146 logTime("Built effects");
4214e9a2 147
e0794d3a
MS
148 // Preset manager
149 presetManager = new PresetManager();
150 logTime("Loaded presets");
4214e9a2 151
1f974cbc
MS
152 // MIDI devices
153 midiEngine = new MidiEngine();
1f974cbc
MS
154 logTime("Setup MIDI devices");
155
e73ef85d 156 // Build output driver
e037f60f 157 grizzlies = new GrizzlyOutput[]{};
34490867 158 try {
e037f60f 159 grizzlies = buildGrizzlies();
34490867
MS
160 for (LXOutput output : grizzlies) {
161 lx.addOutput(output);
162 }
163 } catch (Exception x) {
164 x.printStackTrace();
165 }
e037f60f
MS
166 logTime("Built Grizzly Outputs");
167
168 // Mapping tools
dde75983 169 mappingTool = new MappingTool(lx);
34490867 170
49815cc0 171 // Build overlay UI
e037f60f
MS
172 UILayer[] layers = new UILayer[] {
173 // Camera layer
174 new UICameraLayer(lx.ui)
e18b4cb7 175 .setCenter(model.cx, model.cy, model.cz)
e037f60f
MS
176 .setRadius(290).addComponent(new UICubesLayer()),
177
178 // Left controls
4e6626a9 179 uiPatternA = new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.LEFT_DECK), "PATTERN A", 4, 4, 140, 324),
a8d55ade
MS
180 new UIBlendMode(4, 332, 140, 86),
181 new UIEffects(4, 422, 140, 144),
182 new UITempo(4, 570, 140, 50),
fa4f822d 183 uiSpeed = new UISpeed(4, 624, 140, 50),
a8d55ade 184
e037f60f 185 // Right controls
4e6626a9 186 new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.RIGHT_DECK), "PATTERN B", width-144, 4, 140, 324),
d6ac1ee8 187 uiMidi = new UIMidi(midiEngine, width-144, 332, 140, 158),
e037f60f 188 new UIOutput(grizzlies, width-144, 494, 140, 106),
d626bc9b 189
e037f60f 190 // Crossfader
a8d55ade 191 uiCrossfader = new UICrossfader(width/2-90, height-90, 180, 86),
d626bc9b 192
e037f60f 193 // Overlays
a8d55ade 194 uiDebugText = new UIDebugText(148, height-138, width-304, 44),
4e6626a9 195 uiMapping = new UIMapping(mappingTool, 4, 4, 140, 324)
d626bc9b 196 };
e037f60f
MS
197 uiMapping.setVisible(false);
198 for (UILayer layer : layers) {
199 lx.ui.addLayer(layer);
4e6626a9 200 }
e037f60f 201 logTime("Built UI");
4c640acc
MS
202
203 // Load logo image
204 logo = loadImage("data/logo.png");
e037f60f 205 logTime("Loaded logo image");
4e6626a9 206
49815cc0 207 println("Total setup: " + (millis() - startMillis) + "ms");
e037f60f 208 println("Hit the 'o' key to toggle live output");
49815cc0
MS
209}
210
dde75983
MS
211public SCPattern getPattern() {
212 return (SCPattern) lx.getPattern();
213}
214
215/**
216 * Subclass of LXPattern specific to sugar cubes. These patterns
217 * get access to the glucose state and geometry, and have some
218 * little helpers for interacting with the model.
219 */
220public static abstract class SCPattern extends LXPattern {
221
222 protected SCPattern(LX lx) {
223 super(lx);
224 }
225
226 /**
227 * Reset this pattern to its default state.
228 */
229 public final void reset() {
230 for (LXParameter parameter : getParameters()) {
231 parameter.reset();
232 }
233 onReset();
234 }
235
236 /**
237 * Subclasses may override to add additional reset functionality.
238 */
239 protected /*abstract*/ void onReset() {}
240
241 /**
242 * Invoked by the engine when a grid controller button press occurs
243 *
244 * @param row Row index on the gird
245 * @param col Column index on the grid
246 * @return True if the event was consumed, false otherwise
247 */
248 public boolean gridPressed(int row, int col) {
249 return false;
250 }
251
252 /**
253 * Invoked by the engine when a grid controller button release occurs
254 *
255 * @param row Row index on the gird
256 * @param col Column index on the grid
257 * @return True if the event was consumed, false otherwise
258 */
259 public boolean gridReleased(int row, int col) {
260 return false;
261 }
262
263 /**
264 * Invoked by engine when this pattern is focused an a midi note is received.
265 *
266 * @param note
267 * @return True if the pattern has consumed this note, false if the top-level
268 * may handle it
269 */
270 public boolean noteOn(rwmidi.Note note) {
271 return false;
272 }
273
274 /**
275 * Invoked by engine when this pattern is focused an a midi note off is received.
276 *
277 * @param note
278 * @return True if the pattern has consumed this note, false if the top-level
279 * may handle it
280 */
281 public boolean noteOff(rwmidi.Note note) {
282 return false;
283 }
284
285 /**
286 * Invoked by engine when this pattern is focused an a controller is received
287 *
288 * @param note
289 * @return True if the pattern has consumed this controller, false if the top-level
290 * may handle it
291 */
292 public boolean controllerChange(rwmidi.Controller controller) {
293 return false;
294 }
295}
296
e18b4cb7
MS
297long simulationNanos = 0;
298
34327c96
MS
299/**
300 * Core render loop and drawing functionality.
301 */
49815cc0 302void draw() {
73678c57
MS
303 long drawStart = System.nanoTime();
304
4e6626a9 305 // Set background
0a9f99cc 306 background(40);
4e6626a9
MS
307
308 // Send colors
e037f60f 309 color[] sendColors = glucose.getColors();
73678c57 310 long gammaStart = System.nanoTime();
7974acd6
MS
311 // Gamma correction here. Apply a cubic to the brightness
312 // for better representation of dynamic range
313 for (int i = 0; i < sendColors.length; ++i) {
314 lx.RGBtoHSB(sendColors[i], hsb);
315 float b = hsb[2];
316 sendColors[i] = lx.hsb(360.*hsb[0], 100.*hsb[1], 100.*(b*b*b));
317 }
73678c57 318 long gammaNanos = System.nanoTime() - gammaStart;
4e6626a9 319
e037f60f 320 // Always draw FPS meter
4e6626a9 321 drawFPS();
4e6626a9
MS
322
323 // TODO(mcslee): fix
73678c57 324 long drawNanos = System.nanoTime() - drawStart;
e18b4cb7
MS
325 long uiNanos = 0;
326
73678c57 327 if (diagnosticsOn) {
e037f60f 328 drawDiagnostics(drawNanos, simulationNanos, uiNanos, gammaNanos);
4e6626a9
MS
329 }
330}
331
332class UICubesLayer extends UICameraComponent {
333 void onDraw(UI ui) {
334 color[] simulationColors = glucose.getColors();
335 String displayMode = uiCrossfader.getDisplayMode();
336 if (displayMode == "A") {
337 simulationColors = lx.engine.getDeck(GLucose.LEFT_DECK).getColors();
338 } else if (displayMode == "B") {
339 simulationColors = lx.engine.getDeck(GLucose.RIGHT_DECK).getColors();
340 }
4e6626a9
MS
341
342 long simulationStart = System.nanoTime();
343 if (simulationOn) {
344 drawSimulation(simulationColors);
345 }
e18b4cb7 346 simulationNanos = System.nanoTime() - simulationStart;
4e6626a9
MS
347
348 camera();
349 javax.media.opengl.GL gl = ((PGraphicsOpenGL)g).beginGL();
350 gl.glClear(javax.media.opengl.GL.GL_DEPTH_BUFFER_BIT);
351 ((PGraphicsOpenGL)g).endGL();
352 strokeWeight(1);
e18b4cb7
MS
353 }
354
355 void drawSimulation(color[] simulationColors) {
356 translate(0, 30, 0);
357
358 noStroke();
359 fill(#141414);
360 drawBox(0, -TRAILER_HEIGHT, 0, 0, 0, 0, TRAILER_WIDTH, TRAILER_HEIGHT, TRAILER_DEPTH, TRAILER_HEIGHT/2.);
361 fill(#070707);
362 stroke(#222222);
363 beginShape();
364 vertex(0, 0, 0);
365 vertex(TRAILER_WIDTH, 0, 0);
366 vertex(TRAILER_WIDTH, 0, TRAILER_DEPTH);
367 vertex(0, 0, TRAILER_DEPTH);
368 endShape();
369
370 // Draw the logo on the front of platform
371 pushMatrix();
372 translate(0, 0, -1);
373 float s = .07;
374 scale(s, -s, s);
375 image(logo, TRAILER_WIDTH/2/s-logo.width/2, TRAILER_HEIGHT/2/s-logo.height/2-2/s);
376 popMatrix();
377
378 noStroke();
b9b7b3d4 379 for (Cube c : model.cubes) {
e18b4cb7
MS
380 drawCube(c);
381 }
382
383 noFill();
384 strokeWeight(2);
385 beginShape(POINTS);
b9b7b3d4 386 for (LXPoint p : model.points) {
e18b4cb7
MS
387 stroke(simulationColors[p.index]);
388 vertex(p.x, p.y, p.z);
389 }
390 endShape();
391 }
392
393 void drawCube(Cube c) {
394 float in = .15;
395 noStroke();
396 fill(#393939);
397 drawBox(c.x+in, c.y+in, c.z+in, c.rx, c.ry, c.rz, Cube.EDGE_WIDTH-in*2, Cube.EDGE_HEIGHT-in*2, Cube.EDGE_WIDTH-in*2, Cube.CHANNEL_WIDTH-in);
398 }
399
400 void drawBox(float x, float y, float z, float rx, float ry, float rz, float xd, float yd, float zd, float sw) {
401 pushMatrix();
402 translate(x, y, z);
403 rotate(rx / 180. * PI, -1, 0, 0);
404 rotate(ry / 180. * PI, 0, -1, 0);
405 rotate(rz / 180. * PI, 0, 0, -1);
406 for (int i = 0; i < 4; ++i) {
407 float wid = (i % 2 == 0) ? xd : zd;
408
409 beginShape();
410 vertex(0, 0);
411 vertex(wid, 0);
412 vertex(wid, yd);
413 vertex(wid - sw, yd);
414 vertex(wid - sw, sw);
415 vertex(0, sw);
416 endShape();
417 beginShape();
418 vertex(0, sw);
419 vertex(0, yd);
420 vertex(wid - sw, yd);
421 vertex(wid - sw, yd - sw);
422 vertex(sw, yd - sw);
423 vertex(sw, sw);
424 endShape();
425
426 translate(wid, 0, 0);
427 rotate(HALF_PI, 0, -1, 0);
428 }
429 popMatrix();
430 }
73678c57
MS
431}
432
e037f60f 433void drawDiagnostics(long drawNanos, long simulationNanos, long uiNanos, long gammaNanos) {
73678c57
MS
434 float ws = 4 / 1000000.;
435 int thirtyfps = 1000000000 / 30;
436 int sixtyfps = 1000000000 / 60;
437 int x = width - 138;
438 int y = height - 14;
439 int h = 10;
440 noFill();
441 stroke(#999999);
442 rect(x, y, thirtyfps * ws, h);
443 noStroke();
444 int xp = x;
445 float hv = 0;
e037f60f 446 for (long val : new long[] {lx.timer.drawNanos, simulationNanos, uiNanos, gammaNanos, lx.timer.outputNanos }) {
73678c57
MS
447 fill(lx.hsb(hv % 360, 100, 80));
448 rect(xp, y, val * ws, h-1);
449 hv += 140;
450 xp += val * ws;
451 }
452 noFill();
453 stroke(#333333);
454 line(x+sixtyfps*ws, y+1, x+sixtyfps*ws, y+h-1);
ef7118ad
MS
455
456 y = y - 14;
457 xp = x;
458 float tw = thirtyfps * ws;
459 noFill();
460 stroke(#999999);
461 rect(x, y, tw, h);
bae2197a 462 h = 5;
ef7118ad
MS
463 noStroke();
464 for (long val : new long[] {
465 lx.engine.timer.deckNanos,
bae2197a 466 lx.engine.timer.copyNanos,
ef7118ad
MS
467 lx.engine.timer.fxNanos}) {
468 float amt = val / (float) lx.timer.drawNanos;
469 fill(lx.hsb(hv % 360, 100, 80));
470 rect(xp, y, amt * tw, h-1);
471 hv += 140;
472 xp += amt * tw;
bae2197a
MS
473 }
474
475 xp = x;
476 y += h;
477 hv = 120;
478 for (long val : new long[] {
479 lx.engine.getDeck(0).timer.runNanos,
480 lx.engine.getDeck(1).timer.runNanos,
481 lx.engine.getDeck(1).getFaderTransition().timer.blendNanos}) {
482 float amt = val / (float) lx.timer.drawNanos;
483 fill(lx.hsb(hv % 360, 100, 80));
484 rect(xp, y, amt * tw, h-1);
485 hv += 140;
486 xp += amt * tw;
487 }
7974acd6
MS
488}
489
4e6626a9 490void drawFPS() {
d626bc9b
MS
491 // Always draw FPS meter
492 fill(#555555);
493 textSize(9);
494 textAlign(LEFT, BASELINE);
495 text("FPS: " + ((int) (frameRate*10)) / 10. + " / " + targetFramerate + " (-/+)", 4, height-4);
49815cc0
MS
496}
497
4c640acc 498
34327c96
MS
499/**
500 * Top-level keyboard event handling
501 */
49815cc0 502void keyPressed() {
bf551144 503 if (mappingMode) {
d626bc9b 504 mappingTool.keyPressed(uiMapping);
bf551144 505 }
3f8be614 506 switch (key) {
2b068dd5
MS
507 case '1':
508 case '2':
509 case '3':
510 case '4':
511 case '5':
512 case '6':
513 case '7':
514 case '8':
515 if (!midiEngine.isQwertyEnabled()) {
516 presetManager.select(midiEngine.getFocusedDeck(), key - '1');
517 }
518 break;
519
520 case '!':
521 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 0);
522 break;
523 case '@':
524 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 1);
525 break;
526 case '#':
527 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 2);
528 break;
529 case '$':
530 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 3);
531 break;
532 case '%':
533 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 4);
534 break;
535 case '^':
536 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 5);
537 break;
538 case '&':
539 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 6);
540 break;
541 case '*':
542 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 7);
543 break;
544
0e3c5542
MS
545 case '-':
546 case '_':
547 frameRate(--targetFramerate);
548 break;
549 case '=':
550 case '+':
551 frameRate(++targetFramerate);
75e1ddde
MS
552 break;
553 case 'b':
24fc0330 554 effects.boom.trigger();
75e1ddde 555 break;
cc9fcf4b 556 case 'd':
d6ac1ee8 557 if (!midiEngine.isQwertyEnabled()) {
a8d55ade
MS
558 debugMode = !debugMode;
559 println("Debug output: " + (debugMode ? "ON" : "OFF"));
560 }
554e38ff 561 break;
bf551144 562 case 'm':
d6ac1ee8 563 if (!midiEngine.isQwertyEnabled()) {
a8d55ade
MS
564 mappingMode = !mappingMode;
565 uiPatternA.setVisible(!mappingMode);
566 uiMapping.setVisible(mappingMode);
567 if (mappingMode) {
568 restoreToPattern = lx.getPattern();
569 lx.setPatterns(new LXPattern[] { mappingTool });
570 } else {
571 lx.setPatterns(patterns);
572 LXTransition pop = restoreToPattern.getTransition();
573 restoreToPattern.setTransition(null);
574 lx.goPattern(restoreToPattern);
575 restoreToPattern.setTransition(pop);
576 }
bf551144
MS
577 }
578 break;
19d16a16
MS
579 case 't':
580 if (!midiEngine.isQwertyEnabled()) {
581 lx.engine.setThreaded(!lx.engine.isThreaded());
582 }
583 break;
e037f60f 584 case 'o':
e73ef85d 585 case 'p':
e037f60f
MS
586 for (LXOutput output : grizzlies) {
587 output.enabled.toggle();
79ae8245 588 }
cc9fcf4b 589 break;
73678c57
MS
590 case 'q':
591 if (!midiEngine.isQwertyEnabled()) {
592 diagnosticsOn = !diagnosticsOn;
593 }
594 break;
7974acd6
MS
595 case 's':
596 if (!midiEngine.isQwertyEnabled()) {
597 simulationOn = !simulationOn;
598 }
599 break;
d626bc9b 600 }
0a9f99cc 601}
73687629 602