BoundingSphere.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  1. import Cartesian3 from "./Cartesian3.js";
  2. import Cartographic from "./Cartographic.js";
  3. import Check from "./Check.js";
  4. import defaultValue from "./defaultValue.js";
  5. import defined from "./defined.js";
  6. import Ellipsoid from "./Ellipsoid.js";
  7. import GeographicProjection from "./GeographicProjection.js";
  8. import Intersect from "./Intersect.js";
  9. import Interval from "./Interval.js";
  10. import CesiumMath from "./Math.js";
  11. import Matrix3 from "./Matrix3.js";
  12. import Matrix4 from "./Matrix4.js";
  13. import Rectangle from "./Rectangle.js";
  14. /**
  15. * A bounding sphere with a center and a radius.
  16. * @alias BoundingSphere
  17. * @constructor
  18. *
  19. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  20. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  21. *
  22. * @see AxisAlignedBoundingBox
  23. * @see BoundingRectangle
  24. * @see Packable
  25. */
  26. function BoundingSphere(center, radius) {
  27. /**
  28. * The center point of the sphere.
  29. * @type {Cartesian3}
  30. * @default {@link Cartesian3.ZERO}
  31. */
  32. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  33. /**
  34. * The radius of the sphere.
  35. * @type {Number}
  36. * @default 0.0
  37. */
  38. this.radius = defaultValue(radius, 0.0);
  39. }
  40. const fromPointsXMin = new Cartesian3();
  41. const fromPointsYMin = new Cartesian3();
  42. const fromPointsZMin = new Cartesian3();
  43. const fromPointsXMax = new Cartesian3();
  44. const fromPointsYMax = new Cartesian3();
  45. const fromPointsZMax = new Cartesian3();
  46. const fromPointsCurrentPos = new Cartesian3();
  47. const fromPointsScratch = new Cartesian3();
  48. const fromPointsRitterCenter = new Cartesian3();
  49. const fromPointsMinBoxPt = new Cartesian3();
  50. const fromPointsMaxBoxPt = new Cartesian3();
  51. const fromPointsNaiveCenterScratch = new Cartesian3();
  52. const volumeConstant = (4.0 / 3.0) * CesiumMath.PI;
  53. /**
  54. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  55. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  56. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  57. *
  58. * @param {Cartesian3[]} [positions] An array of points that the bounding sphere will enclose. Each point must have <code>x</code>, <code>y</code>, and <code>z</code> properties.
  59. * @param {BoundingSphere} [result] The object onto which to store the result.
  60. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  61. *
  62. * @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
  63. */
  64. BoundingSphere.fromPoints = function (positions, result) {
  65. if (!defined(result)) {
  66. result = new BoundingSphere();
  67. }
  68. if (!defined(positions) || positions.length === 0) {
  69. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  70. result.radius = 0.0;
  71. return result;
  72. }
  73. const currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  74. const xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  75. const yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  76. const zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  77. const xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  78. const yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  79. const zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  80. const numPositions = positions.length;
  81. let i;
  82. for (i = 1; i < numPositions; i++) {
  83. Cartesian3.clone(positions[i], currentPos);
  84. const x = currentPos.x;
  85. const y = currentPos.y;
  86. const z = currentPos.z;
  87. // Store points containing the the smallest and largest components
  88. if (x < xMin.x) {
  89. Cartesian3.clone(currentPos, xMin);
  90. }
  91. if (x > xMax.x) {
  92. Cartesian3.clone(currentPos, xMax);
  93. }
  94. if (y < yMin.y) {
  95. Cartesian3.clone(currentPos, yMin);
  96. }
  97. if (y > yMax.y) {
  98. Cartesian3.clone(currentPos, yMax);
  99. }
  100. if (z < zMin.z) {
  101. Cartesian3.clone(currentPos, zMin);
  102. }
  103. if (z > zMax.z) {
  104. Cartesian3.clone(currentPos, zMax);
  105. }
  106. }
  107. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  108. const xSpan = Cartesian3.magnitudeSquared(
  109. Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  110. );
  111. const ySpan = Cartesian3.magnitudeSquared(
  112. Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  113. );
  114. const zSpan = Cartesian3.magnitudeSquared(
  115. Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  116. );
  117. // Set the diameter endpoints to the largest span.
  118. let diameter1 = xMin;
  119. let diameter2 = xMax;
  120. let maxSpan = xSpan;
  121. if (ySpan > maxSpan) {
  122. maxSpan = ySpan;
  123. diameter1 = yMin;
  124. diameter2 = yMax;
  125. }
  126. if (zSpan > maxSpan) {
  127. maxSpan = zSpan;
  128. diameter1 = zMin;
  129. diameter2 = zMax;
  130. }
  131. // Calculate the center of the initial sphere found by Ritter's algorithm
  132. const ritterCenter = fromPointsRitterCenter;
  133. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  134. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  135. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  136. // Calculate the radius of the initial sphere found by Ritter's algorithm
  137. let radiusSquared = Cartesian3.magnitudeSquared(
  138. Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  139. );
  140. let ritterRadius = Math.sqrt(radiusSquared);
  141. // Find the center of the sphere found using the Naive method.
  142. const minBoxPt = fromPointsMinBoxPt;
  143. minBoxPt.x = xMin.x;
  144. minBoxPt.y = yMin.y;
  145. minBoxPt.z = zMin.z;
  146. const maxBoxPt = fromPointsMaxBoxPt;
  147. maxBoxPt.x = xMax.x;
  148. maxBoxPt.y = yMax.y;
  149. maxBoxPt.z = zMax.z;
  150. const naiveCenter = Cartesian3.midpoint(
  151. minBoxPt,
  152. maxBoxPt,
  153. fromPointsNaiveCenterScratch
  154. );
  155. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  156. let naiveRadius = 0;
  157. for (i = 0; i < numPositions; i++) {
  158. Cartesian3.clone(positions[i], currentPos);
  159. // Find the furthest point from the naive center to calculate the naive radius.
  160. const r = Cartesian3.magnitude(
  161. Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  162. );
  163. if (r > naiveRadius) {
  164. naiveRadius = r;
  165. }
  166. // Make adjustments to the Ritter Sphere to include all points.
  167. const oldCenterToPointSquared = Cartesian3.magnitudeSquared(
  168. Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  169. );
  170. if (oldCenterToPointSquared > radiusSquared) {
  171. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  172. // Calculate new radius to include the point that lies outside
  173. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  174. radiusSquared = ritterRadius * ritterRadius;
  175. // Calculate center of new Ritter sphere
  176. const oldToNew = oldCenterToPoint - ritterRadius;
  177. ritterCenter.x =
  178. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  179. oldCenterToPoint;
  180. ritterCenter.y =
  181. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  182. oldCenterToPoint;
  183. ritterCenter.z =
  184. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  185. oldCenterToPoint;
  186. }
  187. }
  188. if (ritterRadius < naiveRadius) {
  189. Cartesian3.clone(ritterCenter, result.center);
  190. result.radius = ritterRadius;
  191. } else {
  192. Cartesian3.clone(naiveCenter, result.center);
  193. result.radius = naiveRadius;
  194. }
  195. return result;
  196. };
  197. const defaultProjection = new GeographicProjection();
  198. const fromRectangle2DLowerLeft = new Cartesian3();
  199. const fromRectangle2DUpperRight = new Cartesian3();
  200. const fromRectangle2DSouthwest = new Cartographic();
  201. const fromRectangle2DNortheast = new Cartographic();
  202. /**
  203. * Computes a bounding sphere from a rectangle projected in 2D.
  204. *
  205. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  206. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  207. * @param {BoundingSphere} [result] The object onto which to store the result.
  208. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  209. */
  210. BoundingSphere.fromRectangle2D = function (rectangle, projection, result) {
  211. return BoundingSphere.fromRectangleWithHeights2D(
  212. rectangle,
  213. projection,
  214. 0.0,
  215. 0.0,
  216. result
  217. );
  218. };
  219. /**
  220. * Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
  221. * object's minimum and maximum heights over the rectangle.
  222. *
  223. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  224. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  225. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  226. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  227. * @param {BoundingSphere} [result] The object onto which to store the result.
  228. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  229. */
  230. BoundingSphere.fromRectangleWithHeights2D = function (
  231. rectangle,
  232. projection,
  233. minimumHeight,
  234. maximumHeight,
  235. result
  236. ) {
  237. if (!defined(result)) {
  238. result = new BoundingSphere();
  239. }
  240. if (!defined(rectangle)) {
  241. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  242. result.radius = 0.0;
  243. return result;
  244. }
  245. projection = defaultValue(projection, defaultProjection);
  246. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  247. fromRectangle2DSouthwest.height = minimumHeight;
  248. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  249. fromRectangle2DNortheast.height = maximumHeight;
  250. const lowerLeft = projection.project(
  251. fromRectangle2DSouthwest,
  252. fromRectangle2DLowerLeft
  253. );
  254. const upperRight = projection.project(
  255. fromRectangle2DNortheast,
  256. fromRectangle2DUpperRight
  257. );
  258. const width = upperRight.x - lowerLeft.x;
  259. const height = upperRight.y - lowerLeft.y;
  260. const elevation = upperRight.z - lowerLeft.z;
  261. result.radius =
  262. Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  263. const center = result.center;
  264. center.x = lowerLeft.x + width * 0.5;
  265. center.y = lowerLeft.y + height * 0.5;
  266. center.z = lowerLeft.z + elevation * 0.5;
  267. return result;
  268. };
  269. const fromRectangle3DScratch = [];
  270. /**
  271. * Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
  272. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  273. *
  274. * @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
  275. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  276. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  277. * @param {BoundingSphere} [result] The object onto which to store the result.
  278. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  279. */
  280. BoundingSphere.fromRectangle3D = function (
  281. rectangle,
  282. ellipsoid,
  283. surfaceHeight,
  284. result
  285. ) {
  286. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  287. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  288. if (!defined(result)) {
  289. result = new BoundingSphere();
  290. }
  291. if (!defined(rectangle)) {
  292. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  293. result.radius = 0.0;
  294. return result;
  295. }
  296. const positions = Rectangle.subsample(
  297. rectangle,
  298. ellipsoid,
  299. surfaceHeight,
  300. fromRectangle3DScratch
  301. );
  302. return BoundingSphere.fromPoints(positions, result);
  303. };
  304. /**
  305. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  306. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  307. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  308. * ensure a tight fit.
  309. *
  310. * @param {Number[]} [positions] An array of points that the bounding sphere will enclose. Each point
  311. * is formed from three elements in the array in the order X, Y, Z.
  312. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  313. * origin of the coordinate system. This is useful when the positions are to be used for
  314. * relative-to-center (RTC) rendering.
  315. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  316. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  317. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  318. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  319. * the stride is 5, however, two array elements are skipped and the next position begins at array
  320. * index 5.
  321. * @param {BoundingSphere} [result] The object onto which to store the result.
  322. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  323. *
  324. * @example
  325. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  326. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  327. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  328. * const center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  329. * const points = [1.0, 2.0, 3.0, 0.1, 0.2,
  330. * 4.0, 5.0, 6.0, 0.1, 0.2,
  331. * 7.0, 8.0, 9.0, 0.1, 0.2];
  332. * const sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  333. *
  334. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  335. */
  336. BoundingSphere.fromVertices = function (positions, center, stride, result) {
  337. if (!defined(result)) {
  338. result = new BoundingSphere();
  339. }
  340. if (!defined(positions) || positions.length === 0) {
  341. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  342. result.radius = 0.0;
  343. return result;
  344. }
  345. center = defaultValue(center, Cartesian3.ZERO);
  346. stride = defaultValue(stride, 3);
  347. //>>includeStart('debug', pragmas.debug);
  348. Check.typeOf.number.greaterThanOrEquals("stride", stride, 3);
  349. //>>includeEnd('debug');
  350. const currentPos = fromPointsCurrentPos;
  351. currentPos.x = positions[0] + center.x;
  352. currentPos.y = positions[1] + center.y;
  353. currentPos.z = positions[2] + center.z;
  354. const xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  355. const yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  356. const zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  357. const xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  358. const yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  359. const zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  360. const numElements = positions.length;
  361. let i;
  362. for (i = 0; i < numElements; i += stride) {
  363. const x = positions[i] + center.x;
  364. const y = positions[i + 1] + center.y;
  365. const z = positions[i + 2] + center.z;
  366. currentPos.x = x;
  367. currentPos.y = y;
  368. currentPos.z = z;
  369. // Store points containing the the smallest and largest components
  370. if (x < xMin.x) {
  371. Cartesian3.clone(currentPos, xMin);
  372. }
  373. if (x > xMax.x) {
  374. Cartesian3.clone(currentPos, xMax);
  375. }
  376. if (y < yMin.y) {
  377. Cartesian3.clone(currentPos, yMin);
  378. }
  379. if (y > yMax.y) {
  380. Cartesian3.clone(currentPos, yMax);
  381. }
  382. if (z < zMin.z) {
  383. Cartesian3.clone(currentPos, zMin);
  384. }
  385. if (z > zMax.z) {
  386. Cartesian3.clone(currentPos, zMax);
  387. }
  388. }
  389. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  390. const xSpan = Cartesian3.magnitudeSquared(
  391. Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  392. );
  393. const ySpan = Cartesian3.magnitudeSquared(
  394. Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  395. );
  396. const zSpan = Cartesian3.magnitudeSquared(
  397. Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  398. );
  399. // Set the diameter endpoints to the largest span.
  400. let diameter1 = xMin;
  401. let diameter2 = xMax;
  402. let maxSpan = xSpan;
  403. if (ySpan > maxSpan) {
  404. maxSpan = ySpan;
  405. diameter1 = yMin;
  406. diameter2 = yMax;
  407. }
  408. if (zSpan > maxSpan) {
  409. maxSpan = zSpan;
  410. diameter1 = zMin;
  411. diameter2 = zMax;
  412. }
  413. // Calculate the center of the initial sphere found by Ritter's algorithm
  414. const ritterCenter = fromPointsRitterCenter;
  415. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  416. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  417. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  418. // Calculate the radius of the initial sphere found by Ritter's algorithm
  419. let radiusSquared = Cartesian3.magnitudeSquared(
  420. Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  421. );
  422. let ritterRadius = Math.sqrt(radiusSquared);
  423. // Find the center of the sphere found using the Naive method.
  424. const minBoxPt = fromPointsMinBoxPt;
  425. minBoxPt.x = xMin.x;
  426. minBoxPt.y = yMin.y;
  427. minBoxPt.z = zMin.z;
  428. const maxBoxPt = fromPointsMaxBoxPt;
  429. maxBoxPt.x = xMax.x;
  430. maxBoxPt.y = yMax.y;
  431. maxBoxPt.z = zMax.z;
  432. const naiveCenter = Cartesian3.midpoint(
  433. minBoxPt,
  434. maxBoxPt,
  435. fromPointsNaiveCenterScratch
  436. );
  437. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  438. let naiveRadius = 0;
  439. for (i = 0; i < numElements; i += stride) {
  440. currentPos.x = positions[i] + center.x;
  441. currentPos.y = positions[i + 1] + center.y;
  442. currentPos.z = positions[i + 2] + center.z;
  443. // Find the furthest point from the naive center to calculate the naive radius.
  444. const r = Cartesian3.magnitude(
  445. Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  446. );
  447. if (r > naiveRadius) {
  448. naiveRadius = r;
  449. }
  450. // Make adjustments to the Ritter Sphere to include all points.
  451. const oldCenterToPointSquared = Cartesian3.magnitudeSquared(
  452. Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  453. );
  454. if (oldCenterToPointSquared > radiusSquared) {
  455. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  456. // Calculate new radius to include the point that lies outside
  457. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  458. radiusSquared = ritterRadius * ritterRadius;
  459. // Calculate center of new Ritter sphere
  460. const oldToNew = oldCenterToPoint - ritterRadius;
  461. ritterCenter.x =
  462. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  463. oldCenterToPoint;
  464. ritterCenter.y =
  465. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  466. oldCenterToPoint;
  467. ritterCenter.z =
  468. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  469. oldCenterToPoint;
  470. }
  471. }
  472. if (ritterRadius < naiveRadius) {
  473. Cartesian3.clone(ritterCenter, result.center);
  474. result.radius = ritterRadius;
  475. } else {
  476. Cartesian3.clone(naiveCenter, result.center);
  477. result.radius = naiveRadius;
  478. }
  479. return result;
  480. };
  481. /**
  482. * Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
  483. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  484. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  485. * ensure a tight fit.
  486. *
  487. * @param {Number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  488. * is formed from three elements in the array in the order X, Y, Z.
  489. * @param {Number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  490. * is formed from three elements in the array in the order X, Y, Z.
  491. * @param {BoundingSphere} [result] The object onto which to store the result.
  492. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  493. *
  494. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  495. */
  496. BoundingSphere.fromEncodedCartesianVertices = function (
  497. positionsHigh,
  498. positionsLow,
  499. result
  500. ) {
  501. if (!defined(result)) {
  502. result = new BoundingSphere();
  503. }
  504. if (
  505. !defined(positionsHigh) ||
  506. !defined(positionsLow) ||
  507. positionsHigh.length !== positionsLow.length ||
  508. positionsHigh.length === 0
  509. ) {
  510. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  511. result.radius = 0.0;
  512. return result;
  513. }
  514. const currentPos = fromPointsCurrentPos;
  515. currentPos.x = positionsHigh[0] + positionsLow[0];
  516. currentPos.y = positionsHigh[1] + positionsLow[1];
  517. currentPos.z = positionsHigh[2] + positionsLow[2];
  518. const xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  519. const yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  520. const zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  521. const xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  522. const yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  523. const zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  524. const numElements = positionsHigh.length;
  525. let i;
  526. for (i = 0; i < numElements; i += 3) {
  527. const x = positionsHigh[i] + positionsLow[i];
  528. const y = positionsHigh[i + 1] + positionsLow[i + 1];
  529. const z = positionsHigh[i + 2] + positionsLow[i + 2];
  530. currentPos.x = x;
  531. currentPos.y = y;
  532. currentPos.z = z;
  533. // Store points containing the the smallest and largest components
  534. if (x < xMin.x) {
  535. Cartesian3.clone(currentPos, xMin);
  536. }
  537. if (x > xMax.x) {
  538. Cartesian3.clone(currentPos, xMax);
  539. }
  540. if (y < yMin.y) {
  541. Cartesian3.clone(currentPos, yMin);
  542. }
  543. if (y > yMax.y) {
  544. Cartesian3.clone(currentPos, yMax);
  545. }
  546. if (z < zMin.z) {
  547. Cartesian3.clone(currentPos, zMin);
  548. }
  549. if (z > zMax.z) {
  550. Cartesian3.clone(currentPos, zMax);
  551. }
  552. }
  553. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  554. const xSpan = Cartesian3.magnitudeSquared(
  555. Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  556. );
  557. const ySpan = Cartesian3.magnitudeSquared(
  558. Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  559. );
  560. const zSpan = Cartesian3.magnitudeSquared(
  561. Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  562. );
  563. // Set the diameter endpoints to the largest span.
  564. let diameter1 = xMin;
  565. let diameter2 = xMax;
  566. let maxSpan = xSpan;
  567. if (ySpan > maxSpan) {
  568. maxSpan = ySpan;
  569. diameter1 = yMin;
  570. diameter2 = yMax;
  571. }
  572. if (zSpan > maxSpan) {
  573. maxSpan = zSpan;
  574. diameter1 = zMin;
  575. diameter2 = zMax;
  576. }
  577. // Calculate the center of the initial sphere found by Ritter's algorithm
  578. const ritterCenter = fromPointsRitterCenter;
  579. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  580. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  581. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  582. // Calculate the radius of the initial sphere found by Ritter's algorithm
  583. let radiusSquared = Cartesian3.magnitudeSquared(
  584. Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  585. );
  586. let ritterRadius = Math.sqrt(radiusSquared);
  587. // Find the center of the sphere found using the Naive method.
  588. const minBoxPt = fromPointsMinBoxPt;
  589. minBoxPt.x = xMin.x;
  590. minBoxPt.y = yMin.y;
  591. minBoxPt.z = zMin.z;
  592. const maxBoxPt = fromPointsMaxBoxPt;
  593. maxBoxPt.x = xMax.x;
  594. maxBoxPt.y = yMax.y;
  595. maxBoxPt.z = zMax.z;
  596. const naiveCenter = Cartesian3.midpoint(
  597. minBoxPt,
  598. maxBoxPt,
  599. fromPointsNaiveCenterScratch
  600. );
  601. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  602. let naiveRadius = 0;
  603. for (i = 0; i < numElements; i += 3) {
  604. currentPos.x = positionsHigh[i] + positionsLow[i];
  605. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  606. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  607. // Find the furthest point from the naive center to calculate the naive radius.
  608. const r = Cartesian3.magnitude(
  609. Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  610. );
  611. if (r > naiveRadius) {
  612. naiveRadius = r;
  613. }
  614. // Make adjustments to the Ritter Sphere to include all points.
  615. const oldCenterToPointSquared = Cartesian3.magnitudeSquared(
  616. Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  617. );
  618. if (oldCenterToPointSquared > radiusSquared) {
  619. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  620. // Calculate new radius to include the point that lies outside
  621. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  622. radiusSquared = ritterRadius * ritterRadius;
  623. // Calculate center of new Ritter sphere
  624. const oldToNew = oldCenterToPoint - ritterRadius;
  625. ritterCenter.x =
  626. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  627. oldCenterToPoint;
  628. ritterCenter.y =
  629. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  630. oldCenterToPoint;
  631. ritterCenter.z =
  632. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  633. oldCenterToPoint;
  634. }
  635. }
  636. if (ritterRadius < naiveRadius) {
  637. Cartesian3.clone(ritterCenter, result.center);
  638. result.radius = ritterRadius;
  639. } else {
  640. Cartesian3.clone(naiveCenter, result.center);
  641. result.radius = naiveRadius;
  642. }
  643. return result;
  644. };
  645. /**
  646. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  647. * tighly and fully encompases the box.
  648. *
  649. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  650. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  651. * @param {BoundingSphere} [result] The object onto which to store the result.
  652. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  653. *
  654. * @example
  655. * // Create a bounding sphere around the unit cube
  656. * const sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  657. */
  658. BoundingSphere.fromCornerPoints = function (corner, oppositeCorner, result) {
  659. //>>includeStart('debug', pragmas.debug);
  660. Check.typeOf.object("corner", corner);
  661. Check.typeOf.object("oppositeCorner", oppositeCorner);
  662. //>>includeEnd('debug');
  663. if (!defined(result)) {
  664. result = new BoundingSphere();
  665. }
  666. const center = Cartesian3.midpoint(corner, oppositeCorner, result.center);
  667. result.radius = Cartesian3.distance(center, oppositeCorner);
  668. return result;
  669. };
  670. /**
  671. * Creates a bounding sphere encompassing an ellipsoid.
  672. *
  673. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  674. * @param {BoundingSphere} [result] The object onto which to store the result.
  675. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  676. *
  677. * @example
  678. * const boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  679. */
  680. BoundingSphere.fromEllipsoid = function (ellipsoid, result) {
  681. //>>includeStart('debug', pragmas.debug);
  682. Check.typeOf.object("ellipsoid", ellipsoid);
  683. //>>includeEnd('debug');
  684. if (!defined(result)) {
  685. result = new BoundingSphere();
  686. }
  687. Cartesian3.clone(Cartesian3.ZERO, result.center);
  688. result.radius = ellipsoid.maximumRadius;
  689. return result;
  690. };
  691. const fromBoundingSpheresScratch = new Cartesian3();
  692. /**
  693. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  694. *
  695. * @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
  696. * @param {BoundingSphere} [result] The object onto which to store the result.
  697. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  698. */
  699. BoundingSphere.fromBoundingSpheres = function (boundingSpheres, result) {
  700. if (!defined(result)) {
  701. result = new BoundingSphere();
  702. }
  703. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  704. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  705. result.radius = 0.0;
  706. return result;
  707. }
  708. const length = boundingSpheres.length;
  709. if (length === 1) {
  710. return BoundingSphere.clone(boundingSpheres[0], result);
  711. }
  712. if (length === 2) {
  713. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  714. }
  715. const positions = [];
  716. let i;
  717. for (i = 0; i < length; i++) {
  718. positions.push(boundingSpheres[i].center);
  719. }
  720. result = BoundingSphere.fromPoints(positions, result);
  721. const center = result.center;
  722. let radius = result.radius;
  723. for (i = 0; i < length; i++) {
  724. const tmp = boundingSpheres[i];
  725. radius = Math.max(
  726. radius,
  727. Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) +
  728. tmp.radius
  729. );
  730. }
  731. result.radius = radius;
  732. return result;
  733. };
  734. const fromOrientedBoundingBoxScratchU = new Cartesian3();
  735. const fromOrientedBoundingBoxScratchV = new Cartesian3();
  736. const fromOrientedBoundingBoxScratchW = new Cartesian3();
  737. /**
  738. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  739. *
  740. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  741. * @param {BoundingSphere} [result] The object onto which to store the result.
  742. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  743. */
  744. BoundingSphere.fromOrientedBoundingBox = function (
  745. orientedBoundingBox,
  746. result
  747. ) {
  748. //>>includeStart('debug', pragmas.debug);
  749. Check.defined("orientedBoundingBox", orientedBoundingBox);
  750. //>>includeEnd('debug');
  751. if (!defined(result)) {
  752. result = new BoundingSphere();
  753. }
  754. const halfAxes = orientedBoundingBox.halfAxes;
  755. const u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  756. const v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  757. const w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  758. Cartesian3.add(u, v, u);
  759. Cartesian3.add(u, w, u);
  760. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  761. result.radius = Cartesian3.magnitude(u);
  762. return result;
  763. };
  764. const scratchFromTransformationCenter = new Cartesian3();
  765. const scratchFromTransformationScale = new Cartesian3();
  766. /**
  767. * Computes a tight-fitting bounding sphere enclosing the provided affine transformation.
  768. *
  769. * @param {Matrix4} transformation The affine transformation.
  770. * @param {BoundingSphere} [result] The object onto which to store the result.
  771. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  772. */
  773. BoundingSphere.fromTransformation = function (transformation, result) {
  774. //>>includeStart('debug', pragmas.debug);
  775. Check.typeOf.object("transformation", transformation);
  776. //>>includeEnd('debug');
  777. if (!defined(result)) {
  778. result = new BoundingSphere();
  779. }
  780. const center = Matrix4.getTranslation(
  781. transformation,
  782. scratchFromTransformationCenter
  783. );
  784. const scale = Matrix4.getScale(
  785. transformation,
  786. scratchFromTransformationScale
  787. );
  788. const radius = 0.5 * Cartesian3.magnitude(scale);
  789. result.center = Cartesian3.clone(center, result.center);
  790. result.radius = radius;
  791. return result;
  792. };
  793. /**
  794. * Duplicates a BoundingSphere instance.
  795. *
  796. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  797. * @param {BoundingSphere} [result] The object onto which to store the result.
  798. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  799. */
  800. BoundingSphere.clone = function (sphere, result) {
  801. if (!defined(sphere)) {
  802. return undefined;
  803. }
  804. if (!defined(result)) {
  805. return new BoundingSphere(sphere.center, sphere.radius);
  806. }
  807. result.center = Cartesian3.clone(sphere.center, result.center);
  808. result.radius = sphere.radius;
  809. return result;
  810. };
  811. /**
  812. * The number of elements used to pack the object into an array.
  813. * @type {Number}
  814. */
  815. BoundingSphere.packedLength = 4;
  816. /**
  817. * Stores the provided instance into the provided array.
  818. *
  819. * @param {BoundingSphere} value The value to pack.
  820. * @param {Number[]} array The array to pack into.
  821. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  822. *
  823. * @returns {Number[]} The array that was packed into
  824. */
  825. BoundingSphere.pack = function (value, array, startingIndex) {
  826. //>>includeStart('debug', pragmas.debug);
  827. Check.typeOf.object("value", value);
  828. Check.defined("array", array);
  829. //>>includeEnd('debug');
  830. startingIndex = defaultValue(startingIndex, 0);
  831. const center = value.center;
  832. array[startingIndex++] = center.x;
  833. array[startingIndex++] = center.y;
  834. array[startingIndex++] = center.z;
  835. array[startingIndex] = value.radius;
  836. return array;
  837. };
  838. /**
  839. * Retrieves an instance from a packed array.
  840. *
  841. * @param {Number[]} array The packed array.
  842. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  843. * @param {BoundingSphere} [result] The object into which to store the result.
  844. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  845. */
  846. BoundingSphere.unpack = function (array, startingIndex, result) {
  847. //>>includeStart('debug', pragmas.debug);
  848. Check.defined("array", array);
  849. //>>includeEnd('debug');
  850. startingIndex = defaultValue(startingIndex, 0);
  851. if (!defined(result)) {
  852. result = new BoundingSphere();
  853. }
  854. const center = result.center;
  855. center.x = array[startingIndex++];
  856. center.y = array[startingIndex++];
  857. center.z = array[startingIndex++];
  858. result.radius = array[startingIndex];
  859. return result;
  860. };
  861. const unionScratch = new Cartesian3();
  862. const unionScratchCenter = new Cartesian3();
  863. /**
  864. * Computes a bounding sphere that contains both the left and right bounding spheres.
  865. *
  866. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  867. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  868. * @param {BoundingSphere} [result] The object onto which to store the result.
  869. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  870. */
  871. BoundingSphere.union = function (left, right, result) {
  872. //>>includeStart('debug', pragmas.debug);
  873. Check.typeOf.object("left", left);
  874. Check.typeOf.object("right", right);
  875. //>>includeEnd('debug');
  876. if (!defined(result)) {
  877. result = new BoundingSphere();
  878. }
  879. const leftCenter = left.center;
  880. const leftRadius = left.radius;
  881. const rightCenter = right.center;
  882. const rightRadius = right.radius;
  883. const toRightCenter = Cartesian3.subtract(
  884. rightCenter,
  885. leftCenter,
  886. unionScratch
  887. );
  888. const centerSeparation = Cartesian3.magnitude(toRightCenter);
  889. if (leftRadius >= centerSeparation + rightRadius) {
  890. // Left sphere wins.
  891. left.clone(result);
  892. return result;
  893. }
  894. if (rightRadius >= centerSeparation + leftRadius) {
  895. // Right sphere wins.
  896. right.clone(result);
  897. return result;
  898. }
  899. // There are two tangent points, one on far side of each sphere.
  900. const halfDistanceBetweenTangentPoints =
  901. (leftRadius + centerSeparation + rightRadius) * 0.5;
  902. // Compute the center point halfway between the two tangent points.
  903. const center = Cartesian3.multiplyByScalar(
  904. toRightCenter,
  905. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
  906. unionScratchCenter
  907. );
  908. Cartesian3.add(center, leftCenter, center);
  909. Cartesian3.clone(center, result.center);
  910. result.radius = halfDistanceBetweenTangentPoints;
  911. return result;
  912. };
  913. const expandScratch = new Cartesian3();
  914. /**
  915. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  916. *
  917. * @param {BoundingSphere} sphere A sphere to expand.
  918. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  919. * @param {BoundingSphere} [result] The object onto which to store the result.
  920. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  921. */
  922. BoundingSphere.expand = function (sphere, point, result) {
  923. //>>includeStart('debug', pragmas.debug);
  924. Check.typeOf.object("sphere", sphere);
  925. Check.typeOf.object("point", point);
  926. //>>includeEnd('debug');
  927. result = BoundingSphere.clone(sphere, result);
  928. const radius = Cartesian3.magnitude(
  929. Cartesian3.subtract(point, result.center, expandScratch)
  930. );
  931. if (radius > result.radius) {
  932. result.radius = radius;
  933. }
  934. return result;
  935. };
  936. /**
  937. * Determines which side of a plane a sphere is located.
  938. *
  939. * @param {BoundingSphere} sphere The bounding sphere to test.
  940. * @param {Plane} plane The plane to test against.
  941. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  942. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  943. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  944. * intersects the plane.
  945. */
  946. BoundingSphere.intersectPlane = function (sphere, plane) {
  947. //>>includeStart('debug', pragmas.debug);
  948. Check.typeOf.object("sphere", sphere);
  949. Check.typeOf.object("plane", plane);
  950. //>>includeEnd('debug');
  951. const center = sphere.center;
  952. const radius = sphere.radius;
  953. const normal = plane.normal;
  954. const distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  955. if (distanceToPlane < -radius) {
  956. // The center point is negative side of the plane normal
  957. return Intersect.OUTSIDE;
  958. } else if (distanceToPlane < radius) {
  959. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  960. return Intersect.INTERSECTING;
  961. }
  962. return Intersect.INSIDE;
  963. };
  964. /**
  965. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  966. *
  967. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  968. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  969. * @param {BoundingSphere} [result] The object onto which to store the result.
  970. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  971. */
  972. BoundingSphere.transform = function (sphere, transform, result) {
  973. //>>includeStart('debug', pragmas.debug);
  974. Check.typeOf.object("sphere", sphere);
  975. Check.typeOf.object("transform", transform);
  976. //>>includeEnd('debug');
  977. if (!defined(result)) {
  978. result = new BoundingSphere();
  979. }
  980. result.center = Matrix4.multiplyByPoint(
  981. transform,
  982. sphere.center,
  983. result.center
  984. );
  985. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  986. return result;
  987. };
  988. const distanceSquaredToScratch = new Cartesian3();
  989. /**
  990. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  991. *
  992. * @param {BoundingSphere} sphere The sphere.
  993. * @param {Cartesian3} cartesian The point
  994. * @returns {Number} The distance squared from the bounding sphere to the point. Returns 0 if the point is inside the sphere.
  995. *
  996. * @example
  997. * // Sort bounding spheres from back to front
  998. * spheres.sort(function(a, b) {
  999. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  1000. * });
  1001. */
  1002. BoundingSphere.distanceSquaredTo = function (sphere, cartesian) {
  1003. //>>includeStart('debug', pragmas.debug);
  1004. Check.typeOf.object("sphere", sphere);
  1005. Check.typeOf.object("cartesian", cartesian);
  1006. //>>includeEnd('debug');
  1007. const diff = Cartesian3.subtract(
  1008. sphere.center,
  1009. cartesian,
  1010. distanceSquaredToScratch
  1011. );
  1012. const distance = Cartesian3.magnitude(diff) - sphere.radius;
  1013. if (distance <= 0.0) {
  1014. return 0.0;
  1015. }
  1016. return distance * distance;
  1017. };
  1018. /**
  1019. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  1020. * The transformation matrix is not verified to have a uniform scale of 1.
  1021. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  1022. *
  1023. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  1024. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  1025. * @param {BoundingSphere} [result] The object onto which to store the result.
  1026. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1027. *
  1028. * @example
  1029. * const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  1030. * const boundingSphere = new Cesium.BoundingSphere();
  1031. * const newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  1032. */
  1033. BoundingSphere.transformWithoutScale = function (sphere, transform, result) {
  1034. //>>includeStart('debug', pragmas.debug);
  1035. Check.typeOf.object("sphere", sphere);
  1036. Check.typeOf.object("transform", transform);
  1037. //>>includeEnd('debug');
  1038. if (!defined(result)) {
  1039. result = new BoundingSphere();
  1040. }
  1041. result.center = Matrix4.multiplyByPoint(
  1042. transform,
  1043. sphere.center,
  1044. result.center
  1045. );
  1046. result.radius = sphere.radius;
  1047. return result;
  1048. };
  1049. const scratchCartesian3 = new Cartesian3();
  1050. /**
  1051. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  1052. * plus/minus the radius of the bounding sphere.
  1053. * <br>
  1054. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  1055. * closest and farthest planes from position that intersect the bounding sphere.
  1056. *
  1057. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  1058. * @param {Cartesian3} position The position to calculate the distance from.
  1059. * @param {Cartesian3} direction The direction from position.
  1060. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  1061. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  1062. */
  1063. BoundingSphere.computePlaneDistances = function (
  1064. sphere,
  1065. position,
  1066. direction,
  1067. result
  1068. ) {
  1069. //>>includeStart('debug', pragmas.debug);
  1070. Check.typeOf.object("sphere", sphere);
  1071. Check.typeOf.object("position", position);
  1072. Check.typeOf.object("direction", direction);
  1073. //>>includeEnd('debug');
  1074. if (!defined(result)) {
  1075. result = new Interval();
  1076. }
  1077. const toCenter = Cartesian3.subtract(
  1078. sphere.center,
  1079. position,
  1080. scratchCartesian3
  1081. );
  1082. const mag = Cartesian3.dot(direction, toCenter);
  1083. result.start = mag - sphere.radius;
  1084. result.stop = mag + sphere.radius;
  1085. return result;
  1086. };
  1087. const projectTo2DNormalScratch = new Cartesian3();
  1088. const projectTo2DEastScratch = new Cartesian3();
  1089. const projectTo2DNorthScratch = new Cartesian3();
  1090. const projectTo2DWestScratch = new Cartesian3();
  1091. const projectTo2DSouthScratch = new Cartesian3();
  1092. const projectTo2DCartographicScratch = new Cartographic();
  1093. const projectTo2DPositionsScratch = new Array(8);
  1094. for (let n = 0; n < 8; ++n) {
  1095. projectTo2DPositionsScratch[n] = new Cartesian3();
  1096. }
  1097. const projectTo2DProjection = new GeographicProjection();
  1098. /**
  1099. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  1100. *
  1101. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  1102. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  1103. * @param {BoundingSphere} [result] The object onto which to store the result.
  1104. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1105. */
  1106. BoundingSphere.projectTo2D = function (sphere, projection, result) {
  1107. //>>includeStart('debug', pragmas.debug);
  1108. Check.typeOf.object("sphere", sphere);
  1109. //>>includeEnd('debug');
  1110. projection = defaultValue(projection, projectTo2DProjection);
  1111. const ellipsoid = projection.ellipsoid;
  1112. let center = sphere.center;
  1113. const radius = sphere.radius;
  1114. let normal;
  1115. if (Cartesian3.equals(center, Cartesian3.ZERO)) {
  1116. // Bounding sphere is at the center. The geodetic surface normal is not
  1117. // defined here so pick the x-axis as a fallback.
  1118. normal = Cartesian3.clone(Cartesian3.UNIT_X, projectTo2DNormalScratch);
  1119. } else {
  1120. normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  1121. }
  1122. const east = Cartesian3.cross(
  1123. Cartesian3.UNIT_Z,
  1124. normal,
  1125. projectTo2DEastScratch
  1126. );
  1127. Cartesian3.normalize(east, east);
  1128. const north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  1129. Cartesian3.normalize(north, north);
  1130. Cartesian3.multiplyByScalar(normal, radius, normal);
  1131. Cartesian3.multiplyByScalar(north, radius, north);
  1132. Cartesian3.multiplyByScalar(east, radius, east);
  1133. const south = Cartesian3.negate(north, projectTo2DSouthScratch);
  1134. const west = Cartesian3.negate(east, projectTo2DWestScratch);
  1135. const positions = projectTo2DPositionsScratch;
  1136. // top NE corner
  1137. let corner = positions[0];
  1138. Cartesian3.add(normal, north, corner);
  1139. Cartesian3.add(corner, east, corner);
  1140. // top NW corner
  1141. corner = positions[1];
  1142. Cartesian3.add(normal, north, corner);
  1143. Cartesian3.add(corner, west, corner);
  1144. // top SW corner
  1145. corner = positions[2];
  1146. Cartesian3.add(normal, south, corner);
  1147. Cartesian3.add(corner, west, corner);
  1148. // top SE corner
  1149. corner = positions[3];
  1150. Cartesian3.add(normal, south, corner);
  1151. Cartesian3.add(corner, east, corner);
  1152. Cartesian3.negate(normal, normal);
  1153. // bottom NE corner
  1154. corner = positions[4];
  1155. Cartesian3.add(normal, north, corner);
  1156. Cartesian3.add(corner, east, corner);
  1157. // bottom NW corner
  1158. corner = positions[5];
  1159. Cartesian3.add(normal, north, corner);
  1160. Cartesian3.add(corner, west, corner);
  1161. // bottom SW corner
  1162. corner = positions[6];
  1163. Cartesian3.add(normal, south, corner);
  1164. Cartesian3.add(corner, west, corner);
  1165. // bottom SE corner
  1166. corner = positions[7];
  1167. Cartesian3.add(normal, south, corner);
  1168. Cartesian3.add(corner, east, corner);
  1169. const length = positions.length;
  1170. for (let i = 0; i < length; ++i) {
  1171. const position = positions[i];
  1172. Cartesian3.add(center, position, position);
  1173. const cartographic = ellipsoid.cartesianToCartographic(
  1174. position,
  1175. projectTo2DCartographicScratch
  1176. );
  1177. projection.project(cartographic, position);
  1178. }
  1179. result = BoundingSphere.fromPoints(positions, result);
  1180. // swizzle center components
  1181. center = result.center;
  1182. const x = center.x;
  1183. const y = center.y;
  1184. const z = center.z;
  1185. center.x = z;
  1186. center.y = x;
  1187. center.z = y;
  1188. return result;
  1189. };
  1190. /**
  1191. * Determines whether or not a sphere is hidden from view by the occluder.
  1192. *
  1193. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  1194. * @param {Occluder} occluder The occluder.
  1195. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  1196. */
  1197. BoundingSphere.isOccluded = function (sphere, occluder) {
  1198. //>>includeStart('debug', pragmas.debug);
  1199. Check.typeOf.object("sphere", sphere);
  1200. Check.typeOf.object("occluder", occluder);
  1201. //>>includeEnd('debug');
  1202. return !occluder.isBoundingSphereVisible(sphere);
  1203. };
  1204. /**
  1205. * Compares the provided BoundingSphere componentwise and returns
  1206. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1207. *
  1208. * @param {BoundingSphere} [left] The first BoundingSphere.
  1209. * @param {BoundingSphere} [right] The second BoundingSphere.
  1210. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1211. */
  1212. BoundingSphere.equals = function (left, right) {
  1213. return (
  1214. left === right ||
  1215. (defined(left) &&
  1216. defined(right) &&
  1217. Cartesian3.equals(left.center, right.center) &&
  1218. left.radius === right.radius)
  1219. );
  1220. };
  1221. /**
  1222. * Determines which side of a plane the sphere is located.
  1223. *
  1224. * @param {Plane} plane The plane to test against.
  1225. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  1226. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  1227. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  1228. * intersects the plane.
  1229. */
  1230. BoundingSphere.prototype.intersectPlane = function (plane) {
  1231. return BoundingSphere.intersectPlane(this, plane);
  1232. };
  1233. /**
  1234. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  1235. *
  1236. * @param {Cartesian3} cartesian The point
  1237. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  1238. *
  1239. * @example
  1240. * // Sort bounding spheres from back to front
  1241. * spheres.sort(function(a, b) {
  1242. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  1243. * });
  1244. */
  1245. BoundingSphere.prototype.distanceSquaredTo = function (cartesian) {
  1246. return BoundingSphere.distanceSquaredTo(this, cartesian);
  1247. };
  1248. /**
  1249. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  1250. * plus/minus the radius of the bounding sphere.
  1251. * <br>
  1252. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  1253. * closest and farthest planes from position that intersect the bounding sphere.
  1254. *
  1255. * @param {Cartesian3} position The position to calculate the distance from.
  1256. * @param {Cartesian3} direction The direction from position.
  1257. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  1258. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  1259. */
  1260. BoundingSphere.prototype.computePlaneDistances = function (
  1261. position,
  1262. direction,
  1263. result
  1264. ) {
  1265. return BoundingSphere.computePlaneDistances(
  1266. this,
  1267. position,
  1268. direction,
  1269. result
  1270. );
  1271. };
  1272. /**
  1273. * Determines whether or not a sphere is hidden from view by the occluder.
  1274. *
  1275. * @param {Occluder} occluder The occluder.
  1276. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  1277. */
  1278. BoundingSphere.prototype.isOccluded = function (occluder) {
  1279. return BoundingSphere.isOccluded(this, occluder);
  1280. };
  1281. /**
  1282. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  1283. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1284. *
  1285. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  1286. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  1287. */
  1288. BoundingSphere.prototype.equals = function (right) {
  1289. return BoundingSphere.equals(this, right);
  1290. };
  1291. /**
  1292. * Duplicates this BoundingSphere instance.
  1293. *
  1294. * @param {BoundingSphere} [result] The object onto which to store the result.
  1295. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1296. */
  1297. BoundingSphere.prototype.clone = function (result) {
  1298. return BoundingSphere.clone(this, result);
  1299. };
  1300. /**
  1301. * Computes the radius of the BoundingSphere.
  1302. * @returns {Number} The radius of the BoundingSphere.
  1303. */
  1304. BoundingSphere.prototype.volume = function () {
  1305. const radius = this.radius;
  1306. return volumeConstant * radius * radius * radius;
  1307. };
  1308. export default BoundingSphere;