babylon.ray.ts 18 KB

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