Last active
June 4, 2022 18:18
-
-
Save bluelhf/a9ada3552fe0ab6aab6ef3a107c2e3bb to your computer and use it in GitHub Desktop.
JShell script that loads a method for finding intersections between a ray and a sphere given the origin of the sphere, the origin of the ray, the direction vector of the ray, and the radius of the sphere.
This file contains 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
import static java.lang.Math.*; | |
double[][] intersections(double[] p, double[] o, double[] d, double r) { | |
double[] ip = inverse(p); | |
double a = dot(d, d); | |
double b = 2 * dot(o, d) + 2 * dot(ip, d); | |
double c = dot(o, o) + 2 * dot(ip, o) + dot(ip, ip) - pow(r, 2); | |
double dct = pow(b, 2) - 4 * a * c; | |
double[] t = new double[]{ | |
(-b - sqrt(dct)) / (2 * a), | |
(-b + sqrt(dct)) / (2 * a) | |
}; | |
return new double[][]{ | |
add(o, mult(d, t[0])), | |
add(o, mult(d, t[1])) | |
}; | |
} | |
double[] inverse(double[] input) { | |
return mult(input, -1); | |
} | |
double sum(double[] input) { | |
double sum = 0; | |
for (int i = 0; i < input.length; i++) { | |
sum += input[i]; | |
} | |
return sum; | |
} | |
double[] mult(double[] input, double scalar) { | |
double[] clone = new double[input.length]; | |
for (int i = 0; i < input.length; i++) { | |
clone[i] = scalar * input[i]; | |
} | |
return clone; | |
} | |
double[] add(double[] a, double[] b) { | |
double[] result = new double[a.length]; | |
for (int i = 0; i < a.length; i++) { | |
result[i] = a[i] + b[i]; | |
} | |
return result; | |
} | |
double dot(double[] a, double[] b) { | |
assert a.length == b.length: "Dot product inputs must be of equal dimension"; | |
double sum = 0; | |
for (int i = 0; i < a.length; i++) { | |
sum += a[i] * b[i]; | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Java 17 comes with a binary,
jshell
, which can execute this script — simply run the binary with the path to this script as the argument, and it'll load each method and throw you into a read-eval-print loop in which you can runintersections
with your desired inputs.