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