switch cartesian/spherical function names and make them use length. still a tweak...
[ardour2.git] / libs / pbd / cartesian.cc
blobd15f9a3c27365023f16d2cac36b9d59aa7c0da8d
1 /*
2 Copyright (C) 2010 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 #include <iostream>
20 #include <math.h>
22 #include "pbd/cartesian.h"
24 using namespace std;
26 void
27 PBD::spherical_to_cartesian (double azi, double ele, double len, double& x, double& y, double& z)
29 /* convert from cylindrical coordinates in degrees to cartesian */
31 static const double atorad = 2.0 * M_PI / 360.0 ;
33 if (len == 0.0) {
34 len = 1.0;
37 x = len * cos (azi * atorad) * cos (ele * atorad);
38 y = len * sin (azi * atorad) * cos (ele * atorad);
39 z = len * sin (ele * atorad);
42 void
43 PBD::cartesian_to_spherical (double x, double y, double z, double& azimuth, double& elevation, double& length)
45 #if 1
46 /* converts cartesian coordinates to cylindrical in degrees*/
48 double rho, theta, phi;
50 rho = sqrt (x*x + y*y + z*z);
51 phi = acos (1.0/rho);
52 theta = atan2 (y, x);
54 /* XXX for now, clamp phi to zero */
56 phi = 0.0;
58 if (theta < 0.0) {
59 azimuth = 180.0 - (180.0 * (theta / M_PI)); /* LHS is negative */
60 } else {
61 azimuth = 180.0 * (theta / M_PI);
64 if (phi < 0.0) {
65 elevation = 180.0 - (180.0 * (phi / M_PI)); /* LHS is negative */
66 } else {
67 elevation = 180.0 * (phi / M_PI);
70 length = rho;
71 #else
72 /* converts cartesian coordinates to cylindrical in degrees*/
74 const double atorad = 2.0 * M_PI / 360.0;
75 double atan_y_per_x, atan_x_pl_y_per_z;
76 double distance;
78 if (x == 0.0) {
79 atan_y_per_x = M_PI / 2;
80 } else {
81 atan_y_per_x = atan2 (y,x);
84 if (y < 0.0) {
85 /* below x-axis: atan2 returns 0 .. -PI (negative) so convert to degrees and ADD to 180 */
86 azimuth = 180.0 + (atan_y_per_x / (M_PI/180.0) + 180.0);
87 } else {
88 /* above x-axis: atan2 returns 0 .. +PI so convert to degrees */
89 azimuth = atan_y_per_x / atorad;
92 distance = sqrt (x*x + y*y);
94 if (z == 0.0) {
95 atan_x_pl_y_per_z = 0.0;
96 } else {
97 atan_x_pl_y_per_z = atan2 (z,distance);
100 if (distance == 0.0) {
101 if (z < 0.0) {
102 atan_x_pl_y_per_z = -M_PI/2.0;
103 } else if (z > 0.0) {
104 atan_x_pl_y_per_z = M_PI/2.0;
108 elevation = atan_x_pl_y_per_z / atorad;
110 // distance = sqrtf (x*x + y*y + z*z);
111 #endif