Skip to content

Instantly share code, notes, and snippets.

@doxas
Last active September 12, 2017 14:47
Show Gist options
  • Save doxas/e0a797c38a4b1d93b6686639c024a0f3 to your computer and use it in GitHub Desktop.
Save doxas/e0a797c38a4b1d93b6686639c024a0f3 to your computer and use it in GitHub Desktop.
quaternion to matrix
/**
* @class InteractionCamera
* @example
* let camera = new InteractionCamera();
* window.addEventListener('mousedown', camera.startEvent, false);
* window.addEventListener('mousemove', camera.moveEvent, false);
* window.addEventListener('mouseup', camera.endEvent, false);
* camera.update();
* mMatrix = gl3.Math.Qtn.toMat4(camera.qtn, mMatrix);
*/
class InteractionCamera {
/**
* @constructor
*/
constructor(){
this.qtn = qtn.identity(qtn.create());
this.dragging = false;
this.prevMouse = [0, 0];
this.rotationScale = Math.min(window.innerWidth, window.innerHeight);
this.rotation = 0.0;
this.rotateAxis = [0.0, 0.0, 0.0];
this.rotatePower = 1.5;
this.rotateAttenuation = 0.9;
this.scale = 1.0;
this.scalePower = 0.0;
this.scaleAttenuation = 0.8;
this.scaleMin = 0.5;
this.scaleMax = 1.5;
this.startEvent = this.startEvent.bind(this);
this.moveEvent = this.moveEvent.bind(this);
this.endEvent = this.endEvent.bind(this);
this.wheelEvent = this.wheelEvent.bind(this);
}
/**
* mouse down event
* @param {Event} eve - event object
*/
startEvent(eve){
this.dragging = true;
this.prevMouse = [eve.pageX, eve.pageY];
}
/**
* mouse move event
* @param {Event} eve - event object
*/
moveEvent(eve){
if(this.dragging !== true){return;}
let x = this.prevMouse[0] - eve.pageX;
let y = this.prevMouse[1] - eve.pageY;
this.rotation = Math.sqrt(x * x + y * y) / this.rotationScale * this.rotatePower;
this.rotateAxis[0] = y;
this.rotateAxis[1] = x;
this.prevMouse = [eve.pageX, eve.pageY];
}
/**
* mouse up event
*/
endEvent(){
this.dragging = false;
}
/**
* wheel event
* @param {Event} eve - event object
*/
wheelEvent(eve){
let w = eve.wheelDelta;
if(w > 0){
this.scalePower = 0.01;
}else if(w < 0){
this.scalePower = -0.01;
}
}
/**
* quaternion update
*/
update(){
this.scalePower *= this.scaleAttenuation;
this.scale = Math.max(this.scaleMin, Math.min(this.scaleMax, this.scale + this.scalePower));
if(this.rotation === 0.0){return;}
this.rotation *= this.rotateAttenuation;
let q = qtn.identity(qtn.create());
q = qtn.rotate(this.rotation, this.rotateAxis);
this.qtn = qtn.multiply(this.qtn, q);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment