ray.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. module BABYLON {
  2. /**
  3. * Class representing a ray with position and direction
  4. */
  5. export class Ray {
  6. private static readonly TmpVector3 = Tools.BuildArray(6, Vector3.Zero);
  7. private _tmpRay: Ray;
  8. /**
  9. * Creates a new ray
  10. * @param origin origin point
  11. * @param direction direction
  12. * @param length length of the ray
  13. */
  14. constructor(
  15. /** origin point */
  16. public origin: Vector3,
  17. /** direction */
  18. public direction: Vector3,
  19. /** length of the ray */
  20. public length: number = Number.MAX_VALUE) {
  21. }
  22. // Methods
  23. /**
  24. * Checks if the ray intersects a box
  25. * @param minimum bound of the box
  26. * @param maximum bound of the box
  27. * @param intersectionTreshold extra extend to be added to the box in all direction
  28. * @returns if the box was hit
  29. */
  30. public intersectsBoxMinMax(minimum: Vector3, maximum: Vector3, intersectionTreshold: number = 0): boolean {
  31. const newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  32. const newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  33. var d = 0.0;
  34. var maxValue = Number.MAX_VALUE;
  35. var inv: number;
  36. var min: number;
  37. var max: number;
  38. var temp: number;
  39. if (Math.abs(this.direction.x) < 0.0000001) {
  40. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  41. return false;
  42. }
  43. }
  44. else {
  45. inv = 1.0 / this.direction.x;
  46. min = (newMinimum.x - this.origin.x) * inv;
  47. max = (newMaximum.x - this.origin.x) * inv;
  48. if (max === -Infinity) {
  49. max = Infinity;
  50. }
  51. if (min > max) {
  52. temp = min;
  53. min = max;
  54. max = temp;
  55. }
  56. d = Math.max(min, d);
  57. maxValue = Math.min(max, maxValue);
  58. if (d > maxValue) {
  59. return false;
  60. }
  61. }
  62. if (Math.abs(this.direction.y) < 0.0000001) {
  63. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  64. return false;
  65. }
  66. }
  67. else {
  68. inv = 1.0 / this.direction.y;
  69. min = (newMinimum.y - this.origin.y) * inv;
  70. max = (newMaximum.y - this.origin.y) * inv;
  71. if (max === -Infinity) {
  72. max = Infinity;
  73. }
  74. if (min > max) {
  75. temp = min;
  76. min = max;
  77. max = temp;
  78. }
  79. d = Math.max(min, d);
  80. maxValue = Math.min(max, maxValue);
  81. if (d > maxValue) {
  82. return false;
  83. }
  84. }
  85. if (Math.abs(this.direction.z) < 0.0000001) {
  86. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  87. return false;
  88. }
  89. }
  90. else {
  91. inv = 1.0 / this.direction.z;
  92. min = (newMinimum.z - this.origin.z) * inv;
  93. max = (newMaximum.z - this.origin.z) * inv;
  94. if (max === -Infinity) {
  95. max = Infinity;
  96. }
  97. if (min > max) {
  98. temp = min;
  99. min = max;
  100. max = temp;
  101. }
  102. d = Math.max(min, d);
  103. maxValue = Math.min(max, maxValue);
  104. if (d > maxValue) {
  105. return false;
  106. }
  107. }
  108. return true;
  109. }
  110. /**
  111. * Checks if the ray intersects a box
  112. * @param box the bounding box to check
  113. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  114. * @returns if the box was hit
  115. */
  116. public intersectsBox(box: BoundingBox, intersectionTreshold: number = 0): boolean {
  117. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  118. }
  119. /**
  120. * If the ray hits a sphere
  121. * @param sphere the bounding sphere to check
  122. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  123. * @returns true if it hits the sphere
  124. */
  125. public intersectsSphere(sphere: BoundingSphere, intersectionTreshold: number = 0): boolean {
  126. var x = sphere.center.x - this.origin.x;
  127. var y = sphere.center.y - this.origin.y;
  128. var z = sphere.center.z - this.origin.z;
  129. var pyth = (x * x) + (y * y) + (z * z);
  130. const radius = sphere.radius + intersectionTreshold;
  131. var rr = radius * radius;
  132. if (pyth <= rr) {
  133. return true;
  134. }
  135. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  136. if (dot < 0.0) {
  137. return false;
  138. }
  139. var temp = pyth - (dot * dot);
  140. return temp <= rr;
  141. }
  142. /**
  143. * If the ray hits a triange
  144. * @param vertex0 triangle vertex
  145. * @param vertex1 triangle vertex
  146. * @param vertex2 triangle vertex
  147. * @returns intersection information if hit
  148. */
  149. public intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): Nullable<IntersectionInfo> {
  150. const edge1 = Ray.TmpVector3[0];
  151. const edge2 = Ray.TmpVector3[1];
  152. const pvec = Ray.TmpVector3[2];
  153. const tvec = Ray.TmpVector3[3];
  154. const qvec = Ray.TmpVector3[4];
  155. vertex1.subtractToRef(vertex0, edge1);
  156. vertex2.subtractToRef(vertex0, edge2);
  157. Vector3.CrossToRef(this.direction, edge2, pvec);
  158. var det = Vector3.Dot(edge1, pvec);
  159. if (det === 0) {
  160. return null;
  161. }
  162. var invdet = 1 / det;
  163. this.origin.subtractToRef(vertex0, tvec);
  164. var bu = Vector3.Dot(tvec, pvec) * invdet;
  165. if (bu < 0 || bu > 1.0) {
  166. return null;
  167. }
  168. Vector3.CrossToRef(tvec, edge1, qvec);
  169. var bv = Vector3.Dot(this.direction, qvec) * invdet;
  170. if (bv < 0 || bu + bv > 1.0) {
  171. return null;
  172. }
  173. //check if the distance is longer than the predefined length.
  174. var distance = Vector3.Dot(edge2, qvec) * invdet;
  175. if (distance > this.length) {
  176. return null;
  177. }
  178. return new IntersectionInfo(bu, bv, distance);
  179. }
  180. /**
  181. * Checks if ray intersects a plane
  182. * @param plane the plane to check
  183. * @returns the distance away it was hit
  184. */
  185. public intersectsPlane(plane: Plane): Nullable<number> {
  186. var distance: number;
  187. var result1 = Vector3.Dot(plane.normal, this.direction);
  188. if (Math.abs(result1) < 9.99999997475243E-07) {
  189. return null;
  190. }
  191. else {
  192. var result2 = Vector3.Dot(plane.normal, this.origin);
  193. distance = (-plane.d - result2) / result1;
  194. if (distance < 0.0) {
  195. if (distance < -9.99999997475243E-07) {
  196. return null;
  197. } else {
  198. return 0;
  199. }
  200. }
  201. return distance;
  202. }
  203. }
  204. /**
  205. * Checks if ray intersects a mesh
  206. * @param mesh the mesh to check
  207. * @param fastCheck if only the bounding box should checked
  208. * @returns picking info of the intersecton
  209. */
  210. public intersectsMesh(mesh: AbstractMesh, fastCheck?: boolean): PickingInfo {
  211. var tm = Tmp.Matrix[0];
  212. mesh.getWorldMatrix().invertToRef(tm);
  213. if (this._tmpRay) {
  214. Ray.TransformToRef(this, tm, this._tmpRay);
  215. }else {
  216. this._tmpRay = Ray.Transform(this, tm);
  217. }
  218. return mesh.intersects(this._tmpRay, fastCheck);
  219. }
  220. /**
  221. * Checks if ray intersects a mesh
  222. * @param meshes the meshes to check
  223. * @param fastCheck if only the bounding box should checked
  224. * @param results array to store result in
  225. * @returns Array of picking infos
  226. */
  227. public intersectsMeshes(meshes: Array<AbstractMesh>, fastCheck?: boolean, results?: Array<PickingInfo>): Array<PickingInfo> {
  228. if (results) {
  229. results.length = 0;
  230. }else {
  231. results = [];
  232. }
  233. for (var i = 0; i < meshes.length; i++) {
  234. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  235. if (pickInfo.hit) {
  236. results.push(pickInfo);
  237. }
  238. }
  239. results.sort(this._comparePickingInfo);
  240. return results;
  241. }
  242. private _comparePickingInfo(pickingInfoA: PickingInfo, pickingInfoB: PickingInfo): number {
  243. if (pickingInfoA.distance < pickingInfoB.distance) {
  244. return -1;
  245. }else if (pickingInfoA.distance > pickingInfoB.distance) {
  246. return 1;
  247. }else {
  248. return 0;
  249. }
  250. }
  251. private static smallnum = 0.00000001;
  252. private static rayl = 10e8;
  253. /**
  254. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  255. * @param sega the first point of the segment to test the intersection against
  256. * @param segb the second point of the segment to test the intersection against
  257. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  258. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  259. */
  260. intersectionSegment(sega: Vector3, segb: Vector3, threshold: number): number {
  261. const o = this.origin;
  262. const u = Tmp.Vector3[0];
  263. const rsegb = Tmp.Vector3[1];
  264. const v = Tmp.Vector3[2];
  265. const w = Tmp.Vector3[3];
  266. segb.subtractToRef(sega, u);
  267. this.direction.scaleToRef(Ray.rayl, v);
  268. o.addToRef(v, rsegb);
  269. sega.subtractToRef(o, w);
  270. var a = Vector3.Dot(u, u); // always >= 0
  271. var b = Vector3.Dot(u, v);
  272. var c = Vector3.Dot(v, v); // always >= 0
  273. var d = Vector3.Dot(u, w);
  274. var e = Vector3.Dot(v, w);
  275. var D = a * c - b * b; // always >= 0
  276. var sc: number, sN: number, sD = D; // sc = sN / sD, default sD = D >= 0
  277. var tc: number, tN: number, tD = D; // tc = tN / tD, default tD = D >= 0
  278. // compute the line parameters of the two closest points
  279. if (D < Ray.smallnum) { // the lines are almost parallel
  280. sN = 0.0; // force using point P0 on segment S1
  281. sD = 1.0; // to prevent possible division by 0.0 later
  282. tN = e;
  283. tD = c;
  284. }
  285. else { // get the closest points on the infinite lines
  286. sN = (b * e - c * d);
  287. tN = (a * e - b * d);
  288. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  289. sN = 0.0;
  290. tN = e;
  291. tD = c;
  292. } else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  293. sN = sD;
  294. tN = e + b;
  295. tD = c;
  296. }
  297. }
  298. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  299. tN = 0.0;
  300. // recompute sc for this edge
  301. if (-d < 0.0) {
  302. sN = 0.0;
  303. } else if (-d > a) {
  304. sN = sD;
  305. }
  306. else {
  307. sN = -d;
  308. sD = a;
  309. }
  310. } else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  311. tN = tD;
  312. // recompute sc for this edge
  313. if ((-d + b) < 0.0) {
  314. sN = 0;
  315. } else if ((-d + b) > a) {
  316. sN = sD;
  317. } else {
  318. sN = (-d + b);
  319. sD = a;
  320. }
  321. }
  322. // finally do the division to get sc and tc
  323. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  324. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  325. // get the difference of the two closest points
  326. const qtc = Tmp.Vector3[4];
  327. v.scaleToRef(tc, qtc);
  328. const dP = Tmp.Vector3[5];
  329. u.scaleToRef(sc, dP);
  330. dP.addInPlace(w).subtractInPlace(qtc); // = S1(sc) - S2(tc)
  331. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  332. if (isIntersected) {
  333. return qtc.length();
  334. }
  335. return -1;
  336. }
  337. /**
  338. * Update the ray from viewport position
  339. * @param x position
  340. * @param y y position
  341. * @param viewportWidth viewport width
  342. * @param viewportHeight viewport height
  343. * @param world world matrix
  344. * @param view view matrix
  345. * @param projection projection matrix
  346. * @returns this ray updated
  347. */
  348. public update(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Readonly<Matrix>, view: Readonly<Matrix>, projection: Readonly<Matrix>): Ray {
  349. Vector3.UnprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection, this);
  350. return this;
  351. }
  352. // Statics
  353. /**
  354. * Creates a ray with origin and direction of 0,0,0
  355. * @returns the new ray
  356. */
  357. public static Zero(): Ray {
  358. return new Ray(Vector3.Zero(), Vector3.Zero());
  359. }
  360. /**
  361. * Creates a new ray from screen space and viewport
  362. * @param x position
  363. * @param y y position
  364. * @param viewportWidth viewport width
  365. * @param viewportHeight viewport height
  366. * @param world world matrix
  367. * @param view view matrix
  368. * @param projection projection matrix
  369. * @returns new ray
  370. */
  371. public static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Ray {
  372. let result = Ray.Zero();
  373. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  374. }
  375. /**
  376. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  377. * transformed to the given world matrix.
  378. * @param origin The origin point
  379. * @param end The end point
  380. * @param world a matrix to transform the ray to. Default is the identity matrix.
  381. * @returns the new ray
  382. */
  383. public static CreateNewFromTo(origin: Vector3, end: Vector3, world: Readonly<Matrix> = Matrix.IdentityReadOnly): Ray {
  384. var direction = end.subtract(origin);
  385. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  386. direction.normalize();
  387. return Ray.Transform(new Ray(origin, direction, length), world);
  388. }
  389. /**
  390. * Transforms a ray by a matrix
  391. * @param ray ray to transform
  392. * @param matrix matrix to apply
  393. * @returns the resulting new ray
  394. */
  395. public static Transform(ray: Ray, matrix: Readonly<Matrix>): Ray {
  396. var result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
  397. Ray.TransformToRef(ray, matrix, result);
  398. return result;
  399. }
  400. /**
  401. * Transforms a ray by a matrix
  402. * @param ray ray to transform
  403. * @param matrix matrix to apply
  404. * @param result ray to store result in
  405. */
  406. public static TransformToRef(ray: Ray, matrix: Readonly<Matrix>, result: Ray): void {
  407. Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  408. Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  409. result.length = ray.length;
  410. var dir = result.direction;
  411. var len = dir.length();
  412. if (!(len === 0 || len === 1)) {
  413. var num = 1.0 / len;
  414. dir.x *= num;
  415. dir.y *= num;
  416. dir.z *= num;
  417. result.length *= len;
  418. }
  419. }
  420. }
  421. }