Add diagnostics meter to show time things take
[SugarCubes.git] / _Internals.pde
1 /**
2 * DOUBLE BLACK DIAMOND DOUBLE BLACK DIAMOND
3 *
4 * //\\ //\\ //\\ //\\
5 * ///\\\ ///\\\ ///\\\ ///\\\
6 * \\\/// \\\/// \\\/// \\\///
7 * \\// \\// \\// \\//H
8 *
9 * EXPERTS ONLY!! EXPERTS ONLY!!
10 *
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
16 import glucose.*;
17 import glucose.control.*;
18 import glucose.effect.*;
19 import glucose.model.*;
20 import glucose.pattern.*;
21 import glucose.transform.*;
22 import glucose.transition.*;
23 import heronarts.lx.*;
24 import heronarts.lx.control.*;
25 import heronarts.lx.effect.*;
26 import heronarts.lx.modulator.*;
27 import heronarts.lx.pattern.*;
28 import heronarts.lx.transition.*;
29 import ddf.minim.*;
30 import ddf.minim.analysis.*;
31 import processing.opengl.*;
32 import rwmidi.*;
33 import java.lang.reflect.*;
34
35 final int VIEWPORT_WIDTH = 900;
36 final int VIEWPORT_HEIGHT = 700;
37
38 // The trailer is measured from the outside of the black metal (but not including the higher welded part on the front)
39 final float TRAILER_WIDTH = 240;
40 final float TRAILER_DEPTH = 97;
41 final float TRAILER_HEIGHT = 33;
42
43 final int MaxCubeHeight = 5;
44 final int NumBackTowers = 11;
45
46 int targetFramerate = 60;
47 int startMillis, lastMillis;
48
49 // Core engine variables
50 GLucose glucose;
51 LX lx;
52 LXPattern[] patterns;
53 Effects effects;
54 MappingTool mappingTool;
55 PandaDriver[] pandaBoards;
56 PresetManager presetManager;
57 MidiEngine midiEngine;
58
59 // Display configuration mode
60 boolean mappingMode = false;
61 boolean debugMode = false;
62 DebugUI debugUI;
63 boolean uiOn = true;
64 boolean simulationOn = true;
65 boolean diagnosticsOn = false;
66 LXPattern restoreToPattern = null;
67 PImage logo;
68 float[] hsb = new float[3];
69
70 // Handles to UI objects
71 UIContext[] overlays;
72 UIPatternDeck uiPatternA;
73 UICrossfader uiCrossfader;
74 UIMidi uiMidi;
75 UIMapping uiMapping;
76 UIDebugText uiDebugText;
77 UISpeed uiSpeed;
78
79 // Camera variables
80 float eyeR, eyeA, eyeX, eyeY, eyeZ, midX, midY, midZ;
81
82 /**
83 * Engine construction and initialization.
84 */
85
86 LXTransition _transition(GLucose glucose) {
87 return new DissolveTransition(glucose.lx).setDuration(1000);
88 }
89
90 LXPattern[] _leftPatterns(GLucose glucose) {
91 LXPattern[] patterns = patterns(glucose);
92 for (LXPattern p : patterns) {
93 p.setTransition(_transition(glucose));
94 }
95 return patterns;
96 }
97
98 LXPattern[] _rightPatterns(GLucose glucose) {
99 LXPattern[] patterns = _leftPatterns(glucose);
100 LXPattern[] rightPatterns = new LXPattern[patterns.length+1];
101 int i = 0;
102 rightPatterns[i++] = new BlankPattern(glucose).setTransition(_transition(glucose));
103 for (LXPattern p : patterns) {
104 rightPatterns[i++] = p;
105 }
106 return rightPatterns;
107 }
108
109 LXEffect[] _effectsArray(Effects effects) {
110 List<LXEffect> effectList = new ArrayList<LXEffect>();
111 for (Field f : effects.getClass().getDeclaredFields()) {
112 try {
113 Object val = f.get(effects);
114 if (val instanceof LXEffect) {
115 effectList.add((LXEffect)val);
116 }
117 } catch (IllegalAccessException iax) {}
118 }
119 return effectList.toArray(new LXEffect[]{});
120 }
121
122 void logTime(String evt) {
123 int now = millis();
124 println(evt + ": " + (now - lastMillis) + "ms");
125 lastMillis = now;
126 }
127
128 void setup() {
129 startMillis = lastMillis = millis();
130
131 // Initialize the Processing graphics environment
132 size(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, OPENGL);
133 frameRate(targetFramerate);
134 noSmooth();
135 // hint(ENABLE_OPENGL_4X_SMOOTH); // no discernable improvement?
136 logTime("Created viewport");
137
138 // Create the GLucose engine to run the cubes
139 glucose = new GLucose(this, buildModel());
140 lx = glucose.lx;
141 lx.enableKeyboardTempo();
142 logTime("Built GLucose engine");
143
144 // Set the patterns
145 LXEngine engine = lx.engine;
146 engine.setPatterns(patterns = _leftPatterns(glucose));
147 engine.addDeck(_rightPatterns(glucose));
148 logTime("Built patterns");
149 glucose.setTransitions(transitions(glucose));
150 logTime("Built transitions");
151 glucose.lx.addEffects(_effectsArray(effects = new Effects()));
152 logTime("Built effects");
153
154 // Preset manager
155 presetManager = new PresetManager();
156 logTime("Loaded presets");
157
158 // MIDI devices
159 midiEngine = new MidiEngine();
160 logTime("Setup MIDI devices");
161
162 // Build output driver
163 PandaMapping[] pandaMappings = buildPandaList();
164 pandaBoards = new PandaDriver[pandaMappings.length];
165 int pbi = 0;
166 for (PandaMapping pm : pandaMappings) {
167 pandaBoards[pbi++] = new PandaDriver(pm.ip, glucose.model, pm);
168 }
169 mappingTool = new MappingTool(glucose, pandaMappings);
170 logTime("Built PandaDriver");
171
172 // Build overlay UI
173 debugUI = new DebugUI(pandaMappings);
174 overlays = new UIContext[] {
175 uiPatternA = new UIPatternDeck(lx.engine.getDeck(GLucose.LEFT_DECK), "PATTERN A", 4, 4, 140, 324),
176 new UIBlendMode(4, 332, 140, 86),
177 new UIEffects(4, 422, 140, 144),
178 new UITempo(4, 570, 140, 50),
179 uiSpeed = new UISpeed(4, 624, 140, 50),
180
181 new UIPatternDeck(lx.engine.getDeck(GLucose.RIGHT_DECK), "PATTERN B", width-144, 4, 140, 324),
182 uiMidi = new UIMidi(midiEngine, width-144, 332, 140, 158),
183 new UIOutput(width-144, 494, 140, 106),
184
185 uiCrossfader = new UICrossfader(width/2-90, height-90, 180, 86),
186
187 uiDebugText = new UIDebugText(148, height-138, width-304, 44),
188 uiMapping = new UIMapping(mappingTool, 4, 4, 140, 324),
189 };
190 uiMapping.setVisible(false);
191 logTime("Built overlay UI");
192
193 // Load logo image
194 logo = loadImage("data/logo.png");
195
196 // Setup camera
197 midX = TRAILER_WIDTH/2.;
198 midY = glucose.model.yMax/2;
199 midZ = TRAILER_DEPTH/2.;
200 eyeR = -290;
201 eyeA = .15;
202 eyeY = midY + 70;
203 eyeX = midX + eyeR*sin(eyeA);
204 eyeZ = midZ + eyeR*cos(eyeA);
205
206 // Add mouse scrolling event support
207 addMouseWheelListener(new java.awt.event.MouseWheelListener() {
208 public void mouseWheelMoved(java.awt.event.MouseWheelEvent mwe) {
209 mouseWheel(mwe.getWheelRotation());
210 }});
211
212 println("Total setup: " + (millis() - startMillis) + "ms");
213 println("Hit the 'p' key to toggle Panda Board output");
214 }
215
216 /**
217 * Core render loop and drawing functionality.
218 */
219 void draw() {
220 long drawStart = System.nanoTime();
221
222 // Draws the simulation and the 2D UI overlay
223 background(40);
224
225 color[] simulationColors;
226 color[] sendColors;
227 simulationColors = sendColors = glucose.getColors();
228 String displayMode = uiCrossfader.getDisplayMode();
229 if (displayMode == "A") {
230 simulationColors = lx.engine.getDeck(GLucose.LEFT_DECK).getColors();
231 } else if (displayMode == "B") {
232 simulationColors = lx.engine.getDeck(GLucose.RIGHT_DECK).getColors();
233 }
234 if (debugMode) {
235 debugUI.maskColors(simulationColors);
236 debugUI.maskColors(sendColors);
237 }
238
239 long simulationStart = System.nanoTime();
240 if (simulationOn) {
241 drawSimulation(simulationColors);
242 }
243 long simulationNanos = System.nanoTime() - simulationStart;
244
245 // 2D Overlay UI
246 long uiStart = System.nanoTime();
247 drawUI();
248 long uiNanos = System.nanoTime() - uiStart;
249
250 long gammaStart = System.nanoTime();
251 // Gamma correction here. Apply a cubic to the brightness
252 // for better representation of dynamic range
253 for (int i = 0; i < sendColors.length; ++i) {
254 lx.RGBtoHSB(sendColors[i], hsb);
255 float b = hsb[2];
256 sendColors[i] = lx.hsb(360.*hsb[0], 100.*hsb[1], 100.*(b*b*b));
257 }
258 long gammaNanos = System.nanoTime() - gammaStart;
259
260 long sendStart = System.nanoTime();
261 for (PandaDriver p : pandaBoards) {
262 p.send(sendColors);
263 }
264 long sendNanos = System.nanoTime() - sendStart;
265
266 long drawNanos = System.nanoTime() - drawStart;
267
268 if (diagnosticsOn) {
269 drawDiagnostics(lx.drawNanos(), drawNanos, simulationNanos, uiNanos, gammaNanos, sendNanos);
270 }
271 }
272
273 void drawDiagnostics(long lxNanos, long drawNanos, long simulationNanos, long uiNanos, long gammaNanos, long sendNanos) {
274 float ws = 4 / 1000000.;
275 int thirtyfps = 1000000000 / 30;
276 int sixtyfps = 1000000000 / 60;
277 int x = width - 138;
278 int y = height - 14;
279 int h = 10;
280 noFill();
281 stroke(#999999);
282 rect(x, y, thirtyfps * ws, h);
283 noStroke();
284 int xp = x;
285 float hv = 0;
286 for (long val : new long[] {lxNanos, simulationNanos, uiNanos, gammaNanos, sendNanos }) {
287 fill(lx.hsb(hv % 360, 100, 80));
288 rect(xp, y, val * ws, h-1);
289 hv += 140;
290 xp += val * ws;
291 }
292 noFill();
293 stroke(#333333);
294 line(x+sixtyfps*ws, y+1, x+sixtyfps*ws, y+h-1);
295 }
296
297 void drawSimulation(color[] simulationColors) {
298 camera(
299 eyeX, eyeY, eyeZ,
300 midX, midY, midZ,
301 0, -1, 0
302 );
303
304 translate(0, 40, 0);
305
306 noStroke();
307 fill(#141414);
308 drawBox(0, -TRAILER_HEIGHT, 0, 0, 0, 0, TRAILER_WIDTH, TRAILER_HEIGHT, TRAILER_DEPTH, TRAILER_HEIGHT/2.);
309 fill(#070707);
310 stroke(#222222);
311 beginShape();
312 vertex(0, 0, 0);
313 vertex(TRAILER_WIDTH, 0, 0);
314 vertex(TRAILER_WIDTH, 0, TRAILER_DEPTH);
315 vertex(0, 0, TRAILER_DEPTH);
316 endShape();
317
318 // Draw the logo on the front of platform
319 pushMatrix();
320 translate(0, 0, -1);
321 float s = .07;
322 scale(s, -s, s);
323 image(logo, TRAILER_WIDTH/2/s-logo.width/2, TRAILER_HEIGHT/2/s-logo.height/2-2/s);
324 popMatrix();
325
326 noStroke();
327 if (glucose.model.bassBox.exists) {
328 drawBassBox(glucose.model.bassBox, false);
329 }
330 for (Speaker speaker : glucose.model.speakers) {
331 drawSpeaker(speaker);
332 }
333 for (Cube c : glucose.model.cubes) {
334 drawCube(c);
335 }
336
337 noFill();
338 strokeWeight(2);
339 beginShape(POINTS);
340 for (Point p : glucose.model.points) {
341 stroke(simulationColors[p.index]);
342 vertex(p.x, p.y, p.z);
343 }
344 endShape();
345 }
346
347 void drawBassBox(BassBox b, boolean hasSub) {
348
349 float in = .15;
350
351 if (hasSub) {
352 noStroke();
353 fill(#191919);
354 pushMatrix();
355 translate(b.x + BassBox.EDGE_WIDTH/2., b.y + BassBox.EDGE_HEIGHT/2, b.z + BassBox.EDGE_DEPTH/2.);
356 box(BassBox.EDGE_WIDTH-20*in, BassBox.EDGE_HEIGHT-20*in, BassBox.EDGE_DEPTH-20*in);
357 popMatrix();
358 }
359
360 noStroke();
361 fill(#393939);
362 drawBox(b.x+in, b.y+in, b.z+in, 0, 0, 0, BassBox.EDGE_WIDTH-in*2, BassBox.EDGE_HEIGHT-in*2, BassBox.EDGE_DEPTH-in*2, Cube.CHANNEL_WIDTH-in);
363
364 pushMatrix();
365 translate(b.x+(Cube.CHANNEL_WIDTH-in)/2., b.y + BassBox.EDGE_HEIGHT-in, b.z + BassBox.EDGE_DEPTH/2.);
366 float lastOffset = 0;
367 for (float offset : BoothFloor.STRIP_OFFSETS) {
368 translate(offset - lastOffset, 0, 0);
369 box(Cube.CHANNEL_WIDTH-in, 0, BassBox.EDGE_DEPTH - 2*in);
370 lastOffset = offset;
371 }
372 popMatrix();
373
374 pushMatrix();
375 translate(b.x + (Cube.CHANNEL_WIDTH-in)/2., b.y + BassBox.EDGE_HEIGHT/2., b.z + in);
376 for (int j = 0; j < 2; ++j) {
377 pushMatrix();
378 for (int i = 0; i < BassBox.NUM_FRONT_STRUTS; ++i) {
379 translate(BassBox.FRONT_STRUT_SPACING, 0, 0);
380 box(Cube.CHANNEL_WIDTH-in, BassBox.EDGE_HEIGHT - in*2, 0);
381 }
382 popMatrix();
383 translate(0, 0, BassBox.EDGE_DEPTH - 2*in);
384 }
385 popMatrix();
386
387 pushMatrix();
388 translate(b.x + in, b.y + BassBox.EDGE_HEIGHT/2., b.z + BassBox.SIDE_STRUT_SPACING + (Cube.CHANNEL_WIDTH-in)/2.);
389 box(0, BassBox.EDGE_HEIGHT - in*2, Cube.CHANNEL_WIDTH-in);
390 translate(BassBox.EDGE_WIDTH-2*in, 0, 0);
391 box(0, BassBox.EDGE_HEIGHT - in*2, Cube.CHANNEL_WIDTH-in);
392 popMatrix();
393
394 }
395
396 void drawCube(Cube c) {
397 float in = .15;
398 noStroke();
399 fill(#393939);
400 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);
401 }
402
403 void drawSpeaker(Speaker s) {
404 float in = .15;
405
406 noStroke();
407 fill(#191919);
408 pushMatrix();
409 translate(s.x, s.y, s.z);
410 rotate(s.ry / 180. * PI, 0, -1, 0);
411 translate(Speaker.EDGE_WIDTH/2., Speaker.EDGE_HEIGHT/2., Speaker.EDGE_DEPTH/2.);
412 box(Speaker.EDGE_WIDTH-20*in, Speaker.EDGE_HEIGHT-20*in, Speaker.EDGE_DEPTH-20*in);
413 translate(0, Speaker.EDGE_HEIGHT/2. + Speaker.EDGE_HEIGHT*.8/2, 0);
414
415 fill(#222222);
416 box(Speaker.EDGE_WIDTH*.6, Speaker.EDGE_HEIGHT*.8, Speaker.EDGE_DEPTH*.75);
417 popMatrix();
418
419 noStroke();
420 fill(#393939);
421 drawBox(s.x+in, s.y+in, s.z+in, 0, s.ry, 0, Speaker.EDGE_WIDTH-in*2, Speaker.EDGE_HEIGHT-in*2, Speaker.EDGE_DEPTH-in*2, Cube.CHANNEL_WIDTH-in);
422 }
423
424 void drawBox(float x, float y, float z, float rx, float ry, float rz, float xd, float yd, float zd, float sw) {
425 pushMatrix();
426 translate(x, y, z);
427 rotate(rx / 180. * PI, -1, 0, 0);
428 rotate(ry / 180. * PI, 0, -1, 0);
429 rotate(rz / 180. * PI, 0, 0, -1);
430 for (int i = 0; i < 4; ++i) {
431 float wid = (i % 2 == 0) ? xd : zd;
432
433 beginShape();
434 vertex(0, 0);
435 vertex(wid, 0);
436 vertex(wid, yd);
437 vertex(wid - sw, yd);
438 vertex(wid - sw, sw);
439 vertex(0, sw);
440 endShape();
441 beginShape();
442 vertex(0, sw);
443 vertex(0, yd);
444 vertex(wid - sw, yd);
445 vertex(wid - sw, yd - sw);
446 vertex(sw, yd - sw);
447 vertex(sw, sw);
448 endShape();
449
450 translate(wid, 0, 0);
451 rotate(HALF_PI, 0, -1, 0);
452 }
453 popMatrix();
454 }
455
456 void drawUI() {
457 camera();
458 javax.media.opengl.GL gl = ((PGraphicsOpenGL)g).beginGL();
459 gl.glClear(javax.media.opengl.GL.GL_DEPTH_BUFFER_BIT);
460 ((PGraphicsOpenGL)g).endGL();
461 strokeWeight(1);
462
463 if (uiOn) {
464 for (UIContext context : overlays) {
465 context.draw();
466 }
467 }
468
469 // Always draw FPS meter
470 fill(#555555);
471 textSize(9);
472 textAlign(LEFT, BASELINE);
473 text("FPS: " + ((int) (frameRate*10)) / 10. + " / " + targetFramerate + " (-/+)", 4, height-4);
474
475 if (debugMode) {
476 debugUI.draw();
477 }
478 }
479
480
481 /**
482 * Top-level keyboard event handling
483 */
484 void keyPressed() {
485 if (mappingMode) {
486 mappingTool.keyPressed(uiMapping);
487 }
488 switch (key) {
489 case '1':
490 case '2':
491 case '3':
492 case '4':
493 case '5':
494 case '6':
495 case '7':
496 case '8':
497 if (!midiEngine.isQwertyEnabled()) {
498 presetManager.select(midiEngine.getFocusedDeck(), key - '1');
499 }
500 break;
501
502 case '!':
503 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 0);
504 break;
505 case '@':
506 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 1);
507 break;
508 case '#':
509 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 2);
510 break;
511 case '$':
512 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 3);
513 break;
514 case '%':
515 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 4);
516 break;
517 case '^':
518 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 5);
519 break;
520 case '&':
521 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 6);
522 break;
523 case '*':
524 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 7);
525 break;
526
527 case '-':
528 case '_':
529 frameRate(--targetFramerate);
530 break;
531 case '=':
532 case '+':
533 frameRate(++targetFramerate);
534 break;
535 case 'b':
536 effects.boom.trigger();
537 break;
538 case 'd':
539 if (!midiEngine.isQwertyEnabled()) {
540 debugMode = !debugMode;
541 println("Debug output: " + (debugMode ? "ON" : "OFF"));
542 }
543 break;
544 case 'm':
545 if (!midiEngine.isQwertyEnabled()) {
546 mappingMode = !mappingMode;
547 uiPatternA.setVisible(!mappingMode);
548 uiMapping.setVisible(mappingMode);
549 if (mappingMode) {
550 restoreToPattern = lx.getPattern();
551 lx.setPatterns(new LXPattern[] { mappingTool });
552 } else {
553 lx.setPatterns(patterns);
554 LXTransition pop = restoreToPattern.getTransition();
555 restoreToPattern.setTransition(null);
556 lx.goPattern(restoreToPattern);
557 restoreToPattern.setTransition(pop);
558 }
559 }
560 break;
561 case 't':
562 if (!midiEngine.isQwertyEnabled()) {
563 lx.engine.setThreaded(!lx.engine.isThreaded());
564 }
565 break;
566 case 'p':
567 for (PandaDriver p : pandaBoards) {
568 p.toggle();
569 }
570 break;
571 case 'q':
572 if (!midiEngine.isQwertyEnabled()) {
573 diagnosticsOn = !diagnosticsOn;
574 }
575 break;
576 case 's':
577 if (!midiEngine.isQwertyEnabled()) {
578 simulationOn = !simulationOn;
579 }
580 break;
581 case 'u':
582 if (!midiEngine.isQwertyEnabled()) {
583 uiOn = !uiOn;
584 }
585 break;
586 }
587 }
588
589 /**
590 * Top-level mouse event handling
591 */
592 int mx, my;
593 void mousePressed() {
594 boolean debugged = false;
595 if (debugMode) {
596 debugged = debugUI.mousePressed();
597 }
598 if (!debugged) {
599 for (UIContext context : overlays) {
600 context.mousePressed(mouseX, mouseY);
601 }
602 }
603 mx = mouseX;
604 my = mouseY;
605 }
606
607 void mouseDragged() {
608 boolean dragged = false;
609 for (UIContext context : overlays) {
610 dragged |= context.mouseDragged(mouseX, mouseY);
611 }
612 if (!dragged) {
613 int dx = mouseX - mx;
614 int dy = mouseY - my;
615 mx = mouseX;
616 my = mouseY;
617 eyeA += dx*.003;
618 eyeX = midX + eyeR*sin(eyeA);
619 eyeZ = midZ + eyeR*cos(eyeA);
620 eyeY += dy;
621 }
622 }
623
624 void mouseReleased() {
625 for (UIContext context : overlays) {
626 context.mouseReleased(mouseX, mouseY);
627 }
628 }
629
630 void mouseWheel(int delta) {
631 boolean wheeled = false;
632 for (UIContext context : overlays) {
633 wheeled |= context.mouseWheel(mouseX, mouseY, delta);
634 }
635
636 if (!wheeled) {
637 eyeR = constrain(eyeR - delta, -500, -80);
638 eyeX = midX + eyeR*sin(eyeA);
639 eyeZ = midZ + eyeR*cos(eyeA);
640 }
641 }