Last active
January 18, 2019 08:26
-
-
Save hiroyuki/3781210 to your computer and use it in GitHub Desktop.
cartesian<>Polar
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
/** | |
* converts cartesion to polar coordinates | |
* result: | |
* [0] = length | |
* [1] = angle z-axis rotation [-PI, PI](range) Z軸回転 | |
* [2] = angle of projection into x,y, plane with x-axis [-PI, PI](range) | |
*/ | |
static ofVec3f cartesianToPolar(const ofVec3f &v) | |
{ | |
ofVec3f polar; | |
polar[0] = v.length(); | |
if (v[2] > 0.0f) { | |
polar[1] = (float)atan(sqrt(v[0] * v[0] + v[1] * v[1]) / v[2]); | |
} | |
else if (v[2] < 0.0f) { | |
polar[1] = (float)atan(sqrt(v[0] * v[0] + v[1] * v[1]) / v[2]) + PI; | |
} | |
else { | |
polar[1] = PI * 0.5; | |
} | |
polar[1] -= PI*0.5; | |
if (v[0] > 0.0f) { | |
polar[2] = (float)atan(v[1] / v[0]); | |
} | |
else if (v[0] < 0.0f) { | |
polar[2] = atan(v[1] / v[0]); | |
if (v[0] < 0 && v[1] < 0) | |
{ | |
polar[2] -= PI; | |
} | |
if (v[1] / v[0] <= 0) | |
polar[2] += PI; | |
} | |
else if (v[1] > 0) { | |
polar[2] = PI * 0.5f; | |
} | |
else { | |
polar[2] = -PI * 0.5; | |
} | |
return polar; | |
} | |
//GLSL | |
/** | |
* converts cartesion to polar coordinates | |
* result: | |
* [0] = length | |
* [1] = angle with z-axis[-PI, PI] | |
* [2] = angle of projection into x,y, plane with x-axis[-PI, PI] | |
*/ | |
vec3 cartesianToPolar (vec3 v) | |
{ | |
vec3 polar; | |
float M_PI = 3.14159265358979323846; | |
float HALF_PI = M_PI/2.0; | |
polar[0] = length(v); | |
if (v[2] > 0.0f) { | |
polar[1] = atan(sqrt (v[0]*v[0]+ v[1]*v[1])/v[2]); | |
} | |
else if (v[2] < 0.0f) { | |
polar[1] = atan(sqrt(v[0]*v[0]+ v[1]*v[1])/v[2]) + M_PI; | |
} | |
else { | |
polar[1] = M_PI * 0.5f; | |
} | |
polar[ 1 ] -= HALF_PI; | |
if (v[0] != 0.0f) { | |
polar[2] = clamp(atan (v[1], v[0]), -M_PI, M_PI); | |
} | |
else if (v[1] > 0) { | |
polar[2] = M_PI * 0.5f; | |
} | |
else { | |
polar[2] = -M_PI * 0.5; | |
} | |
return polar; | |
} | |
/** | |
* converts polar to cartesion coordinates | |
* input: | |
* [0] = length | |
* [1] = angle with z-axis | |
* [2] = angle of projection into (x,y)-plane | |
*/ | |
static ofVec3f polarToCartesian (const ofVec3f &v) | |
{ | |
ofVec3f cart; | |
cart[0] = v[0] * (float) sin (v[1]) * | |
(float) cos (v[2]); | |
cart[1] = v[0] * (float) sin (v[1]) * | |
(float) sin (v[2]); | |
cart[2] = v[0] * (float) cos (v[1]); | |
return cart; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment