1b313ccbad5620ec1f16e71e283874ba3b8125d5
[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 heronarts.lx.*;
18 import heronarts.lx.effect.*;
19 import heronarts.lx.model.*;
20 import heronarts.lx.modulator.*;
21 import heronarts.lx.parameter.*;
22 import heronarts.lx.pattern.*;
23 import heronarts.lx.transform.*;
24 import heronarts.lx.transition.*;
25 import heronarts.lx.ui.*;
26 import heronarts.lx.ui.component.*;
27 import heronarts.lx.ui.control.*;
28 import ddf.minim.*;
29 import ddf.minim.analysis.*;
30 import processing.opengl.*;
31 import rwmidi.*;
32 import java.lang.reflect.*;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.List;
36
37 final int VIEWPORT_WIDTH = 900;
38 final int VIEWPORT_HEIGHT = 700;
39
40 // The trailer is measured from the outside of the black metal (but not including the higher welded part on the front)
41 final float TRAILER_WIDTH = 192;
42 final float TRAILER_DEPTH = 192;
43 final float TRAILER_HEIGHT = 33;
44
45 int targetFramerate = 60;
46 int startMillis, lastMillis;
47
48 // Core engine variables
49 GLucose glucose;
50 LX lx;
51 Model model;
52 LXPattern[] patterns;
53 Effects effects;
54 MappingTool mappingTool;
55 GrizzlyOutput[] grizzlies;
56 PresetManager presetManager;
57 MidiEngine midiEngine;
58
59 // Display configuration mode
60 boolean mappingMode = false;
61 boolean debugMode = false;
62 boolean simulationOn = true;
63 boolean diagnosticsOn = false;
64 LXPattern restoreToPattern = null;
65 PImage logo;
66 float[] hsb = new float[3];
67
68 // Handles to UI objects
69 UIPatternDeck uiPatternA;
70 UICrossfader uiCrossfader;
71 UIMidi uiMidi;
72 UIMapping uiMapping;
73 UIDebugText uiDebugText;
74 UISpeed uiSpeed;
75
76 /**
77 * Engine construction and initialization.
78 */
79
80 LXTransition _transition(GLucose glucose) {
81 return new DissolveTransition(glucose.lx).setDuration(1000);
82 }
83
84 LXPattern[] _leftPatterns(GLucose glucose) {
85 LXPattern[] patterns = patterns(glucose);
86 for (LXPattern p : patterns) {
87 p.setTransition(_transition(glucose));
88 }
89 return patterns;
90 }
91
92 LXPattern[] _rightPatterns(GLucose glucose) {
93 LXPattern[] patterns = _leftPatterns(glucose);
94 LXPattern[] rightPatterns = new LXPattern[patterns.length+1];
95 int i = 0;
96 rightPatterns[i++] = new BlankPattern(glucose).setTransition(_transition(glucose));
97 for (LXPattern p : patterns) {
98 rightPatterns[i++] = p;
99 }
100 return rightPatterns;
101 }
102
103 LXEffect[] _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 }
115
116 void logTime(String evt) {
117 int now = millis();
118 println(evt + ": " + (now - lastMillis) + "ms");
119 lastMillis = now;
120 }
121
122 void setup() {
123 startMillis = lastMillis = millis();
124
125 // Initialize the Processing graphics environment
126 size(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, OPENGL);
127 frameRate(targetFramerate);
128 noSmooth();
129 // hint(ENABLE_OPENGL_4X_SMOOTH); // no discernable improvement?
130 logTime("Created viewport");
131
132 // Create the GLucose engine to run the cubes
133 glucose = new GLucose(this, model = buildModel());
134 lx = glucose.lx;
135 lx.enableKeyboardTempo();
136 logTime("Built GLucose engine");
137
138 // Set the patterns
139 LXEngine engine = lx.engine;
140 engine.setPatterns(patterns = _leftPatterns(glucose));
141 engine.addDeck(_rightPatterns(glucose));
142 logTime("Built patterns");
143 glucose.setTransitions(transitions(glucose));
144 logTime("Built transitions");
145 glucose.lx.addEffects(_effectsArray(effects = new Effects()));
146 logTime("Built effects");
147
148 // Preset manager
149 presetManager = new PresetManager();
150 logTime("Loaded presets");
151
152 // MIDI devices
153 midiEngine = new MidiEngine();
154 logTime("Setup MIDI devices");
155
156 // Build output driver
157 grizzlies = new GrizzlyOutput[]{};
158 try {
159 grizzlies = buildGrizzlies();
160 for (LXOutput output : grizzlies) {
161 lx.addOutput(output);
162 }
163 } catch (Exception x) {
164 x.printStackTrace();
165 }
166 logTime("Built Grizzly Outputs");
167
168 // Mapping tools
169 mappingTool = new MappingTool(glucose);
170
171 // Build overlay UI
172 UILayer[] layers = new UILayer[] {
173 // Camera layer
174 new UICameraLayer(lx.ui)
175 .setCenter(model.cx, model.cy, model.cz)
176 .setRadius(290).addComponent(new UICubesLayer()),
177
178 // Left controls
179 uiPatternA = new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.LEFT_DECK), "PATTERN A", 4, 4, 140, 324),
180 new UIBlendMode(4, 332, 140, 86),
181 new UIEffects(4, 422, 140, 144),
182 new UITempo(4, 570, 140, 50),
183 uiSpeed = new UISpeed(4, 624, 140, 50),
184
185 // Right controls
186 new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.RIGHT_DECK), "PATTERN B", width-144, 4, 140, 324),
187 uiMidi = new UIMidi(midiEngine, width-144, 332, 140, 158),
188 new UIOutput(grizzlies, width-144, 494, 140, 106),
189
190 // Crossfader
191 uiCrossfader = new UICrossfader(width/2-90, height-90, 180, 86),
192
193 // Overlays
194 uiDebugText = new UIDebugText(148, height-138, width-304, 44),
195 uiMapping = new UIMapping(mappingTool, 4, 4, 140, 324)
196 };
197 uiMapping.setVisible(false);
198 for (UILayer layer : layers) {
199 lx.ui.addLayer(layer);
200 }
201 logTime("Built UI");
202
203 // Load logo image
204 logo = loadImage("data/logo.png");
205 logTime("Loaded logo image");
206
207 println("Total setup: " + (millis() - startMillis) + "ms");
208 println("Hit the 'o' key to toggle live output");
209 }
210
211 long simulationNanos = 0;
212
213 /**
214 * Core render loop and drawing functionality.
215 */
216 void draw() {
217 long drawStart = System.nanoTime();
218
219 // Set background
220 background(40);
221
222 // Send colors
223 color[] sendColors = glucose.getColors();
224 long gammaStart = System.nanoTime();
225 // Gamma correction here. Apply a cubic to the brightness
226 // for better representation of dynamic range
227 for (int i = 0; i < sendColors.length; ++i) {
228 lx.RGBtoHSB(sendColors[i], hsb);
229 float b = hsb[2];
230 sendColors[i] = lx.hsb(360.*hsb[0], 100.*hsb[1], 100.*(b*b*b));
231 }
232 long gammaNanos = System.nanoTime() - gammaStart;
233
234 // Always draw FPS meter
235 drawFPS();
236
237 // TODO(mcslee): fix
238 long drawNanos = System.nanoTime() - drawStart;
239 long uiNanos = 0;
240
241 if (diagnosticsOn) {
242 drawDiagnostics(drawNanos, simulationNanos, uiNanos, gammaNanos);
243 }
244 }
245
246 class UICubesLayer extends UICameraComponent {
247 void onDraw(UI ui) {
248 color[] simulationColors = glucose.getColors();
249 String displayMode = uiCrossfader.getDisplayMode();
250 if (displayMode == "A") {
251 simulationColors = lx.engine.getDeck(GLucose.LEFT_DECK).getColors();
252 } else if (displayMode == "B") {
253 simulationColors = lx.engine.getDeck(GLucose.RIGHT_DECK).getColors();
254 }
255
256 long simulationStart = System.nanoTime();
257 if (simulationOn) {
258 drawSimulation(simulationColors);
259 }
260 simulationNanos = System.nanoTime() - simulationStart;
261
262 camera();
263 javax.media.opengl.GL gl = ((PGraphicsOpenGL)g).beginGL();
264 gl.glClear(javax.media.opengl.GL.GL_DEPTH_BUFFER_BIT);
265 ((PGraphicsOpenGL)g).endGL();
266 strokeWeight(1);
267 }
268
269 void drawSimulation(color[] simulationColors) {
270 translate(0, 30, 0);
271
272 noStroke();
273 fill(#141414);
274 drawBox(0, -TRAILER_HEIGHT, 0, 0, 0, 0, TRAILER_WIDTH, TRAILER_HEIGHT, TRAILER_DEPTH, TRAILER_HEIGHT/2.);
275 fill(#070707);
276 stroke(#222222);
277 beginShape();
278 vertex(0, 0, 0);
279 vertex(TRAILER_WIDTH, 0, 0);
280 vertex(TRAILER_WIDTH, 0, TRAILER_DEPTH);
281 vertex(0, 0, TRAILER_DEPTH);
282 endShape();
283
284 // Draw the logo on the front of platform
285 pushMatrix();
286 translate(0, 0, -1);
287 float s = .07;
288 scale(s, -s, s);
289 image(logo, TRAILER_WIDTH/2/s-logo.width/2, TRAILER_HEIGHT/2/s-logo.height/2-2/s);
290 popMatrix();
291
292 noStroke();
293 for (Cube c : model.cubes) {
294 drawCube(c);
295 }
296
297 noFill();
298 strokeWeight(2);
299 beginShape(POINTS);
300 for (LXPoint p : model.points) {
301 stroke(simulationColors[p.index]);
302 vertex(p.x, p.y, p.z);
303 }
304 endShape();
305 }
306
307 void drawCube(Cube c) {
308 float in = .15;
309 noStroke();
310 fill(#393939);
311 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);
312 }
313
314 void drawBox(float x, float y, float z, float rx, float ry, float rz, float xd, float yd, float zd, float sw) {
315 pushMatrix();
316 translate(x, y, z);
317 rotate(rx / 180. * PI, -1, 0, 0);
318 rotate(ry / 180. * PI, 0, -1, 0);
319 rotate(rz / 180. * PI, 0, 0, -1);
320 for (int i = 0; i < 4; ++i) {
321 float wid = (i % 2 == 0) ? xd : zd;
322
323 beginShape();
324 vertex(0, 0);
325 vertex(wid, 0);
326 vertex(wid, yd);
327 vertex(wid - sw, yd);
328 vertex(wid - sw, sw);
329 vertex(0, sw);
330 endShape();
331 beginShape();
332 vertex(0, sw);
333 vertex(0, yd);
334 vertex(wid - sw, yd);
335 vertex(wid - sw, yd - sw);
336 vertex(sw, yd - sw);
337 vertex(sw, sw);
338 endShape();
339
340 translate(wid, 0, 0);
341 rotate(HALF_PI, 0, -1, 0);
342 }
343 popMatrix();
344 }
345 }
346
347 void drawDiagnostics(long drawNanos, long simulationNanos, long uiNanos, long gammaNanos) {
348 float ws = 4 / 1000000.;
349 int thirtyfps = 1000000000 / 30;
350 int sixtyfps = 1000000000 / 60;
351 int x = width - 138;
352 int y = height - 14;
353 int h = 10;
354 noFill();
355 stroke(#999999);
356 rect(x, y, thirtyfps * ws, h);
357 noStroke();
358 int xp = x;
359 float hv = 0;
360 for (long val : new long[] {lx.timer.drawNanos, simulationNanos, uiNanos, gammaNanos, lx.timer.outputNanos }) {
361 fill(lx.hsb(hv % 360, 100, 80));
362 rect(xp, y, val * ws, h-1);
363 hv += 140;
364 xp += val * ws;
365 }
366 noFill();
367 stroke(#333333);
368 line(x+sixtyfps*ws, y+1, x+sixtyfps*ws, y+h-1);
369
370 y = y - 14;
371 xp = x;
372 float tw = thirtyfps * ws;
373 noFill();
374 stroke(#999999);
375 rect(x, y, tw, h);
376 h = 5;
377 noStroke();
378 for (long val : new long[] {
379 lx.engine.timer.deckNanos,
380 lx.engine.timer.copyNanos,
381 lx.engine.timer.fxNanos}) {
382 float amt = val / (float) lx.timer.drawNanos;
383 fill(lx.hsb(hv % 360, 100, 80));
384 rect(xp, y, amt * tw, h-1);
385 hv += 140;
386 xp += amt * tw;
387 }
388
389 xp = x;
390 y += h;
391 hv = 120;
392 for (long val : new long[] {
393 lx.engine.getDeck(0).timer.runNanos,
394 lx.engine.getDeck(1).timer.runNanos,
395 lx.engine.getDeck(1).getFaderTransition().timer.blendNanos}) {
396 float amt = val / (float) lx.timer.drawNanos;
397 fill(lx.hsb(hv % 360, 100, 80));
398 rect(xp, y, amt * tw, h-1);
399 hv += 140;
400 xp += amt * tw;
401 }
402 }
403
404 void drawFPS() {
405 // Always draw FPS meter
406 fill(#555555);
407 textSize(9);
408 textAlign(LEFT, BASELINE);
409 text("FPS: " + ((int) (frameRate*10)) / 10. + " / " + targetFramerate + " (-/+)", 4, height-4);
410 }
411
412
413 /**
414 * Top-level keyboard event handling
415 */
416 void keyPressed() {
417 if (mappingMode) {
418 mappingTool.keyPressed(uiMapping);
419 }
420 switch (key) {
421 case '1':
422 case '2':
423 case '3':
424 case '4':
425 case '5':
426 case '6':
427 case '7':
428 case '8':
429 if (!midiEngine.isQwertyEnabled()) {
430 presetManager.select(midiEngine.getFocusedDeck(), key - '1');
431 }
432 break;
433
434 case '!':
435 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 0);
436 break;
437 case '@':
438 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 1);
439 break;
440 case '#':
441 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 2);
442 break;
443 case '$':
444 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 3);
445 break;
446 case '%':
447 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 4);
448 break;
449 case '^':
450 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 5);
451 break;
452 case '&':
453 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 6);
454 break;
455 case '*':
456 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 7);
457 break;
458
459 case '-':
460 case '_':
461 frameRate(--targetFramerate);
462 break;
463 case '=':
464 case '+':
465 frameRate(++targetFramerate);
466 break;
467 case 'b':
468 effects.boom.trigger();
469 break;
470 case 'd':
471 if (!midiEngine.isQwertyEnabled()) {
472 debugMode = !debugMode;
473 println("Debug output: " + (debugMode ? "ON" : "OFF"));
474 }
475 break;
476 case 'm':
477 if (!midiEngine.isQwertyEnabled()) {
478 mappingMode = !mappingMode;
479 uiPatternA.setVisible(!mappingMode);
480 uiMapping.setVisible(mappingMode);
481 if (mappingMode) {
482 restoreToPattern = lx.getPattern();
483 lx.setPatterns(new LXPattern[] { mappingTool });
484 } else {
485 lx.setPatterns(patterns);
486 LXTransition pop = restoreToPattern.getTransition();
487 restoreToPattern.setTransition(null);
488 lx.goPattern(restoreToPattern);
489 restoreToPattern.setTransition(pop);
490 }
491 }
492 break;
493 case 't':
494 if (!midiEngine.isQwertyEnabled()) {
495 lx.engine.setThreaded(!lx.engine.isThreaded());
496 }
497 break;
498 case 'o':
499 case 'p':
500 for (LXOutput output : grizzlies) {
501 output.enabled.toggle();
502 }
503 break;
504 case 'q':
505 if (!midiEngine.isQwertyEnabled()) {
506 diagnosticsOn = !diagnosticsOn;
507 }
508 break;
509 case 's':
510 if (!midiEngine.isQwertyEnabled()) {
511 simulationOn = !simulationOn;
512 }
513 break;
514 }
515 }
516