Created
June 22, 2019 07:37
-
-
Save josherich/b0e324bb03a128fac1f9d61936c465f1 to your computer and use it in GitHub Desktop.
geometry in 3d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
v3 = new function() { | |
this.forward = [0,0,1] | |
this.up = [0,1,0] | |
this.right = [1,0,0] | |
this.zero = [0,0,0] | |
} | |
// rotate vector | |
rotvec = function(vec,axis,th){ | |
var [l,m,n] = axis | |
var [x,y,z] = vec | |
var [costh,sinth] = [Math.cos(th), Math.sin(th)] | |
var mat={} | |
mat[11]= l*l *(1-costh) +costh | |
mat[12]= m*l *(1-costh) -n*sinth | |
mat[13]= n*l *(1-costh) +m*sinth | |
mat[21]= l*m *(1-costh) +n*sinth | |
mat[22]= m*m *(1-costh) +costh | |
mat[23]= n*m *(1-costh) -l*sinth | |
mat[31]= l*n *(1-costh) -m*sinth | |
mat[32]= m*n *(1-costh) +l*sinth | |
mat[33]= n*n *(1-costh) +costh | |
return [ | |
x*mat[11] + y*mat[12] + z*mat[13], | |
x*mat[21] + y*mat[22] + z*mat[23], | |
x*mat[31] + y*mat[32] + z*mat[33], | |
] | |
} | |
roteuler = function(vec,rot){ | |
if (rot.z != 0) {vec = v3.rotvec(vec,v3.forward,rot.z)} | |
if (rot.x != 0) {vec = v3.rotvec(vec,v3.right,rot.x)} | |
if (rot.y != 0) {vec = v3.rotvec(vec,v3.up,rot.y)} | |
return vec | |
} | |
scale = function(vec,p){ | |
return [vec.x*p,vec.y*p,vec.z*p] | |
} | |
copy = function(v0){ | |
return [v0.x,v0.y,v0.z] | |
} | |
add = function(v0,v){ | |
return [v0.x+v.x,v0.y+v.y,v0.z+v.z] | |
} | |
subtract = function(v0,v){ | |
return [v0.x-v.x,v0.y-v.y,v0.z-v.z] | |
} | |
// magnitude | |
mag = function(v){ | |
return Math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z) | |
} | |
normalize = function(v){ | |
p = 1/mag(v) | |
return [v.x*p,v.y*p,v.z*p] | |
} | |
dot = function(u,v){ | |
return u.x*v.x + u.y*v.y + u.z*v.z | |
} | |
cross = function(u,v){ | |
return [ | |
u.y*v.z - u.z*v.y, | |
u.z*v.x - u.x*v.z, | |
u.x*v.y - u.y*v.x | |
] | |
} | |
angcos = function(u,v){ | |
return v3.dot(u,v)/(v3.mag(u)*v3.mag(v)) | |
} | |
ang = function(u,v){ | |
return Math.acos(v3.angcos(u,v)) | |
} | |
toeuler = function(v0){ | |
var ep = 5 | |
var ma = 2*PI | |
var mr = [0,0,0] | |
var cnt = 0 | |
for (var x = -180; x < 180; x+=ep){ | |
for (var y = -90; y < 90; y+=ep){ | |
cnt ++; | |
var r = [rad(x),rad(y),0] | |
var v = v3.roteuler([0,0,1],r) | |
var a = v3.ang(v0,v) | |
if (a < rad(ep)){ | |
return r | |
} | |
if (a < ma){ | |
ma = a | |
mr = r | |
} | |
} | |
} | |
return mr | |
} | |
lerp = function(u,v,p){ | |
return [ | |
u.x*(1-p)+v.x*p, | |
u.y*(1-p)+v.y*p, | |
u.z*(1-p)+v.z*p, | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment