ase / index.js
gafoart's picture
Upload 6 files
5268b4e verified
// --------------------------------------------------
// Global Constants.
// --------------------------------------------------
// Store PI as global constant.
var MATH_PI = Math.PI;
// Force mobile testing mode to see how it would behave.
var FORCE_MOBILE_FOR_TESTING = false;
// Top area where we draw waveforms and strings, aspect ratio limits
// so for ultra wide or ultra narrow it doesn't get too spread out or scrunched.
var TOP_ASPECT_RATIO_MAX = 1.6;
var TOP_ASPECT_RATIO_MIN = 0.4;
// Pass this in url e.g. ?sound=triangle
var SOUND = getQueryVariable("sound") == null ? "sine" : getQueryVariable("sound").toLowerCase();
// --------------------------------------------------
// Global variables
// --------------------------------------------------
// the Web Audio "context" object
var context = null;
// width of the movie
var width, height;
// initialize timer variable and frame counter
var t0, t1;
// first time running resize funciton?
var needToInitializeCanvas = true;
var canvasElement, ctx, startButtonElement;
// mobile check
var isMobile; var mobileOS;
// Margins for the overall movie
var leftMargin, rightMargin, topMargin, bottomMargin;
// Aspect ratio of the window - e.g. 1.0 = square, 2.0 = 2:1 horizontal, 0.5 = 1:2 vertical.
var aspectRatio;
// Is user pressing
var isMousePressing = false;
// Used to keep track of active touches.
var currentTouches = new Array;
// Link to main current controller object
var m;
// Link to Tone.context audioContext
var audioContext = Tone.context;
//-------------------------//
// Touch Functions
//-------------------------//
// Finds the array index of a touch in the currentTouches array.
var findCurrentTouchIndex = function (id) {
for (var i=0; i < currentTouches.length; i++) {
if (currentTouches[i].id === id) {
return i;
}
}
// Touch not found! Return -1.
return -1;
};
// Creates a new touch in the currentTouches array and draws the starting
// point on the canvas.
var touchStarted = function (e) {
var touches = e.changedTouches;
for (var i=0; i < touches.length; i++) {
var touch = touches[i];
currentTouches.push({
id: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
});
}
};
// Draws a line on the canvas between the previous touch location and
// the new location.
var touchMoved = function (e) {
var touches = e.changedTouches;
// New code
for (var i=0; i < touches.length; i++) {
var touch = touches[i];
var currentTouchIndex = findCurrentTouchIndex(touch.identifier);
if (currentTouchIndex >= 0) {
var currentTouch = currentTouches[currentTouchIndex];
// Update the touch record.
currentTouch.pageX = touch.pageX;
currentTouch.pageY = touch.pageY;
// Store the record.
currentTouches.splice(currentTouchIndex, 1, currentTouch);
} else {
console.log('Touch was not found!');
}
}
};
// Draws a line to the final touch position on the canvas and then
// removes the touh from the currentTouches array.
var touchEnded = function (e) {
var touches = e.changedTouches;
// New code
for (var i=0; i < touches.length; i++) {
var touch = touches[i];
var currentTouchIndex = findCurrentTouchIndex(touch.identifier);
// Harmonics mode
if (MODE == 0) {
// Strings mode
} else if (MODE == 1) {
var g;
// find the grabber we should destroy
for (var i = 0; i < m.arrGrabbers.length; i++) {
g = m.arrGrabbers[i];
if (g.touchId == touch.identifier) {
// let go of threads if it's holding any
g.dropAll();
m.destroyGrabber(g);
}
}
}
// Now remove the touch itself
if (currentTouchIndex >= 0) {
var currentTouch = currentTouches[currentTouchIndex];
// Remove the record.
currentTouches.splice(currentTouchIndex, 1);
} else {
console.log('Touch was not found!');
}
}
};
// Removes cancelled touches from the currentTouches array.
var touchCancelled = function (e) {
var touches = e.changedTouches;
for (var i=0; i < touches.length; i++) {
var currentTouchIndex = findCurrentTouchIndex(touches[i].identifier);
// Harmonics mode
if (mode == 0) {
// Strings mode
} else if (mode == 1) {
var g;
// find the grabber we should destroy
for (var i = 0; i < m.arrGrabbers.length; i++) {
g = m.arrGrabbers[i];
if (g.touchId == touch.identifier) {
m.destroyGrabber(g);
}
}
// Wind mode
} else if (mode == 2) {
// Bars mode
} else {
}
// Now remove the touch object
if (currentTouchIndex >= 0) {
// Remove the touch record.
currentTouches.splice(currentTouchIndex, 1);
} else {
console.log('Touch was not found!');
}
}
};
// ----------------------------------------------
// Mouse Functions
// ----------------------------------------------
var xMouse, yMouse;
var mouseDown = function(e) {
m.mouseDown(e);
isMousePressing = true;
xMouse = e.clientX;
yMouse = e.clientY;
}
var mouseMove = function(e) {
xMouse = e.clientX;
yMouse = e.clientY;
};
var mouseUp = function(e) {
m.mouseUp(e);
isMousePressing = false;
};
// ----------------------------------------------
// Initialize
// ----------------------------------------------
window.addEventListener('load', function() {
// create canvases
canvasElement = document.getElementById("canvas0");
startButtonElement = document.getElementById("startButtonImage");
ctx = canvasElement.getContext("2d");
// Create Web Audio Context, future proofed for future browsers
contextClass = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext);
if (contextClass) {
context = new contextClass();
} else {
// Web Audio API not available. Ask user to use a supported browser.
}
// initialize mouse position -- *** might need to look at this later,
// as it initializes to the top left corner, the initial mouse down moment
// might be seen as a giant jump
xMouse = 0; yMouse = 0;
// create main object
m = new HarmonicController();
// run the resize function now
rsize();
// start now
begin();
});
/**
* ------------------------------------------------
* Update loop run via requestAnimationFrame.
* ------------------------------------------------
*/
var render = function() {
t1 = context.currentTime;
timeDelta = t1-t0;
// clear the draw area
ctx.clearRect(0, 0, width, height);
// ThreadController object update
m.upd();
// increment for the next loop
t0 = t1;
// next frame
requestAnimFrame(render);
};
/**
* ------------------------------------------------
* Begin dots' warmup before the song begins.
* ------------------------------------------------
*/
var begin = function() {
rsize();
m.begin();
// Set up an event listener for new touches.
canvasElement.addEventListener('touchstart', function(e) {
e.preventDefault();
touchStarted(event);
});
// Set up an event listener for when a touch ends.
canvasElement.addEventListener('touchend', function(e) {
e.preventDefault();
touchEnded(e);
});
// Set up an event listener for when a touch leaves the canvas.
canvasElement.addEventListener('touchleave', function(e) {
e.preventDefault();
touchEnded(e);
});
// Set up an event listener for when the touch instrument is moved.
canvasElement.addEventListener('touchmove', function(e) {
e.preventDefault();
touchMoved(e);
});
// Set up an event listener to catch cancelled touches.
canvasElement.addEventListener('touchcancel', function(e) {
e.preventDefault();
touchCancelled(e);
});
// Mouse events
canvasElement.addEventListener('mousedown', function(e) {
e.preventDefault();
mouseDown(e);
});
// Mouse events
canvasElement.addEventListener('mousemove', function(e) {
e.preventDefault();
mouseMove(e);
});
// Mouse events
canvasElement.addEventListener('mouseup', function(e) {
e.preventDefault();
mouseUp(e);
});
// start the drawing loop.
requestAnimFrame(render);
};
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60); // it's not using this, it's just the fallback.
};
})();
var finishedFile = function(bufferPm) {
bufferLoader.finishedFile(bufferPm);
};
// ------------------------------------------------------
// Universal functions.
// ------------------------------------------------------
// convert color - rgba format
function getColor(color) {
var r = Math.round(color[0]);
var g = Math.round(color[1]);
var b = Math.round(color[2]);
var a = (color[3]);
return 'rgba('+r+','+g+','+b+','+a+')';
}
// convert color - rgba format, but ignore alpha, set to custom alpha
function getColorMinusAlpha(color, alp) {
var r = Math.round(color[0]);
var g = Math.round(color[1]);
var b = Math.round(color[2]);
var a = alp;
return 'rgba('+r+','+g+','+b+','+a+')';
}
// linear extrapolate
function lerp(a, b, t) {
return a + (b-a)*t;
}
function lerpColor(a, b, t) {
var c1 = lerp(a[0], b[0], t);
var c2 = lerp(a[1], b[1], t);
var c3 = lerp(a[2], b[2], t);
var c4 = lerp(a[3], b[3], t);
return [c1, c2, c3, c4];
}
// limit to range
function lim(n, n0, n1) {
if (n < n0) { return n0; } else if (n >= n1) { return n1; } else { return n; }
}
// normalize
var norm = function(a,a0,a1) {
return (a-a0)/(a1-a0);
}
// return the sign of a number. -1 if negative, 1 if it's zero or positive.
function sign(n) {
if (n < 0) return -1;
else return 1;
}
// function: lim
// desc: Returns intersection of segement AB and segment EF as Point
// Returns null if there is no intersection
// params: Takes four Points, returns a Point object
//---------------------------------------------------------------
var lineIntersect = function(A,B,E,F) {
var ip, a1, a2, b1, b2, c1, c2;
// calculate
a1 = B.y-A.y; a2 = F.y-E.y;
b1 = A.x-B.x; b2 = E.x-F.x;
c1 = B.x*A.y - A.x*B.y; c2 = F.x*E.y - E.x*F.y;
// det
var det=a1*b2 - a2*b1;
// if lines are parallel
if (det == 0) { return null; }
// find point of intersection
var xip = (b1*c2 - b2*c1)/det;
var yip = (a2*c1 - a1*c2)/det;
// now check if that point is actually on both line segments using distance
if (Math.pow(xip - B.x, 2) + Math.pow(yip - B.y, 2) > Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2)) { return null; }
if (Math.pow(xip - A.x, 2) + Math.pow(yip - A.y, 2) > Math.pow(A.x - B.x, 2) + Math.pow(A.y - B.y, 2)) { return null; }
if (Math.pow(xip - F.x, 2) + Math.pow(yip - F.y, 2) > Math.pow(E.x - F.x, 2) + Math.pow(E.y - F.y, 2)) { return null; }
if (Math.pow(xip - E.x, 2) + Math.pow(yip - E.y, 2) > Math.pow(E.x - F.x, 2) + Math.pow(E.y - F.y, 2)) { return null; }
// else it's on both segments, return it
return new Point(xip, yip);
}
// ------------------------------------------------
// class: Point
// description:
// ------------------------------------------------
var Point = function(px,py) {
this.x = px; this.y = py;
}
// When window is resized
function rsize(e) {
var lastWidth = width;
var lastHeight = height;
width = window.innerWidth;
height = window.innerHeight;
// Aspect ratio of the window - e.g. 1.0 = square, 2.0 = 2:1 horizontal, 0.5 = 1:2 vertical.
aspectRatio = width/height;
// set margins based on that
leftMargin = rightMargin = height * 0.07;
topMargin = bottomMargin = height * 0.07;
// did it not change?
var isSameSize = (lastWidth == width) && (lastHeight == height);
// center point
xCenter = Math.round(width * 0.5);
yCenter = Math.round(height / 2);
// make the canvas objects match window size
if ((canvasElement != null) && (!isSameSize || needToInitializeCanvas)) {
if (needToInitializeCanvas) needToInitializeCanvas = false;
canvasElement.width = window.innerWidth;
canvasElement.height = window.innerHeight;
// set line style (for some reason it needed to be done here...)
ctx.lineCap = 'round';
}
// Move the start button to upper right
startButtonElement.style.left = (width - 40) + "px";
startButtonElement.style.top = "10px";
m.updateSizeAndPosition();
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
window.addEventListener('resize', rsize, false);
// this function resumes the audio context in case it's in a suspended state
function startAudio(){
if (audioContext.state !== 'running'){
audioContext.resume()
}
}
// this checks if the context is already running and removes the button if it is
var interval = setInterval(function(){
if (audioContext.state === 'running'){
clearInterval(interval);
document.querySelector('#startbutton').remove()
}
}, 100);