annotate examples/10-Instruments/tank_wars/render.cpp @ 464:8fcfbfb32aa0 prerelease

Examples reorder with subdirectories. Added header to each project. Moved Doxygen to bottom of render.cpp.
author Robert Jack <robert.h.jack@gmail.com>
date Mon, 20 Jun 2016 16:20:38 +0100
parents
children
rev   line source
robert@464 1 /*
robert@464 2 * render.cpp
robert@464 3 *
robert@464 4 * Created on: Oct 24, 2014
robert@464 5 * Author: parallels
robert@464 6 */
robert@464 7
robert@464 8
robert@464 9 #include <Bela.h>
robert@464 10 #include "game.h"
robert@464 11 #include <rtdk.h>
robert@464 12 #include <cmath>
robert@464 13 #include <cstdlib>
robert@464 14 #include <time.h>
robert@464 15
robert@464 16 int gAudioFramesPerMatrixFrame = 2; // Ratio in audio to matrix sample rate
robert@464 17
robert@464 18 int gInputTank1Angle = 0; // Inputs for the cannon angles
robert@464 19 int gInputTank2Angle = 1;
robert@464 20 int gInputLauncher = 2; // Input for launcher FSR
robert@464 21
robert@464 22 int gOutputX = 0; // Outputs for the scope
robert@464 23 int gOutputY = 1;
robert@464 24 int gOutputPlayer1LED = 2;
robert@464 25 int gOutputPlayer2LED = 3;
robert@464 26
robert@464 27 int gGameFramesPerSecond = 60; // How often the physics are updated
robert@464 28 int gGameFrameInterval; // ...and in frames
robert@464 29 int gSamplesUntilNextFrame; // Counter until next update
robert@464 30 int gSamplesSinceFinish = 0; // How long since somebody won?
robert@464 31 bool gGameShouldRestart = false;// Whether we need to reinitiliase the game
robert@464 32
robert@464 33 // Counter for overall number of samples that have elapsed
robert@464 34 unsigned int gSampleCounter = 0;
robert@464 35
robert@464 36 // 1st-order filter and peak detector for launcher input
robert@464 37 float gLauncherLastSample = 0;
robert@464 38 float gLauncherFilterPole = 0.8;
robert@464 39 float gLauncherPeakValue = 0;
robert@464 40 float gLauncherPeakFilterPole = 0.999;
robert@464 41 float gLauncherNoiseThreshold = 0.01;
robert@464 42 float gLauncherMinimumPeak = 0.1;
robert@464 43 bool gLauncherTriggered = false;
robert@464 44
robert@464 45 // Screen update rate; affects buffer size. Actual contents of buffer
robert@464 46 // may be smaller than this
robert@464 47 int gScreenWidth = 512;
robert@464 48 int gScreenHeight = 512;
robert@464 49 int gScreenFramesPerSecond = 25;
robert@464 50
robert@464 51 // Double buffer for rendering screen. Each is an interleaved buffer
robert@464 52 // of XY data.
robert@464 53 float *gScreenBuffer1, *gScreenBuffer2;
robert@464 54 float *gScreenBufferWrite, *gScreenBufferRead;
robert@464 55 int gScreenBufferMaxLength; // What is the total buffer allocated?
robert@464 56 int gScreenBufferReadLength; // How long is the read buffer?
robert@464 57 int gScreenBufferWriteLength; // How long is the write (next) buffer?
robert@464 58 int gScreenBufferReadPointer; // Where are we in the read buffer now?
robert@464 59 int gScreenBufferNextUpdateLocation; // When should we render the next buffer?
robert@464 60 bool gScreenNextBufferReady; // Is the next buffer ready to go?
robert@464 61
robert@464 62 // Auxiliary (low-priority) task for updating the screen
robert@464 63 AuxiliaryTask gScreenUpdateTask;
robert@464 64
robert@464 65 // Buffers for music and sound effects
robert@464 66 extern float *gMusicBuffer;
robert@464 67 extern int gMusicBufferLength;
robert@464 68 extern float *gSoundBoomBuffer;
robert@464 69 extern int gSoundBoomBufferLength;
robert@464 70 extern float *gSoundHitBuffer;
robert@464 71 extern int gSoundHitBufferLength;
robert@464 72
robert@464 73 // Current state for sound and music
robert@464 74 int gMusicBufferPointer = 0; // 0 means start of buffer...
robert@464 75 int gSoundBoomBufferPointer = -1; // -1 means don't play...
robert@464 76 int gSoundHitBufferPointer = -1;
robert@464 77 float gSoundProjectileOscillatorPhase = 0;
robert@464 78 float gSoundProjectileOscillatorGain = 0.2;
robert@464 79 float gOscillatorPhaseScaler = 0;
robert@464 80
robert@464 81 void screen_update();
robert@464 82
robert@464 83 // setup() is called once before the audio rendering starts.
robert@464 84 // Use it to perform any initialisation and allocation which is dependent
robert@464 85 // on the period size or sample rate.
robert@464 86 //
robert@464 87 // userData holds an opaque pointer to a data structure that was passed
robert@464 88 // in from the call to initAudio().
robert@464 89 //
robert@464 90 // Return true on success; returning false halts the program.
robert@464 91
robert@464 92 bool setup(BelaContext *context, void *userData)
robert@464 93 {
robert@464 94 srandom(time(NULL));
robert@464 95
robert@464 96 // Verify we are running with matrix enabled
robert@464 97 if(context->analogFrames == 0 || context->analogChannels < 4) {
robert@464 98 rt_printf("Error: this example needs the matrix enabled with at least 4 channels\n");
robert@464 99 return false;
robert@464 100 }
robert@464 101
robert@464 102 // Initialise audio variables
robert@464 103 gAudioFramesPerMatrixFrame = context->audioFrames / context->analogFrames;
robert@464 104 gOscillatorPhaseScaler = 2.0 * M_PI / context->audioSampleRate;
robert@464 105
robert@464 106 // Initialise the screen buffers
robert@464 107 gScreenBufferMaxLength = 2 * context->analogSampleRate / gScreenFramesPerSecond;
robert@464 108 gScreenBuffer1 = new float[gScreenBufferMaxLength];
robert@464 109 gScreenBuffer2 = new float[gScreenBufferMaxLength];
robert@464 110 if(gScreenBuffer1 == 0 || gScreenBuffer2 == 0) {
robert@464 111 rt_printf("Error initialising screen buffers\n");
robert@464 112 return false;
robert@464 113 }
robert@464 114
robert@464 115 gScreenBufferRead = gScreenBuffer1;
robert@464 116 gScreenBufferWrite = gScreenBuffer2;
robert@464 117 gScreenBufferReadLength = gScreenBufferWriteLength = 0;
robert@464 118 gScreenBufferReadPointer = 0;
robert@464 119 gScreenBufferNextUpdateLocation = 0;
robert@464 120 gScreenNextBufferReady = false;
robert@464 121
robert@464 122 // Initialise the game
robert@464 123 setupGame(gScreenWidth, gScreenHeight);
robert@464 124 gGameFrameInterval = context->analogSampleRate / gGameFramesPerSecond;
robert@464 125 gSamplesUntilNextFrame = gGameFrameInterval;
robert@464 126
robert@464 127 // Initialise auxiliary tasks
robert@464 128 if((gScreenUpdateTask = Bela_createAuxiliaryTask(&screen_update, 90,
robert@464 129 "bela-screen-update")) == 0)
robert@464 130 return false;
robert@464 131
robert@464 132 return true;
robert@464 133 }
robert@464 134
robert@464 135 // Swap buffers on the screen
robert@464 136 void swap_buffers()
robert@464 137 {
robert@464 138 if(gScreenBufferRead == gScreenBuffer1) {
robert@464 139 gScreenBufferRead = gScreenBuffer2;
robert@464 140 gScreenBufferWrite = gScreenBuffer1;
robert@464 141 }
robert@464 142 else {
robert@464 143 gScreenBufferRead = gScreenBuffer1;
robert@464 144 gScreenBufferWrite = gScreenBuffer2;
robert@464 145 }
robert@464 146
robert@464 147 gScreenBufferReadLength = gScreenBufferWriteLength;
robert@464 148 gScreenBufferReadPointer = 0;
robert@464 149
robert@464 150 // Schedule next update for 3/4 of the way through the buffer
robert@464 151 gScreenBufferNextUpdateLocation = gScreenBufferReadLength * 0.75;
robert@464 152 gScreenNextBufferReady = false;
robert@464 153 }
robert@464 154
robert@464 155 // render() is called regularly at the highest priority by the audio engine.
robert@464 156 // Input and output are given from the audio hardware and the other
robert@464 157 // ADCs and DACs (if available). If only audio is available, numMatrixFrames
robert@464 158 // will be 0.
robert@464 159
robert@464 160 void render(BelaContext *context, void *userData)
robert@464 161 {
robert@464 162 int audioIndex = 0;
robert@464 163
robert@464 164 for(unsigned int n = 0; n < context->analogFrames; n++) {
robert@464 165 for(int k = 0; k < gAudioFramesPerMatrixFrame; k++) {
robert@464 166 // Render music and sound
robert@464 167 float audioSample = 0;
robert@464 168
robert@464 169 // Music plays in a loop
robert@464 170 if(gMusicBuffer != 0 && gMusicBufferPointer >= 0) {
robert@464 171 audioSample += gMusicBuffer[gMusicBufferPointer++];
robert@464 172 if(gMusicBufferPointer >= gMusicBufferLength)
robert@464 173 gMusicBufferPointer = 0;
robert@464 174 }
robert@464 175
robert@464 176 // Sound effect plays until finished, then stops
robert@464 177 if(gSoundBoomBuffer != 0 && gSoundBoomBufferPointer >= 0) {
robert@464 178 audioSample += gSoundBoomBuffer[gSoundBoomBufferPointer++];
robert@464 179 if(gSoundBoomBufferPointer >= gSoundBoomBufferLength)
robert@464 180 gSoundBoomBufferPointer = -1;
robert@464 181 }
robert@464 182
robert@464 183 if(gSoundHitBuffer != 0 && gSoundHitBufferPointer >= 0) {
robert@464 184 audioSample += gSoundHitBuffer[gSoundHitBufferPointer++];
robert@464 185 if(gSoundHitBufferPointer >= gSoundHitBufferLength)
robert@464 186 gSoundHitBufferPointer = -1;
robert@464 187 }
robert@464 188
robert@464 189 // Oscillator plays to indicate projectile height
robert@464 190 if(gameStatusProjectileInMotion()) {
robert@464 191 audioSample += gSoundProjectileOscillatorGain * sinf(gSoundProjectileOscillatorPhase);
robert@464 192
robert@464 193 gSoundProjectileOscillatorPhase += gOscillatorPhaseScaler * constrain(map(gameStatusProjectileHeight(),
robert@464 194 1.0, 0, 300, 2000), 200, 6000);
robert@464 195 if(gSoundProjectileOscillatorPhase > 2.0 * M_PI)
robert@464 196 gSoundProjectileOscillatorPhase -= 2.0 * M_PI;
robert@464 197 }
robert@464 198
robert@464 199 context->audioOut[2*audioIndex] = context->audioOut[2*audioIndex + 1] = audioSample;
robert@464 200 audioIndex++;
robert@464 201 }
robert@464 202
robert@464 203 // First-order lowpass filter to remove noise on launch FSR
robert@464 204 float rawSample = analogRead(context, n, gInputLauncher);
robert@464 205 float launchSample = gLauncherFilterPole * gLauncherLastSample +
robert@464 206 (1.0f - gLauncherFilterPole) * rawSample;
robert@464 207 gLauncherLastSample = launchSample;
robert@464 208
robert@464 209 // Peak-detect on launch signal
robert@464 210 if(launchSample >= gLauncherPeakValue) {
robert@464 211 gLauncherPeakValue = launchSample;
robert@464 212 gLauncherTriggered = false;
robert@464 213 }
robert@464 214 else {
robert@464 215 if(gLauncherPeakValue - launchSample > gLauncherNoiseThreshold && !gLauncherTriggered) {
robert@464 216 // Detected a peak; is it big enough overall?
robert@464 217 if(gLauncherPeakValue >= gLauncherMinimumPeak) {
robert@464 218 gLauncherTriggered = true;
robert@464 219 // Peak detected-- fire!!
robert@464 220 // Set both cannon strengths but only one will
robert@464 221 // fire depending on whose turn it is
robert@464 222 float strength = map(gLauncherPeakValue,
robert@464 223 gLauncherMinimumPeak, 1.0,
robert@464 224 0.5f, 10.0f);
robert@464 225 setTank1CannonStrength(strength);
robert@464 226 setTank2CannonStrength(strength);
robert@464 227 fireProjectile();
robert@464 228 }
robert@464 229 }
robert@464 230
robert@464 231 gLauncherPeakValue *= gLauncherPeakFilterPole;
robert@464 232 }
robert@464 233
robert@464 234 if(--gSamplesUntilNextFrame <= 0) {
robert@464 235 // Update game physics and cannon angles
robert@464 236 gSamplesUntilNextFrame = gGameFrameInterval;
robert@464 237
robert@464 238 setTank1CannonAngle(map(analogRead(context, n, gInputTank1Angle),
robert@464 239 0, 1.0, M_PI, 0));
robert@464 240 setTank2CannonAngle(map(analogRead(context, n, gInputTank2Angle),
robert@464 241 0, 1.0, M_PI, 0));
robert@464 242 nextGameFrame();
robert@464 243
robert@464 244 // Check for collision and start sound accordingly
robert@464 245 if(gameStatusCollisionOccurred()) {
robert@464 246 gSoundBoomBufferPointer = 0;
robert@464 247 }
robert@464 248
robert@464 249 if(gameStatusTankHitOccurred()) {
robert@464 250 gSoundHitBufferPointer = 0;
robert@464 251 }
robert@464 252 }
robert@464 253
robert@464 254 if(gScreenBufferReadPointer >= gScreenBufferReadLength - 1
robert@464 255 && gScreenNextBufferReady) {
robert@464 256 // Got to the end; swap buffers
robert@464 257 swap_buffers();
robert@464 258 }
robert@464 259
robert@464 260 // Push current screen buffer to the matrix output
robert@464 261 if(gScreenBufferReadPointer < gScreenBufferReadLength - 1) {
robert@464 262 float x = gScreenBufferRead[gScreenBufferReadPointer++];
robert@464 263 float y = gScreenBufferRead[gScreenBufferReadPointer++];
robert@464 264
robert@464 265 // Rescale screen coordinates to matrix ranges; invert the Y
robert@464 266 // coordinate to go from normal screen coordinates to scope coordinates
robert@464 267 analogWriteOnce(context, n, gOutputX, constrain(map(x, 0, gScreenWidth, 0, 1.0), 0, 1.0));
robert@464 268 analogWriteOnce(context, n, gOutputY, constrain(map(y, 0, gScreenHeight, 1.0, 0), 0, 1.0));
robert@464 269 }
robert@464 270 else {
robert@464 271 // Still not ready! Write 0 until something happens
robert@464 272 analogWriteOnce(context, n, gOutputX, 0);
robert@464 273 analogWriteOnce(context, n, gOutputY, 0);
robert@464 274 }
robert@464 275
robert@464 276 if(gameStatusWinner() != 0) {
robert@464 277 // Blink one LED to show who won
robert@464 278 // Blink both LEDs when projectile is in motion
robert@464 279 float val = (gSampleCounter % 4000 > 2000) ? 1.0 : 0;
robert@464 280 analogWriteOnce(context, n, gOutputPlayer1LED, gameStatusWinner() == 1 ? val : 0);
robert@464 281 analogWriteOnce(context, n, gOutputPlayer2LED, gameStatusWinner() == 2 ? val : 0);
robert@464 282
robert@464 283 // After 5 seconds, restart the game
robert@464 284 gSamplesSinceFinish++;
robert@464 285 if(gSamplesSinceFinish > 22050*5)
robert@464 286 gGameShouldRestart = true;
robert@464 287 }
robert@464 288 else if(gameStatusProjectileInMotion()) {
robert@464 289 // Blink both LEDs when projectile is in motion
robert@464 290 float val = (gSampleCounter % 2000 > 1000) ? 1.0 : 0;
robert@464 291 analogWriteOnce(context, n, gOutputPlayer1LED, val);
robert@464 292 analogWriteOnce(context, n, gOutputPlayer2LED, val);
robert@464 293 }
robert@464 294 else if(gameStatusPlayer1Turn()) {
robert@464 295 analogWriteOnce(context, n, gOutputPlayer1LED, 1.0);
robert@464 296 analogWriteOnce(context, n, gOutputPlayer2LED, 0);
robert@464 297 }
robert@464 298 else {
robert@464 299 analogWriteOnce(context, n, gOutputPlayer2LED, 1.0);
robert@464 300 analogWriteOnce(context, n, gOutputPlayer1LED, 0);
robert@464 301 }
robert@464 302
robert@464 303 // Check if we have reached the point where we should next update
robert@464 304 if(gScreenBufferReadPointer >= gScreenBufferNextUpdateLocation &&
robert@464 305 !gScreenNextBufferReady) {
robert@464 306 // Update the screen at lower priority than the audio thread
robert@464 307 Bela_scheduleAuxiliaryTask(gScreenUpdateTask);
robert@464 308 }
robert@464 309
robert@464 310 gSampleCounter++;
robert@464 311 }
robert@464 312 }
robert@464 313
robert@464 314 void screen_update()
robert@464 315 {
robert@464 316 // If we should restart, reinitialise the game
robert@464 317 if(gGameShouldRestart) {
robert@464 318 restartGame();
robert@464 319 gGameShouldRestart = false;
robert@464 320 gSamplesSinceFinish = 0;
robert@464 321 }
robert@464 322
robert@464 323 // Render the game based on the current state
robert@464 324 gScreenBufferWriteLength = drawGame(gScreenBufferWrite, gScreenBufferMaxLength);
robert@464 325
robert@464 326 // Flag it as ready to go
robert@464 327 gScreenNextBufferReady = true;
robert@464 328 }
robert@464 329
robert@464 330 // cleanup() is called once at the end, after the audio has stopped.
robert@464 331 // Release any resources that were allocated in setup().
robert@464 332
robert@464 333 void cleanup(BelaContext *context, void *userData)
robert@464 334 {
robert@464 335 // Clean up the game state
robert@464 336 cleanupGame();
robert@464 337 }