Skip to content

Instantly share code, notes, and snippets.

@ex
Created September 21, 2013 22:10
Show Gist options
  • Save ex/6654702 to your computer and use it in GitHub Desktop.
Save ex/6654702 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cmath>
#define GET_VECTOR(x) { cout << "Insert vector [" << #x << "] "; cin >> x; }
class Vector {
public:
double x;
double y;
double z;
Vector(double ax = 0, double ay = 0, double az = 0):x(ax),y(ay),z(az) { };
friend std::istream& operator >> (std::istream &is, Vector &a) {
is >> a.x >> a.y >> a.z;
return is;
}
friend std::ostream& operator << (std::ostream &os, const Vector &a) {
os << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return os;
}
// Addition: return = this - B
Vector operator - (const Vector &b) {
return Vector(this->x - b.x, this->y - b.y, this->z - b.z);
}
// Addition: return = this + B
Vector operator + (const Vector &b) {
return Vector(this->x + b.x, this->y + b.y, this->z + b.z);
}
// Cross product: return = this X B
Vector operator ^ (const Vector &b) {
return Vector(this->y*b.z - this->z*b.y,
this->z*b.x - this->x*b.z,
this->x*b.y - this->y*b.x);
}
// Dot product: return = this * B
double operator * (const Vector &b) {
return (this->x*b.x + this->y*b.y + this->z*b.z);
}
// Scalar product: return = this * f
Vector operator * (const double &f) {
return Vector(f*this->x, f*this->y, f*this->z);
}
// Scalar product: return = f * this
friend Vector operator * (const double &f, Vector a) {
return Vector(f*a.x, f*a.y, f*a.z);
}
// Convert the vector to an unary vector.
void normalize() {
double rt = x*x + y*y + z*z;
if (rt > 0) {
rt = sqrt(rt);
x /= rt; y /= rt; z /= rt;
}
}
};
using namespace std;
int main() {
Vector p1, p2, p3, p, v;
GET_VECTOR(p1);
GET_VECTOR(p2);
GET_VECTOR(p3);
GET_VECTOR(p);
GET_VECTOR(v);
v.normalize();
Vector p21 = p2 - p1;
Vector p31 = p3 - p1;
Vector normal = p21 ^ p31; // normal plane: N = (P2 - P1) X (P3 - P1)
normal.normalize();
double v_n = v * normal; // V * N
if (abs(v_n) > 0) { // check if solution exists: N * V != 0
double t = ((p1 - p) * normal)/v_n;
if (t < 0) {
cout << "No shadow" << endl;
}
else {
cout << "S: " << (p + t * v) << endl;
}
}
else {
cout << "Plane parallel to V or no plane" << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment