Source: Core/IntersectionTests.js

  1. /*global define*/
  2. define([
  3. './Cartesian3',
  4. './Cartographic',
  5. './defaultValue',
  6. './defined',
  7. './DeveloperError',
  8. './Math',
  9. './Matrix3',
  10. './QuadraticRealPolynomial',
  11. './QuarticRealPolynomial',
  12. './Ray'
  13. ], function(
  14. Cartesian3,
  15. Cartographic,
  16. defaultValue,
  17. defined,
  18. DeveloperError,
  19. CesiumMath,
  20. Matrix3,
  21. QuadraticRealPolynomial,
  22. QuarticRealPolynomial,
  23. Ray) {
  24. 'use strict';
  25. /**
  26. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  27. *
  28. * @exports IntersectionTests
  29. */
  30. var IntersectionTests = {};
  31. /**
  32. * Computes the intersection of a ray and a plane.
  33. *
  34. * @param {Ray} ray The ray.
  35. * @param {Plane} plane The plane.
  36. * @param {Cartesian3} [result] The object onto which to store the result.
  37. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  38. */
  39. IntersectionTests.rayPlane = function(ray, plane, result) {
  40. //>>includeStart('debug', pragmas.debug);
  41. if (!defined(ray)) {
  42. throw new DeveloperError('ray is required.');
  43. }
  44. if (!defined(plane)) {
  45. throw new DeveloperError('plane is required.');
  46. }
  47. //>>includeEnd('debug');
  48. if (!defined(result)) {
  49. result = new Cartesian3();
  50. }
  51. var origin = ray.origin;
  52. var direction = ray.direction;
  53. var normal = plane.normal;
  54. var denominator = Cartesian3.dot(normal, direction);
  55. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  56. // Ray is parallel to plane. The ray may be in the polygon's plane.
  57. return undefined;
  58. }
  59. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  60. if (t < 0) {
  61. return undefined;
  62. }
  63. result = Cartesian3.multiplyByScalar(direction, t, result);
  64. return Cartesian3.add(origin, result, result);
  65. };
  66. var scratchEdge0 = new Cartesian3();
  67. var scratchEdge1 = new Cartesian3();
  68. var scratchPVec = new Cartesian3();
  69. var scratchTVec = new Cartesian3();
  70. var scratchQVec = new Cartesian3();
  71. /**
  72. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  73. * @memberof IntersectionTests
  74. *
  75. * @param {Ray} ray The ray.
  76. * @param {Cartesian3} p0 The first vertex of the triangle.
  77. * @param {Cartesian3} p1 The second vertex of the triangle.
  78. * @param {Cartesian3} p2 The third vertex of the triangle.
  79. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  80. * and return undefined for intersections with the back face.
  81. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  82. */
  83. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  84. //>>includeStart('debug', pragmas.debug);
  85. if (!defined(ray)) {
  86. throw new DeveloperError('ray is required.');
  87. }
  88. if (!defined(p0)) {
  89. throw new DeveloperError('p0 is required.');
  90. }
  91. if (!defined(p1)) {
  92. throw new DeveloperError('p1 is required.');
  93. }
  94. if (!defined(p2)) {
  95. throw new DeveloperError('p2 is required.');
  96. }
  97. //>>includeEnd('debug');
  98. cullBackFaces = defaultValue(cullBackFaces, false);
  99. var origin = ray.origin;
  100. var direction = ray.direction;
  101. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  102. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  103. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  104. var det = Cartesian3.dot(edge0, p);
  105. var tvec;
  106. var q;
  107. var u;
  108. var v;
  109. var t;
  110. if (cullBackFaces) {
  111. if (det < CesiumMath.EPSILON6) {
  112. return undefined;
  113. }
  114. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  115. u = Cartesian3.dot(tvec, p);
  116. if (u < 0.0 || u > det) {
  117. return undefined;
  118. }
  119. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  120. v = Cartesian3.dot(direction, q);
  121. if (v < 0.0 || u + v > det) {
  122. return undefined;
  123. }
  124. t = Cartesian3.dot(edge1, q) / det;
  125. } else {
  126. if (Math.abs(det) < CesiumMath.EPSILON6) {
  127. return undefined;
  128. }
  129. var invDet = 1.0 / det;
  130. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  131. u = Cartesian3.dot(tvec, p) * invDet;
  132. if (u < 0.0 || u > 1.0) {
  133. return undefined;
  134. }
  135. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  136. v = Cartesian3.dot(direction, q) * invDet;
  137. if (v < 0.0 || u + v > 1.0) {
  138. return undefined;
  139. }
  140. t = Cartesian3.dot(edge1, q) * invDet;
  141. }
  142. return t;
  143. };
  144. /**
  145. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  146. * @memberof IntersectionTests
  147. *
  148. * @param {Ray} ray The ray.
  149. * @param {Cartesian3} p0 The first vertex of the triangle.
  150. * @param {Cartesian3} p1 The second vertex of the triangle.
  151. * @param {Cartesian3} p2 The third vertex of the triangle.
  152. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  153. * and return undefined for intersections with the back face.
  154. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  155. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  156. */
  157. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  158. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  159. if (!defined(t) || t < 0.0) {
  160. return undefined;
  161. }
  162. if (!defined(result)) {
  163. result = new Cartesian3();
  164. }
  165. Cartesian3.multiplyByScalar(ray.direction, t, result);
  166. return Cartesian3.add(ray.origin, result, result);
  167. };
  168. var scratchLineSegmentTriangleRay = new Ray();
  169. /**
  170. * Computes the intersection of a line segment and a triangle.
  171. * @memberof IntersectionTests
  172. *
  173. * @param {Cartesian3} v0 The an end point of the line segment.
  174. * @param {Cartesian3} v1 The other end point of the line segment.
  175. * @param {Cartesian3} p0 The first vertex of the triangle.
  176. * @param {Cartesian3} p1 The second vertex of the triangle.
  177. * @param {Cartesian3} p2 The third vertex of the triangle.
  178. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  179. * and return undefined for intersections with the back face.
  180. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  181. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  182. */
  183. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  184. //>>includeStart('debug', pragmas.debug);
  185. if (!defined(v0)) {
  186. throw new DeveloperError('v0 is required.');
  187. }
  188. if (!defined(v1)) {
  189. throw new DeveloperError('v1 is required.');
  190. }
  191. if (!defined(p0)) {
  192. throw new DeveloperError('p0 is required.');
  193. }
  194. if (!defined(p1)) {
  195. throw new DeveloperError('p1 is required.');
  196. }
  197. if (!defined(p2)) {
  198. throw new DeveloperError('p2 is required.');
  199. }
  200. //>>includeEnd('debug');
  201. var ray = scratchLineSegmentTriangleRay;
  202. Cartesian3.clone(v0, ray.origin);
  203. Cartesian3.subtract(v1, v0, ray.direction);
  204. Cartesian3.normalize(ray.direction, ray.direction);
  205. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  206. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  207. return undefined;
  208. }
  209. if (!defined(result)) {
  210. result = new Cartesian3();
  211. }
  212. Cartesian3.multiplyByScalar(ray.direction, t, result);
  213. return Cartesian3.add(ray.origin, result, result);
  214. };
  215. function solveQuadratic(a, b, c, result) {
  216. var det = b * b - 4.0 * a * c;
  217. if (det < 0.0) {
  218. return undefined;
  219. } else if (det > 0.0) {
  220. var denom = 1.0 / (2.0 * a);
  221. var disc = Math.sqrt(det);
  222. var root0 = (-b + disc) * denom;
  223. var root1 = (-b - disc) * denom;
  224. if (root0 < root1) {
  225. result.root0 = root0;
  226. result.root1 = root1;
  227. } else {
  228. result.root0 = root1;
  229. result.root1 = root0;
  230. }
  231. return result;
  232. }
  233. var root = -b / (2.0 * a);
  234. if (root === 0.0) {
  235. return undefined;
  236. }
  237. result.root0 = result.root1 = root;
  238. return result;
  239. }
  240. var raySphereRoots = {
  241. root0 : 0.0,
  242. root1 : 0.0
  243. };
  244. function raySphere(ray, sphere, result) {
  245. if (!defined(result)) {
  246. result = {};
  247. }
  248. var origin = ray.origin;
  249. var direction = ray.direction;
  250. var center = sphere.center;
  251. var radiusSquared = sphere.radius * sphere.radius;
  252. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  253. var a = Cartesian3.dot(direction, direction);
  254. var b = 2.0 * Cartesian3.dot(direction, diff);
  255. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  256. var roots = solveQuadratic(a, b, c, raySphereRoots);
  257. if (!defined(roots)) {
  258. return undefined;
  259. }
  260. result.start = roots.root0;
  261. result.stop = roots.root1;
  262. return result;
  263. }
  264. /**
  265. * Computes the intersection points of a ray with a sphere.
  266. * @memberof IntersectionTests
  267. *
  268. * @param {Ray} ray The ray.
  269. * @param {BoundingSphere} sphere The sphere.
  270. * @param {Object} [result] The result onto which to store the result.
  271. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the ray or undefined if there are no intersections.
  272. */
  273. IntersectionTests.raySphere = function(ray, sphere, result) {
  274. //>>includeStart('debug', pragmas.debug);
  275. if (!defined(ray)) {
  276. throw new DeveloperError('ray is required.');
  277. }
  278. if (!defined(sphere)) {
  279. throw new DeveloperError('sphere is required.');
  280. }
  281. //>>includeEnd('debug');
  282. result = raySphere(ray, sphere, result);
  283. if (!defined(result) || result.stop < 0.0) {
  284. return undefined;
  285. }
  286. result.start = Math.max(result.start, 0.0);
  287. return result;
  288. };
  289. var scratchLineSegmentRay = new Ray();
  290. /**
  291. * Computes the intersection points of a line segment with a sphere.
  292. * @memberof IntersectionTests
  293. *
  294. * @param {Cartesian3} p0 An end point of the line segment.
  295. * @param {Cartesian3} p1 The other end point of the line segment.
  296. * @param {BoundingSphere} sphere The sphere.
  297. * @param {Object} [result] The result onto which to store the result.
  298. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the line segment or undefined if there are no intersections.
  299. */
  300. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  301. //>>includeStart('debug', pragmas.debug);
  302. if (!defined(p0)) {
  303. throw new DeveloperError('p0 is required.');
  304. }
  305. if (!defined(p1)) {
  306. throw new DeveloperError('p1 is required.');
  307. }
  308. if (!defined(sphere)) {
  309. throw new DeveloperError('sphere is required.');
  310. }
  311. //>>includeEnd('debug');
  312. var ray = scratchLineSegmentRay;
  313. Cartesian3.clone(p0, ray.origin);
  314. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  315. var maxT = Cartesian3.magnitude(direction);
  316. Cartesian3.normalize(direction, direction);
  317. result = raySphere(ray, sphere, result);
  318. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  319. return undefined;
  320. }
  321. result.start = Math.max(result.start, 0.0);
  322. result.stop = Math.min(result.stop, maxT);
  323. return result;
  324. };
  325. var scratchQ = new Cartesian3();
  326. var scratchW = new Cartesian3();
  327. /**
  328. * Computes the intersection points of a ray with an ellipsoid.
  329. *
  330. * @param {Ray} ray The ray.
  331. * @param {Ellipsoid} ellipsoid The ellipsoid.
  332. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the ray or undefined if there are no intersections.
  333. */
  334. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  335. //>>includeStart('debug', pragmas.debug);
  336. if (!defined(ray)) {
  337. throw new DeveloperError('ray is required.');
  338. }
  339. if (!defined(ellipsoid)) {
  340. throw new DeveloperError('ellipsoid is required.');
  341. }
  342. //>>includeEnd('debug');
  343. var inverseRadii = ellipsoid.oneOverRadii;
  344. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  345. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  346. var q2 = Cartesian3.magnitudeSquared(q);
  347. var qw = Cartesian3.dot(q, w);
  348. var difference, w2, product, discriminant, temp;
  349. if (q2 > 1.0) {
  350. // Outside ellipsoid.
  351. if (qw >= 0.0) {
  352. // Looking outward or tangent (0 intersections).
  353. return undefined;
  354. }
  355. // qw < 0.0.
  356. var qw2 = qw * qw;
  357. difference = q2 - 1.0; // Positively valued.
  358. w2 = Cartesian3.magnitudeSquared(w);
  359. product = w2 * difference;
  360. if (qw2 < product) {
  361. // Imaginary roots (0 intersections).
  362. return undefined;
  363. } else if (qw2 > product) {
  364. // Distinct roots (2 intersections).
  365. discriminant = qw * qw - product;
  366. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  367. var root0 = temp / w2;
  368. var root1 = difference / temp;
  369. if (root0 < root1) {
  370. return {
  371. start : root0,
  372. stop : root1
  373. };
  374. }
  375. return {
  376. start : root1,
  377. stop : root0
  378. };
  379. } else {
  380. // qw2 == product. Repeated roots (2 intersections).
  381. var root = Math.sqrt(difference / w2);
  382. return {
  383. start : root,
  384. stop : root
  385. };
  386. }
  387. } else if (q2 < 1.0) {
  388. // Inside ellipsoid (2 intersections).
  389. difference = q2 - 1.0; // Negatively valued.
  390. w2 = Cartesian3.magnitudeSquared(w);
  391. product = w2 * difference; // Negatively valued.
  392. discriminant = qw * qw - product;
  393. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  394. return {
  395. start : 0.0,
  396. stop : temp / w2
  397. };
  398. } else {
  399. // q2 == 1.0. On ellipsoid.
  400. if (qw < 0.0) {
  401. // Looking inward.
  402. w2 = Cartesian3.magnitudeSquared(w);
  403. return {
  404. start : 0.0,
  405. stop : -qw / w2
  406. };
  407. }
  408. // qw >= 0.0. Looking outward or tangent.
  409. return undefined;
  410. }
  411. };
  412. function addWithCancellationCheck(left, right, tolerance) {
  413. var difference = left + right;
  414. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  415. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  416. return 0.0;
  417. }
  418. return difference;
  419. }
  420. function quadraticVectorExpression(A, b, c, x, w) {
  421. var xSquared = x * x;
  422. var wSquared = w * w;
  423. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  424. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  425. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  426. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  427. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  428. var cosines;
  429. var solutions = [];
  430. if (r0 === 0.0 && r1 === 0.0) {
  431. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  432. if (cosines.length === 0) {
  433. return solutions;
  434. }
  435. var cosine0 = cosines[0];
  436. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  437. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  438. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  439. if (cosines.length === 2) {
  440. var cosine1 = cosines[1];
  441. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  442. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  443. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  444. }
  445. return solutions;
  446. }
  447. var r0Squared = r0 * r0;
  448. var r1Squared = r1 * r1;
  449. var l2Squared = l2 * l2;
  450. var r0r1 = r0 * r1;
  451. var c4 = l2Squared + r1Squared;
  452. var c3 = 2.0 * (l1 * l2 + r0r1);
  453. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  454. var c1 = 2.0 * (l0 * l1 - r0r1);
  455. var c0 = l0 * l0 - r0Squared;
  456. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  457. return solutions;
  458. }
  459. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  460. var length = cosines.length;
  461. if (length === 0) {
  462. return solutions;
  463. }
  464. for ( var i = 0; i < length; ++i) {
  465. var cosine = cosines[i];
  466. var cosineSquared = cosine * cosine;
  467. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  468. var sine = Math.sqrt(sineSquared);
  469. //var left = l2 * cosineSquared + l1 * cosine + l0;
  470. var left;
  471. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  472. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  473. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  474. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  475. } else {
  476. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  477. }
  478. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  479. var product = left * right;
  480. if (product < 0.0) {
  481. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  482. } else if (product > 0.0) {
  483. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  484. } else if (sine !== 0.0) {
  485. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  486. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  487. ++i;
  488. } else {
  489. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  490. }
  491. }
  492. return solutions;
  493. }
  494. var firstAxisScratch = new Cartesian3();
  495. var secondAxisScratch = new Cartesian3();
  496. var thirdAxisScratch = new Cartesian3();
  497. var referenceScratch = new Cartesian3();
  498. var bCart = new Cartesian3();
  499. var bScratch = new Matrix3();
  500. var btScratch = new Matrix3();
  501. var diScratch = new Matrix3();
  502. var dScratch = new Matrix3();
  503. var cScratch = new Matrix3();
  504. var tempMatrix = new Matrix3();
  505. var aScratch = new Matrix3();
  506. var sScratch = new Cartesian3();
  507. var closestScratch = new Cartesian3();
  508. var surfPointScratch = new Cartographic();
  509. /**
  510. * Provides the point along the ray which is nearest to the ellipsoid.
  511. *
  512. * @param {Ray} ray The ray.
  513. * @param {Ellipsoid} ellipsoid The ellipsoid.
  514. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  515. */
  516. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  517. //>>includeStart('debug', pragmas.debug);
  518. if (!defined(ray)) {
  519. throw new DeveloperError('ray is required.');
  520. }
  521. if (!defined(ellipsoid)) {
  522. throw new DeveloperError('ellipsoid is required.');
  523. }
  524. //>>includeEnd('debug');
  525. var position = ray.origin;
  526. var direction = ray.direction;
  527. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  528. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  529. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  530. return position;
  531. }
  532. }
  533. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  534. // Compute the scaled direction vector.
  535. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  536. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  537. var firstAxis = Cartesian3.normalize(f, f);
  538. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  539. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  540. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  541. var B = bScratch;
  542. B[0] = firstAxis.x;
  543. B[1] = firstAxis.y;
  544. B[2] = firstAxis.z;
  545. B[3] = secondAxis.x;
  546. B[4] = secondAxis.y;
  547. B[5] = secondAxis.z;
  548. B[6] = thirdAxis.x;
  549. B[7] = thirdAxis.y;
  550. B[8] = thirdAxis.z;
  551. var B_T = Matrix3.transpose(B, btScratch);
  552. // Get the scaling matrix and its inverse.
  553. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  554. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  555. var C = cScratch;
  556. C[0] = 0.0;
  557. C[1] = -direction.z;
  558. C[2] = direction.y;
  559. C[3] = direction.z;
  560. C[4] = 0.0;
  561. C[5] = -direction.x;
  562. C[6] = -direction.y;
  563. C[7] = direction.x;
  564. C[8] = 0.0;
  565. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  566. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  567. var b = Matrix3.multiplyByVector(temp, position, bCart);
  568. // Solve for the solutions to the expression in standard form:
  569. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  570. var s;
  571. var altitude;
  572. var length = solutions.length;
  573. if (length > 0) {
  574. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  575. var maximumValue = Number.NEGATIVE_INFINITY;
  576. for ( var i = 0; i < length; ++i) {
  577. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  578. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  579. var dotProduct = Cartesian3.dot(v, direction);
  580. if (dotProduct > maximumValue) {
  581. maximumValue = dotProduct;
  582. closest = Cartesian3.clone(s, closest);
  583. }
  584. }
  585. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  586. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  587. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  588. altitude = intersects ? -altitude : altitude;
  589. surfacePoint.height = altitude;
  590. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  591. }
  592. return undefined;
  593. };
  594. var lineSegmentPlaneDifference = new Cartesian3();
  595. /**
  596. * Computes the intersection of a line segment and a plane.
  597. *
  598. * @param {Cartesian3} endPoint0 An end point of the line segment.
  599. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  600. * @param {Plane} plane The plane.
  601. * @param {Cartesian3} [result] The object onto which to store the result.
  602. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  603. *
  604. * @example
  605. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  606. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  607. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  608. *
  609. * var p0 = new Cesium.Cartesian3(...);
  610. * var p1 = new Cesium.Cartesian3(...);
  611. *
  612. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  613. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  614. */
  615. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  616. //>>includeStart('debug', pragmas.debug);
  617. if (!defined(endPoint0)) {
  618. throw new DeveloperError('endPoint0 is required.');
  619. }
  620. if (!defined(endPoint1)) {
  621. throw new DeveloperError('endPoint1 is required.');
  622. }
  623. if (!defined(plane)) {
  624. throw new DeveloperError('plane is required.');
  625. }
  626. //>>includeEnd('debug');
  627. if (!defined(result)) {
  628. result = new Cartesian3();
  629. }
  630. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  631. var normal = plane.normal;
  632. var nDotDiff = Cartesian3.dot(normal, difference);
  633. // check if the segment and plane are parallel
  634. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  635. return undefined;
  636. }
  637. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  638. var t = -(plane.distance + nDotP0) / nDotDiff;
  639. // intersection only if t is in [0, 1]
  640. if (t < 0.0 || t > 1.0) {
  641. return undefined;
  642. }
  643. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  644. Cartesian3.multiplyByScalar(difference, t, result);
  645. Cartesian3.add(endPoint0, result, result);
  646. return result;
  647. };
  648. /**
  649. * Computes the intersection of a triangle and a plane
  650. *
  651. * @param {Cartesian3} p0 First point of the triangle
  652. * @param {Cartesian3} p1 Second point of the triangle
  653. * @param {Cartesian3} p2 Third point of the triangle
  654. * @param {Plane} plane Intersection plane
  655. * @returns {Object} An object with properties <code>positions</code> and <code>indices</code>, which are arrays that represent three triangles that do not cross the plane. (Undefined if no intersection exists)
  656. *
  657. * @example
  658. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  659. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  660. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  661. *
  662. * var p0 = new Cesium.Cartesian3(...);
  663. * var p1 = new Cesium.Cartesian3(...);
  664. * var p2 = new Cesium.Cartesian3(...);
  665. *
  666. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  667. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  668. */
  669. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  670. //>>includeStart('debug', pragmas.debug);
  671. if ((!defined(p0)) ||
  672. (!defined(p1)) ||
  673. (!defined(p2)) ||
  674. (!defined(plane))) {
  675. throw new DeveloperError('p0, p1, p2, and plane are required.');
  676. }
  677. //>>includeEnd('debug');
  678. var planeNormal = plane.normal;
  679. var planeD = plane.distance;
  680. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  681. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  682. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  683. // Given these dots products, the calls to lineSegmentPlaneIntersection
  684. // always have defined results.
  685. var numBehind = 0;
  686. numBehind += p0Behind ? 1 : 0;
  687. numBehind += p1Behind ? 1 : 0;
  688. numBehind += p2Behind ? 1 : 0;
  689. var u1, u2;
  690. if (numBehind === 1 || numBehind === 2) {
  691. u1 = new Cartesian3();
  692. u2 = new Cartesian3();
  693. }
  694. if (numBehind === 1) {
  695. if (p0Behind) {
  696. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  697. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  698. return {
  699. positions : [p0, p1, p2, u1, u2 ],
  700. indices : [
  701. // Behind
  702. 0, 3, 4,
  703. // In front
  704. 1, 2, 4,
  705. 1, 4, 3
  706. ]
  707. };
  708. } else if (p1Behind) {
  709. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  710. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  711. return {
  712. positions : [p0, p1, p2, u1, u2 ],
  713. indices : [
  714. // Behind
  715. 1, 3, 4,
  716. // In front
  717. 2, 0, 4,
  718. 2, 4, 3
  719. ]
  720. };
  721. } else if (p2Behind) {
  722. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  723. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  724. return {
  725. positions : [p0, p1, p2, u1, u2 ],
  726. indices : [
  727. // Behind
  728. 2, 3, 4,
  729. // In front
  730. 0, 1, 4,
  731. 0, 4, 3
  732. ]
  733. };
  734. }
  735. } else if (numBehind === 2) {
  736. if (!p0Behind) {
  737. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  738. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  739. return {
  740. positions : [p0, p1, p2, u1, u2 ],
  741. indices : [
  742. // Behind
  743. 1, 2, 4,
  744. 1, 4, 3,
  745. // In front
  746. 0, 3, 4
  747. ]
  748. };
  749. } else if (!p1Behind) {
  750. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  751. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  752. return {
  753. positions : [p0, p1, p2, u1, u2 ],
  754. indices : [
  755. // Behind
  756. 2, 0, 4,
  757. 2, 4, 3,
  758. // In front
  759. 1, 3, 4
  760. ]
  761. };
  762. } else if (!p2Behind) {
  763. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  764. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  765. return {
  766. positions : [p0, p1, p2, u1, u2 ],
  767. indices : [
  768. // Behind
  769. 0, 1, 4,
  770. 0, 4, 3,
  771. // In front
  772. 2, 3, 4
  773. ]
  774. };
  775. }
  776. }
  777. // if numBehind is 3, the triangle is completely behind the plane;
  778. // otherwise, it is completely in front (numBehind is 0).
  779. return undefined;
  780. };
  781. return IntersectionTests;
  782. });