Cesium3DTileset.js 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339
  1. import ApproximateTerrainHeights from '../Core/ApproximateTerrainHeights.js';
  2. import Cartesian2 from '../Core/Cartesian2.js';
  3. import Cartesian3 from '../Core/Cartesian3.js';
  4. import Cartographic from '../Core/Cartographic.js';
  5. import Check from '../Core/Check.js';
  6. import Credit from '../Core/Credit.js';
  7. import defaultValue from '../Core/defaultValue.js';
  8. import defined from '../Core/defined.js';
  9. import defineProperties from '../Core/defineProperties.js';
  10. import deprecationWarning from '../Core/deprecationWarning.js';
  11. import destroyObject from '../Core/destroyObject.js';
  12. import DeveloperError from '../Core/DeveloperError.js';
  13. import Ellipsoid from '../Core/Ellipsoid.js';
  14. import Event from '../Core/Event.js';
  15. import JulianDate from '../Core/JulianDate.js';
  16. import ManagedArray from '../Core/ManagedArray.js';
  17. import CesiumMath from '../Core/Math.js';
  18. import Matrix4 from '../Core/Matrix4.js';
  19. import Resource from '../Core/Resource.js';
  20. import RuntimeError from '../Core/RuntimeError.js';
  21. import Transforms from '../Core/Transforms.js';
  22. import ClearCommand from '../Renderer/ClearCommand.js';
  23. import Pass from '../Renderer/Pass.js';
  24. import RenderState from '../Renderer/RenderState.js';
  25. import when from '../ThirdParty/when.js';
  26. import Axis from './Axis.js';
  27. import Cesium3DTile from './Cesium3DTile.js';
  28. import Cesium3DTileColorBlendMode from './Cesium3DTileColorBlendMode.js';
  29. import Cesium3DTileContentState from './Cesium3DTileContentState.js';
  30. import Cesium3DTileOptimizations from './Cesium3DTileOptimizations.js';
  31. import Cesium3DTilePass from './Cesium3DTilePass.js';
  32. import Cesium3DTileRefine from './Cesium3DTileRefine.js';
  33. import Cesium3DTilesetCache from './Cesium3DTilesetCache.js';
  34. import Cesium3DTilesetHeatmap from './Cesium3DTilesetHeatmap.js';
  35. import Cesium3DTilesetStatistics from './Cesium3DTilesetStatistics.js';
  36. import Cesium3DTileStyleEngine from './Cesium3DTileStyleEngine.js';
  37. import ClippingPlaneCollection from './ClippingPlaneCollection.js';
  38. import LabelCollection from './LabelCollection.js';
  39. import PointCloudEyeDomeLighting from './PointCloudEyeDomeLighting.js';
  40. import PointCloudShading from './PointCloudShading.js';
  41. import SceneMode from './SceneMode.js';
  42. import ShadowMode from './ShadowMode.js';
  43. import StencilConstants from './StencilConstants.js';
  44. import TileBoundingRegion from './TileBoundingRegion.js';
  45. import TileBoundingSphere from './TileBoundingSphere.js';
  46. import TileOrientedBoundingBox from './TileOrientedBoundingBox.js';
  47. /**
  48. * A {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification|3D Tiles tileset},
  49. * used for streaming massive heterogeneous 3D geospatial datasets.
  50. *
  51. * @alias Cesium3DTileset
  52. * @constructor
  53. *
  54. * @param {Object} options Object with the following properties:
  55. * @param {Resource|String|Promise<Resource>|Promise<String>} options.url The url to a tileset JSON file.
  56. * @param {Boolean} [options.show=true] Determines if the tileset will be shown.
  57. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] A 4x4 transformation matrix that transforms the tileset's root tile.
  58. * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the tileset casts or receives shadows from each light source.
  59. * @param {Number} [options.maximumScreenSpaceError=16] The maximum screen space error used to drive level of detail refinement.
  60. * @param {Number} [options.maximumMemoryUsage=512] The maximum amount of memory in MB that can be used by the tileset.
  61. * @param {Boolean} [options.cullWithChildrenBounds=true] Optimization option. Whether to cull tiles using the union of their children bounding volumes.
  62. * @param {Boolean} [options.cullRequestsWhileMoving=true] Optimization option. Don't request tiles that will likely be unused when they come back because of the camera's movement.
  63. * @param {Number} [options.cullRequestsWhileMovingMultiplier=60.0] Optimization option. Multiplier used in culling requests while moving. Larger is more aggressive culling, smaller less aggressive culling.
  64. * @param {Boolean} [options.preloadWhenHidden=false] Preload tiles when <code>tileset.show</code> is <code>false</code>. Loads tiles as if the tileset is visible but does not render them.
  65. * @param {Boolean} [options.preloadFlightDestinations=true] Optimization option. Preload tiles at the camera's flight destination while the camera is in flight.
  66. * @param {Boolean} [options.preferLeaves=false] Optimization option. Prefer loading of leaves first.
  67. * @param {Boolean} [options.dynamicScreenSpaceError=false] Optimization option. Reduce the screen space error for tiles that are further away from the camera.
  68. * @param {Number} [options.dynamicScreenSpaceErrorDensity=0.00278] Density used to adjust the dynamic screen space error, similar to fog density.
  69. * @param {Number} [options.dynamicScreenSpaceErrorFactor=4.0] A factor used to increase the computed dynamic screen space error.
  70. * @param {Number} [options.dynamicScreenSpaceErrorHeightFalloff=0.25] A ratio of the tileset's height at which the density starts to falloff.
  71. * @param {Number} [options.progressiveResolutionHeightFraction=0.3] Optimization option. If between (0.0, 0.5], tiles at or above the screen space error for the reduced screen resolution of <code>progressiveResolutionHeightFraction*screenHeight</code> will be prioritized first. This can help get a quick layer of tiles down while full resolution tiles continue to load.
  72. * @param {Boolean} [options.foveatedScreenSpaceError=true] Optimization option. Prioritize loading tiles in the center of the screen by temporarily raising the screen space error for tiles around the edge of the screen. Screen space error returns to normal once all the tiles in the center of the screen as determined by the {@link Cesium3DTileset#foveatedConeSize} are loaded.
  73. * @param {Number} [options.foveatedConeSize=0.1] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred. Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and their screen space error. This is controlled by {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}. Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, disabling the effect.
  74. * @param {Number} [options.foveatedMinimumScreenSpaceErrorRelaxation=0.0] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone. The screen space error will be raised starting with tileset value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}.
  75. * @param {Cesium3DTileset~foveatedInterpolationCallback} [options.foveatedInterpolationCallback=Math.lerp] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how much to raise the screen space error for tiles outside the foveated cone, interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}
  76. * @param {Number} [options.foveatedTimeDelay=0.2] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how long in seconds to wait after the camera stops moving before deferred tiles start loading in. This time delay prevents requesting tiles around the edges of the screen when the camera is moving. Setting this to 0.0 will immediately request all tiles in any given view.
  77. * @param {Boolean} [options.skipLevelOfDetail=true] Optimization option. Determines if level of detail skipping should be applied during the traversal.
  78. * @param {Number} [options.baseScreenSpaceError=1024] When <code>skipLevelOfDetail</code> is <code>true</code>, the screen space error that must be reached before skipping levels of detail.
  79. * @param {Number} [options.skipScreenSpaceErrorFactor=16] When <code>skipLevelOfDetail</code> is <code>true</code>, a multiplier defining the minimum screen space error to skip. Used in conjunction with <code>skipLevels</code> to determine which tiles to load.
  80. * @param {Number} [options.skipLevels=1] When <code>skipLevelOfDetail</code> is <code>true</code>, a constant defining the minimum number of levels to skip when loading tiles. When it is 0, no levels are skipped. Used in conjunction with <code>skipScreenSpaceErrorFactor</code> to determine which tiles to load.
  81. * @param {Boolean} [options.immediatelyLoadDesiredLevelOfDetail=false] When <code>skipLevelOfDetail</code> is <code>true</code>, only tiles that meet the maximum screen space error will ever be downloaded. Skipping factors are ignored and just the desired tiles are loaded.
  82. * @param {Boolean} [options.loadSiblings=false] When <code>skipLevelOfDetail</code> is <code>true</code>, determines whether siblings of visible tiles are always downloaded during traversal.
  83. * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
  84. * @param {ClassificationType} [options.classificationType] Determines whether terrain, 3D Tiles or both will be classified by this tileset. See {@link Cesium3DTileset#classificationType} for details about restrictions and limitations.
  85. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid determining the size and shape of the globe.
  86. * @param {Object} [options.pointCloudShading] Options for constructing a {@link PointCloudShading} object to control point attenuation based on geometric error and lighting.
  87. * @param {Cartesian2} [options.imageBasedLightingFactor=new Cartesian2(1.0, 1.0)] Scales the diffuse and specular image-based lighting from the earth, sky, atmosphere and star skybox.
  88. * @param {Cartesian3} [options.lightColor] The color and intensity of the sunlight used to shade models.
  89. * @param {Number} [options.luminanceAtZenith=0.2] The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map.
  90. * @param {Cartesian3[]} [options.sphericalHarmonicCoefficients] The third order spherical harmonic coefficients used for the diffuse color of image-based lighting.
  91. * @param {String} [options.specularEnvironmentMaps] A URL to a KTX file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
  92. * @param {String} [options.debugHeatmapTilePropertyName] The tile variable to colorize as a heatmap. All rendered tiles will be colorized relative to each other's specified variable value.
  93. * @param {Boolean} [options.debugFreezeFrame=false] For debugging only. Determines if only the tiles from last frame should be used for rendering.
  94. * @param {Boolean} [options.debugColorizeTiles=false] For debugging only. When true, assigns a random color to each tile.
  95. * @param {Boolean} [options.debugWireframe=false] For debugging only. When true, render's each tile's content as a wireframe.
  96. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. When true, renders the bounding volume for each tile.
  97. * @param {Boolean} [options.debugShowContentBoundingVolume=false] For debugging only. When true, renders the bounding volume for each tile's content.
  98. * @param {Boolean} [options.debugShowViewerRequestVolume=false] For debugging only. When true, renders the viewer request volume for each tile.
  99. * @param {Boolean} [options.debugShowGeometricError=false] For debugging only. When true, draws labels to indicate the geometric error of each tile.
  100. * @param {Boolean} [options.debugShowRenderingStatistics=false] For debugging only. When true, draws labels to indicate the number of commands, points, triangles and features for each tile.
  101. * @param {Boolean} [options.debugShowMemoryUsage=false] For debugging only. When true, draws labels to indicate the texture and geometry memory in megabytes used by each tile.
  102. * @param {Boolean} [options.debugShowUrl=false] For debugging only. When true, draws labels to indicate the url of each tile.
  103. *
  104. * @exception {DeveloperError} The tileset must be 3D Tiles version 0.0 or 1.0.
  105. *
  106. * @example
  107. * var tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
  108. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json'
  109. * }));
  110. *
  111. * @example
  112. * // Common setting for the skipLevelOfDetail optimization
  113. * var tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
  114. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json',
  115. * skipLevelOfDetail : true,
  116. * baseScreenSpaceError : 1024,
  117. * skipScreenSpaceErrorFactor : 16,
  118. * skipLevels : 1,
  119. * immediatelyLoadDesiredLevelOfDetail : false,
  120. * loadSiblings : false,
  121. * cullWithChildrenBounds : true
  122. * }));
  123. *
  124. * @example
  125. * // Common settings for the dynamicScreenSpaceError optimization
  126. * var tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
  127. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json',
  128. * dynamicScreenSpaceError : true,
  129. * dynamicScreenSpaceErrorDensity : 0.00278,
  130. * dynamicScreenSpaceErrorFactor : 4.0,
  131. * dynamicScreenSpaceErrorHeightFalloff : 0.25
  132. * }));
  133. *
  134. * @see {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification|3D Tiles specification}
  135. */
  136. function Cesium3DTileset(options) {
  137. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  138. //>>includeStart('debug', pragmas.debug);
  139. Check.defined('options.url', options.url);
  140. //>>includeEnd('debug');
  141. this._url = undefined;
  142. this._basePath = undefined;
  143. this._root = undefined;
  144. this._asset = undefined; // Metadata for the entire tileset
  145. this._properties = undefined; // Metadata for per-model/point/etc properties
  146. this._geometricError = undefined; // Geometric error when the tree is not rendered at all
  147. this._extensionsUsed = undefined;
  148. this._gltfUpAxis = undefined;
  149. this._cache = new Cesium3DTilesetCache();
  150. this._processingQueue = [];
  151. this._selectedTiles = [];
  152. this._emptyTiles = [];
  153. this._requestedTiles = [];
  154. this._selectedTilesToStyle = [];
  155. this._loadTimestamp = undefined;
  156. this._timeSinceLoad = 0.0;
  157. this._updatedVisibilityFrame = 0;
  158. this._extras = undefined;
  159. this._credits = undefined;
  160. this._cullWithChildrenBounds = defaultValue(options.cullWithChildrenBounds, true);
  161. this._allTilesAdditive = true;
  162. this._hasMixedContent = false;
  163. this._stencilClearCommand = undefined;
  164. this._backfaceCommands = new ManagedArray();
  165. this._maximumScreenSpaceError = defaultValue(options.maximumScreenSpaceError, 16);
  166. this._maximumMemoryUsage = defaultValue(options.maximumMemoryUsage, 512);
  167. this._styleEngine = new Cesium3DTileStyleEngine();
  168. this._modelMatrix = defined(options.modelMatrix) ? Matrix4.clone(options.modelMatrix) : Matrix4.clone(Matrix4.IDENTITY);
  169. this._statistics = new Cesium3DTilesetStatistics();
  170. this._statisticsLast = new Cesium3DTilesetStatistics();
  171. this._statisticsPerPass = new Array(Cesium3DTilePass.NUMBER_OF_PASSES);
  172. for (var i = 0; i < Cesium3DTilePass.NUMBER_OF_PASSES; ++i) {
  173. this._statisticsPerPass[i] = new Cesium3DTilesetStatistics();
  174. }
  175. this._requestedTilesInFlight = [];
  176. this._maximumPriority = { foveatedFactor: -Number.MAX_VALUE, depth: -Number.MAX_VALUE, distance: -Number.MAX_VALUE, reverseScreenSpaceError: -Number.MAX_VALUE };
  177. this._minimumPriority = { foveatedFactor: Number.MAX_VALUE, depth: Number.MAX_VALUE, distance: Number.MAX_VALUE, reverseScreenSpaceError: Number.MAX_VALUE };
  178. this._heatmap = new Cesium3DTilesetHeatmap(options.debugHeatmapTilePropertyName);
  179. /**
  180. * Optimization option. Don't request tiles that will likely be unused when they come back because of the camera's movement.
  181. *
  182. * @type {Boolean}
  183. * @default true
  184. */
  185. this.cullRequestsWhileMoving = defaultValue(options.cullRequestsWhileMoving, true);
  186. /**
  187. * Optimization option. Multiplier used in culling requests while moving. Larger is more aggressive culling, smaller less aggressive culling.
  188. *
  189. * @type {Number}
  190. * @default 60.0
  191. */
  192. this.cullRequestsWhileMovingMultiplier = defaultValue(options.cullRequestsWhileMovingMultiplier, 60.0);
  193. /**
  194. * Optimization option. If between (0.0, 0.5], tiles at or above the screen space error for the reduced screen resolution of <code>progressiveResolutionHeightFraction*screenHeight</code> will be prioritized first. This can help get a quick layer of tiles down while full resolution tiles continue to load.
  195. *
  196. * @type {Number}
  197. * @default 0.3
  198. */
  199. this.progressiveResolutionHeightFraction = CesiumMath.clamp(defaultValue(options.progressiveResolutionHeightFraction, 0.3), 0.0, 0.5);
  200. /**
  201. * Optimization option. Prefer loading of leaves first.
  202. *
  203. * @type {Boolean}
  204. * @default false
  205. */
  206. this.preferLeaves = defaultValue(options.preferLeaves, false);
  207. this._tilesLoaded = false;
  208. this._initialTilesLoaded = false;
  209. this._tileDebugLabels = undefined;
  210. this._readyPromise = when.defer();
  211. this._classificationType = options.classificationType;
  212. this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  213. this._initialClippingPlanesOriginMatrix = Matrix4.IDENTITY; // Computed from the tileset JSON.
  214. this._clippingPlanesOriginMatrix = undefined; // Combines the above with any run-time transforms.
  215. this._clippingPlanesOriginMatrixDirty = true;
  216. /**
  217. * Preload tiles when <code>tileset.show</code> is <code>false</code>. Loads tiles as if the tileset is visible but does not render them.
  218. *
  219. * @type {Boolean}
  220. * @default false
  221. */
  222. this.preloadWhenHidden = defaultValue(options.preloadWhenHidden, false);
  223. /**
  224. * Optimization option. Fetch tiles at the camera's flight destination while the camera is in flight.
  225. *
  226. * @type {Boolean}
  227. * @default true
  228. */
  229. this.preloadFlightDestinations = defaultValue(options.preloadFlightDestinations, true);
  230. this._pass = undefined; // Cesium3DTilePass
  231. /**
  232. * Optimization option. Whether the tileset should refine based on a dynamic screen space error. Tiles that are further
  233. * away will be rendered with lower detail than closer tiles. This improves performance by rendering fewer
  234. * tiles and making less requests, but may result in a slight drop in visual quality for tiles in the distance.
  235. * The algorithm is biased towards "street views" where the camera is close to the ground plane of the tileset and looking
  236. * at the horizon. In addition results are more accurate for tightly fitting bounding volumes like box and region.
  237. *
  238. * @type {Boolean}
  239. * @default false
  240. */
  241. this.dynamicScreenSpaceError = defaultValue(options.dynamicScreenSpaceError, false);
  242. /**
  243. * Optimization option. Prioritize loading tiles in the center of the screen by temporarily raising the
  244. * screen space error for tiles around the edge of the screen. Screen space error returns to normal once all
  245. * the tiles in the center of the screen as determined by the {@link Cesium3DTileset#foveatedConeSize} are loaded.
  246. *
  247. * @type {Boolean}
  248. * @default true
  249. */
  250. this.foveatedScreenSpaceError = defaultValue(options.foveatedScreenSpaceError, true);
  251. this._foveatedConeSize = defaultValue(options.foveatedConeSize, 0.1);
  252. this._foveatedMinimumScreenSpaceErrorRelaxation = defaultValue(options.foveatedMinimumScreenSpaceErrorRelaxation, 0.0);
  253. /**
  254. * Gets a function that will update the foveated screen space error for a tile.
  255. *
  256. * @type {Cesium3DTileset~foveatedInterpolationCallback} A callback to control how much to raise the screen space error for tiles outside the foveated cone, interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}.
  257. */
  258. this.foveatedInterpolationCallback = defaultValue(options.foveatedInterpolationCallback, CesiumMath.lerp);
  259. /**
  260. * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control
  261. * how long in seconds to wait after the camera stops moving before deferred tiles start loading in.
  262. * This time delay prevents requesting tiles around the edges of the screen when the camera is moving.
  263. * Setting this to 0.0 will immediately request all tiles in any given view.
  264. *
  265. * @type {Number}
  266. * @default 0.2
  267. */
  268. this.foveatedTimeDelay = defaultValue(options.foveatedTimeDelay, 0.2);
  269. /**
  270. * A scalar that determines the density used to adjust the dynamic screen space error, similar to {@link Fog}. Increasing this
  271. * value has the effect of increasing the maximum screen space error for all tiles, but in a non-linear fashion.
  272. * The error starts at 0.0 and increases exponentially until a midpoint is reached, and then approaches 1.0 asymptotically.
  273. * This has the effect of keeping high detail in the closer tiles and lower detail in the further tiles, with all tiles
  274. * beyond a certain distance all roughly having an error of 1.0.
  275. * <p>
  276. * The dynamic error is in the range [0.0, 1.0) and is multiplied by <code>dynamicScreenSpaceErrorFactor</code> to produce the
  277. * final dynamic error. This dynamic error is then subtracted from the tile's actual screen space error.
  278. * </p>
  279. * <p>
  280. * Increasing <code>dynamicScreenSpaceErrorDensity</code> has the effect of moving the error midpoint closer to the camera.
  281. * It is analogous to moving fog closer to the camera.
  282. * </p>
  283. *
  284. * @type {Number}
  285. * @default 0.00278
  286. */
  287. this.dynamicScreenSpaceErrorDensity = 0.00278;
  288. /**
  289. * A factor used to increase the screen space error of tiles for dynamic screen space error. As this value increases less tiles
  290. * are requested for rendering and tiles in the distance will have lower detail. If set to zero, the feature will be disabled.
  291. *
  292. * @type {Number}
  293. * @default 4.0
  294. */
  295. this.dynamicScreenSpaceErrorFactor = 4.0;
  296. /**
  297. * A ratio of the tileset's height at which the density starts to falloff. If the camera is below this height the
  298. * full computed density is applied, otherwise the density falls off. This has the effect of higher density at
  299. * street level views.
  300. * <p>
  301. * Valid values are between 0.0 and 1.0.
  302. * </p>
  303. *
  304. * @type {Number}
  305. * @default 0.25
  306. */
  307. this.dynamicScreenSpaceErrorHeightFalloff = 0.25;
  308. this._dynamicScreenSpaceErrorComputedDensity = 0.0; // Updated based on the camera position and direction
  309. /**
  310. * Determines whether the tileset casts or receives shadows from each light source.
  311. * <p>
  312. * Enabling shadows has a performance impact. A tileset that casts shadows must be rendered twice, once from the camera and again from the light's point of view.
  313. * </p>
  314. * <p>
  315. * Shadows are rendered only when {@link Viewer#shadows} is <code>true</code>.
  316. * </p>
  317. *
  318. * @type {ShadowMode}
  319. * @default ShadowMode.ENABLED
  320. */
  321. this.shadows = defaultValue(options.shadows, ShadowMode.ENABLED);
  322. /**
  323. * Determines if the tileset will be shown.
  324. *
  325. * @type {Boolean}
  326. * @default true
  327. */
  328. this.show = defaultValue(options.show, true);
  329. /**
  330. * Defines how per-feature colors set from the Cesium API or declarative styling blend with the source colors from
  331. * the original feature, e.g. glTF material or per-point color in the tile.
  332. *
  333. * @type {Cesium3DTileColorBlendMode}
  334. * @default Cesium3DTileColorBlendMode.HIGHLIGHT
  335. */
  336. this.colorBlendMode = Cesium3DTileColorBlendMode.HIGHLIGHT;
  337. /**
  338. * Defines the value used to linearly interpolate between the source color and feature color when the {@link Cesium3DTileset#colorBlendMode} is <code>MIX</code>.
  339. * A value of 0.0 results in the source color while a value of 1.0 results in the feature color, with any value in-between
  340. * resulting in a mix of the source color and feature color.
  341. *
  342. * @type {Number}
  343. * @default 0.5
  344. */
  345. this.colorBlendAmount = 0.5;
  346. /**
  347. * Options for controlling point size based on geometric error and eye dome lighting.
  348. * @type {PointCloudShading}
  349. */
  350. this.pointCloudShading = new PointCloudShading(options.pointCloudShading);
  351. this._pointCloudEyeDomeLighting = new PointCloudEyeDomeLighting();
  352. /**
  353. * The event fired to indicate progress of loading new tiles. This event is fired when a new tile
  354. * is requested, when a requested tile is finished downloading, and when a downloaded tile has been
  355. * processed and is ready to render.
  356. * <p>
  357. * The number of pending tile requests, <code>numberOfPendingRequests</code>, and number of tiles
  358. * processing, <code>numberOfTilesProcessing</code> are passed to the event listener.
  359. * </p>
  360. * <p>
  361. * This event is fired at the end of the frame after the scene is rendered.
  362. * </p>
  363. *
  364. * @type {Event}
  365. * @default new Event()
  366. *
  367. * @example
  368. * tileset.loadProgress.addEventListener(function(numberOfPendingRequests, numberOfTilesProcessing) {
  369. * if ((numberOfPendingRequests === 0) && (numberOfTilesProcessing === 0)) {
  370. * console.log('Stopped loading');
  371. * return;
  372. * }
  373. *
  374. * console.log('Loading: requests: ' + numberOfPendingRequests + ', processing: ' + numberOfTilesProcessing);
  375. * });
  376. */
  377. this.loadProgress = new Event();
  378. /**
  379. * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. The tileset
  380. * is completely loaded for this view.
  381. * <p>
  382. * This event is fired at the end of the frame after the scene is rendered.
  383. * </p>
  384. *
  385. * @type {Event}
  386. * @default new Event()
  387. *
  388. * @example
  389. * tileset.allTilesLoaded.addEventListener(function() {
  390. * console.log('All tiles are loaded');
  391. * });
  392. *
  393. * @see Cesium3DTileset#tilesLoaded
  394. */
  395. this.allTilesLoaded = new Event();
  396. /**
  397. * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. This event
  398. * is fired once when all tiles in the initial view are loaded.
  399. * <p>
  400. * This event is fired at the end of the frame after the scene is rendered.
  401. * </p>
  402. *
  403. * @type {Event}
  404. * @default new Event()
  405. *
  406. * @example
  407. * tileset.initialTilesLoaded.addEventListener(function() {
  408. * console.log('Initial tiles are loaded');
  409. * });
  410. *
  411. * @see Cesium3DTileset#allTilesLoaded
  412. */
  413. this.initialTilesLoaded = new Event();
  414. /**
  415. * The event fired to indicate that a tile's content was loaded.
  416. * <p>
  417. * The loaded {@link Cesium3DTile} is passed to the event listener.
  418. * </p>
  419. * <p>
  420. * This event is fired during the tileset traversal while the frame is being rendered
  421. * so that updates to the tile take effect in the same frame. Do not create or modify
  422. * Cesium entities or primitives during the event listener.
  423. * </p>
  424. *
  425. * @type {Event}
  426. * @default new Event()
  427. *
  428. * @example
  429. * tileset.tileLoad.addEventListener(function(tile) {
  430. * console.log('A tile was loaded.');
  431. * });
  432. */
  433. this.tileLoad = new Event();
  434. /**
  435. * The event fired to indicate that a tile's content was unloaded.
  436. * <p>
  437. * The unloaded {@link Cesium3DTile} is passed to the event listener.
  438. * </p>
  439. * <p>
  440. * This event is fired immediately before the tile's content is unloaded while the frame is being
  441. * rendered so that the event listener has access to the tile's content. Do not create
  442. * or modify Cesium entities or primitives during the event listener.
  443. * </p>
  444. *
  445. * @type {Event}
  446. * @default new Event()
  447. *
  448. * @example
  449. * tileset.tileUnload.addEventListener(function(tile) {
  450. * console.log('A tile was unloaded from the cache.');
  451. * });
  452. *
  453. * @see Cesium3DTileset#maximumMemoryUsage
  454. * @see Cesium3DTileset#trimLoadedTiles
  455. */
  456. this.tileUnload = new Event();
  457. /**
  458. * The event fired to indicate that a tile's content failed to load.
  459. * <p>
  460. * If there are no event listeners, error messages will be logged to the console.
  461. * </p>
  462. * <p>
  463. * The error object passed to the listener contains two properties:
  464. * <ul>
  465. * <li><code>url</code>: the url of the failed tile.</li>
  466. * <li><code>message</code>: the error message.</li>
  467. * </ul>
  468. *
  469. * @type {Event}
  470. * @default new Event()
  471. *
  472. * @example
  473. * tileset.tileFailed.addEventListener(function(error) {
  474. * console.log('An error occurred loading tile: ' + error.url);
  475. * console.log('Error: ' + error.message);
  476. * });
  477. */
  478. this.tileFailed = new Event();
  479. /**
  480. * This event fires once for each visible tile in a frame. This can be used to manually
  481. * style a tileset.
  482. * <p>
  483. * The visible {@link Cesium3DTile} is passed to the event listener.
  484. * </p>
  485. * <p>
  486. * This event is fired during the tileset traversal while the frame is being rendered
  487. * so that updates to the tile take effect in the same frame. Do not create or modify
  488. * Cesium entities or primitives during the event listener.
  489. * </p>
  490. *
  491. * @type {Event}
  492. * @default new Event()
  493. *
  494. * @example
  495. * tileset.tileVisible.addEventListener(function(tile) {
  496. * if (tile.content instanceof Cesium.Batched3DModel3DTileContent) {
  497. * console.log('A Batched 3D Model tile is visible.');
  498. * }
  499. * });
  500. *
  501. * @example
  502. * // Apply a red style and then manually set random colors for every other feature when the tile becomes visible.
  503. * tileset.style = new Cesium.Cesium3DTileStyle({
  504. * color : 'color("red")'
  505. * });
  506. * tileset.tileVisible.addEventListener(function(tile) {
  507. * var content = tile.content;
  508. * var featuresLength = content.featuresLength;
  509. * for (var i = 0; i < featuresLength; i+=2) {
  510. * content.getFeature(i).color = Cesium.Color.fromRandom();
  511. * }
  512. * });
  513. */
  514. this.tileVisible = new Event();
  515. /**
  516. * Optimization option. Determines if level of detail skipping should be applied during the traversal.
  517. * <p>
  518. * The common strategy for replacement-refinement traversal is to store all levels of the tree in memory and require
  519. * all children to be loaded before the parent can refine. With this optimization levels of the tree can be skipped
  520. * entirely and children can be rendered alongside their parents. The tileset requires significantly less memory when
  521. * using this optimization.
  522. * </p>
  523. *
  524. * @type {Boolean}
  525. * @default true
  526. */
  527. this.skipLevelOfDetail = defaultValue(options.skipLevelOfDetail, true);
  528. this._skipLevelOfDetail = this.skipLevelOfDetail;
  529. this._disableSkipLevelOfDetail = false;
  530. /**
  531. * The screen space error that must be reached before skipping levels of detail.
  532. * <p>
  533. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  534. * </p>
  535. *
  536. * @type {Number}
  537. * @default 1024
  538. */
  539. this.baseScreenSpaceError = defaultValue(options.baseScreenSpaceError, 1024);
  540. /**
  541. * Multiplier defining the minimum screen space error to skip.
  542. * For example, if a tile has screen space error of 100, no tiles will be loaded unless they
  543. * are leaves or have a screen space error <code><= 100 / skipScreenSpaceErrorFactor</code>.
  544. * <p>
  545. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  546. * </p>
  547. *
  548. * @type {Number}
  549. * @default 16
  550. */
  551. this.skipScreenSpaceErrorFactor = defaultValue(options.skipScreenSpaceErrorFactor, 16);
  552. /**
  553. * Constant defining the minimum number of levels to skip when loading tiles. When it is 0, no levels are skipped.
  554. * For example, if a tile is level 1, no tiles will be loaded unless they are at level greater than 2.
  555. * <p>
  556. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  557. * </p>
  558. *
  559. * @type {Number}
  560. * @default 1
  561. */
  562. this.skipLevels = defaultValue(options.skipLevels, 1);
  563. /**
  564. * When true, only tiles that meet the maximum screen space error will ever be downloaded.
  565. * Skipping factors are ignored and just the desired tiles are loaded.
  566. * <p>
  567. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  568. * </p>
  569. *
  570. * @type {Boolean}
  571. * @default false
  572. */
  573. this.immediatelyLoadDesiredLevelOfDetail = defaultValue(options.immediatelyLoadDesiredLevelOfDetail, false);
  574. /**
  575. * Determines whether siblings of visible tiles are always downloaded during traversal.
  576. * This may be useful for ensuring that tiles are already available when the viewer turns left/right.
  577. * <p>
  578. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  579. * </p>
  580. *
  581. * @type {Boolean}
  582. * @default false
  583. */
  584. this.loadSiblings = defaultValue(options.loadSiblings, false);
  585. this._clippingPlanes = undefined;
  586. this.clippingPlanes = options.clippingPlanes;
  587. this._imageBasedLightingFactor = new Cartesian2(1.0, 1.0);
  588. Cartesian2.clone(options.imageBasedLightingFactor, this._imageBasedLightingFactor);
  589. /**
  590. * The color and intensity of the sunlight used to shade a model.
  591. * <p>
  592. * For example, disabling additional light sources by setting <code>model.imageBasedLightingFactor = new Cartesian2(0.0, 0.0)</code> will make the
  593. * model much darker. Here, increasing the intensity of the light source will make the model brighter.
  594. * </p>
  595. *
  596. * @type {Cartesian3}
  597. * @default undefined
  598. */
  599. this.lightColor = options.lightColor;
  600. /**
  601. * The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map.
  602. * This is used when {@link Cesium3DTileset#specularEnvironmentMaps} and {@link Cesium3DTileset#sphericalHarmonicCoefficients} are not defined.
  603. *
  604. * @type Number
  605. *
  606. * @default 0.2
  607. *
  608. */
  609. this.luminanceAtZenith = defaultValue(options.luminanceAtZenith, 0.2);
  610. /**
  611. * The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. When <code>undefined</code>, a diffuse irradiance
  612. * computed from the atmosphere color is used.
  613. * <p>
  614. * There are nine <code>Cartesian3</code> coefficients.
  615. * The order of the coefficients is: L<sub>00</sub>, L<sub>1-1</sub>, L<sub>10</sub>, L<sub>11</sub>, L<sub>2-2</sub>, L<sub>2-1</sub>, L<sub>20</sub>, L<sub>21</sub>, L<sub>22</sub>
  616. * </p>
  617. *
  618. * These values can be obtained by preprocessing the environment map using the <code>cmgen</code> tool of
  619. * {@link https://github.com/google/filament/releases|Google's Filament project}. This will also generate a KTX file that can be
  620. * supplied to {@link Cesium3DTileset#specularEnvironmentMaps}.
  621. *
  622. * @type {Cartesian3[]}
  623. * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
  624. * @see {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf|An Efficient Representation for Irradiance Environment Maps}
  625. */
  626. this.sphericalHarmonicCoefficients = options.sphericalHarmonicCoefficients;
  627. /**
  628. * A URL to a KTX file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
  629. *
  630. * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
  631. * @type {String}
  632. * @see Cesium3DTileset#sphericalHarmonicCoefficients
  633. */
  634. this.specularEnvironmentMaps = options.specularEnvironmentMaps;
  635. /**
  636. * This property is for debugging only; it is not optimized for production use.
  637. * <p>
  638. * Determines if only the tiles from last frame should be used for rendering. This
  639. * effectively "freezes" the tileset to the previous frame so it is possible to zoom
  640. * out and see what was rendered.
  641. * </p>
  642. *
  643. * @type {Boolean}
  644. * @default false
  645. */
  646. this.debugFreezeFrame = defaultValue(options.debugFreezeFrame, false);
  647. /**
  648. * This property is for debugging only; it is not optimized for production use.
  649. * <p>
  650. * When true, assigns a random color to each tile. This is useful for visualizing
  651. * what features belong to what tiles, especially with additive refinement where features
  652. * from parent tiles may be interleaved with features from child tiles.
  653. * </p>
  654. *
  655. * @type {Boolean}
  656. * @default false
  657. */
  658. this.debugColorizeTiles = defaultValue(options.debugColorizeTiles, false);
  659. /**
  660. * This property is for debugging only; it is not optimized for production use.
  661. * <p>
  662. * When true, renders each tile's content as a wireframe.
  663. * </p>
  664. *
  665. * @type {Boolean}
  666. * @default false
  667. */
  668. this.debugWireframe = defaultValue(options.debugWireframe, false);
  669. /**
  670. * This property is for debugging only; it is not optimized for production use.
  671. * <p>
  672. * When true, renders the bounding volume for each visible tile. The bounding volume is
  673. * white if the tile has a content bounding volume or is empty; otherwise, it is red. Tiles that don't meet the
  674. * screen space error and are still refining to their descendants are yellow.
  675. * </p>
  676. *
  677. * @type {Boolean}
  678. * @default false
  679. */
  680. this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
  681. /**
  682. * This property is for debugging only; it is not optimized for production use.
  683. * <p>
  684. * When true, renders the bounding volume for each visible tile's content. The bounding volume is
  685. * blue if the tile has a content bounding volume; otherwise it is red.
  686. * </p>
  687. *
  688. * @type {Boolean}
  689. * @default false
  690. */
  691. this.debugShowContentBoundingVolume = defaultValue(options.debugShowContentBoundingVolume, false);
  692. /**
  693. * This property is for debugging only; it is not optimized for production use.
  694. * <p>
  695. * When true, renders the viewer request volume for each tile.
  696. * </p>
  697. *
  698. * @type {Boolean}
  699. * @default false
  700. */
  701. this.debugShowViewerRequestVolume = defaultValue(options.debugShowViewerRequestVolume, false);
  702. this._tileDebugLabels = undefined;
  703. this.debugPickedTileLabelOnly = false;
  704. this.debugPickedTile = undefined;
  705. this.debugPickPosition = undefined;
  706. /**
  707. * This property is for debugging only; it is not optimized for production use.
  708. * <p>
  709. * When true, draws labels to indicate the geometric error of each tile.
  710. * </p>
  711. *
  712. * @type {Boolean}
  713. * @default false
  714. */
  715. this.debugShowGeometricError = defaultValue(options.debugShowGeometricError, false);
  716. /**
  717. * This property is for debugging only; it is not optimized for production use.
  718. * <p>
  719. * When true, draws labels to indicate the number of commands, points, triangles and features of each tile.
  720. * </p>
  721. *
  722. * @type {Boolean}
  723. * @default false
  724. */
  725. this.debugShowRenderingStatistics = defaultValue(options.debugShowRenderingStatistics, false);
  726. /**
  727. * This property is for debugging only; it is not optimized for production use.
  728. * <p>
  729. * When true, draws labels to indicate the geometry and texture memory usage of each tile.
  730. * </p>
  731. *
  732. * @type {Boolean}
  733. * @default false
  734. */
  735. this.debugShowMemoryUsage = defaultValue(options.debugShowMemoryUsage, false);
  736. /**
  737. * This property is for debugging only; it is not optimized for production use.
  738. * <p>
  739. * When true, draws labels to indicate the url of each tile.
  740. * </p>
  741. *
  742. * @type {Boolean}
  743. * @default false
  744. */
  745. this.debugShowUrl = defaultValue(options.debugShowUrl, false);
  746. var that = this;
  747. var resource;
  748. when(options.url)
  749. .then(function(url) {
  750. var basePath;
  751. resource = Resource.createIfNeeded(url);
  752. // ion resources have a credits property we can use for additional attribution.
  753. that._credits = resource.credits;
  754. if (resource.extension === 'json') {
  755. basePath = resource.getBaseUri(true);
  756. } else if (resource.isDataUri) {
  757. basePath = '';
  758. }
  759. that._url = resource.url;
  760. that._basePath = basePath;
  761. return Cesium3DTileset.loadJson(resource);
  762. })
  763. .then(function(tilesetJson) {
  764. that._root = that.loadTileset(resource, tilesetJson);
  765. var gltfUpAxis = defined(tilesetJson.asset.gltfUpAxis) ? Axis.fromName(tilesetJson.asset.gltfUpAxis) : Axis.Y;
  766. var asset = tilesetJson.asset;
  767. that._asset = asset;
  768. that._properties = tilesetJson.properties;
  769. that._geometricError = tilesetJson.geometricError;
  770. that._extensionsUsed = tilesetJson.extensionsUsed;
  771. that._gltfUpAxis = gltfUpAxis;
  772. that._extras = tilesetJson.extras;
  773. var extras = asset.extras;
  774. if (defined(extras) && defined(extras.cesium) && defined(extras.cesium.credits)) {
  775. var extraCredits = extras.cesium.credits;
  776. var credits = that._credits;
  777. if (!defined(credits)) {
  778. credits = [];
  779. that._credits = credits;
  780. }
  781. for (var i = 0; i < extraCredits.length; ++i) {
  782. var credit = extraCredits[i];
  783. credits.push(new Credit(credit.html, credit.showOnScreen));
  784. }
  785. }
  786. // Save the original, untransformed bounding volume position so we can apply
  787. // the tile transform and model matrix at run time
  788. var boundingVolume = that._root.createBoundingVolume(tilesetJson.root.boundingVolume, Matrix4.IDENTITY);
  789. var clippingPlanesOrigin = boundingVolume.boundingSphere.center;
  790. // If this origin is above the surface of the earth
  791. // we want to apply an ENU orientation as our best guess of orientation.
  792. // Otherwise, we assume it gets its position/orientation completely from the
  793. // root tile transform and the tileset's model matrix
  794. var originCartographic = that._ellipsoid.cartesianToCartographic(clippingPlanesOrigin);
  795. if (defined(originCartographic) && (originCartographic.height > ApproximateTerrainHeights._defaultMinTerrainHeight)) {
  796. that._initialClippingPlanesOriginMatrix = Transforms.eastNorthUpToFixedFrame(clippingPlanesOrigin);
  797. }
  798. that._clippingPlanesOriginMatrix = Matrix4.clone(that._initialClippingPlanesOriginMatrix);
  799. that._readyPromise.resolve(that);
  800. }).otherwise(function(error) {
  801. that._readyPromise.reject(error);
  802. });
  803. }
  804. defineProperties(Cesium3DTileset.prototype, {
  805. /**
  806. * Gets the tileset's asset object property, which contains metadata about the tileset.
  807. * <p>
  808. * See the {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification#reference-asset|asset schema reference}
  809. * in the 3D Tiles spec for the full set of properties.
  810. * </p>
  811. *
  812. * @memberof Cesium3DTileset.prototype
  813. *
  814. * @type {Object}
  815. * @readonly
  816. *
  817. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  818. */
  819. asset : {
  820. get : function() {
  821. //>>includeStart('debug', pragmas.debug);
  822. if (!this.ready) {
  823. throw new DeveloperError('The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.');
  824. }
  825. //>>includeEnd('debug');
  826. return this._asset;
  827. }
  828. },
  829. /**
  830. * The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
  831. *
  832. * @memberof Cesium3DTileset.prototype
  833. *
  834. * @type {ClippingPlaneCollection}
  835. */
  836. clippingPlanes : {
  837. get : function() {
  838. return this._clippingPlanes;
  839. },
  840. set : function(value) {
  841. ClippingPlaneCollection.setOwner(value, this, '_clippingPlanes');
  842. }
  843. },
  844. /**
  845. * Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.
  846. * <p>
  847. * See the {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification#reference-properties|properties schema reference}
  848. * in the 3D Tiles spec for the full set of properties.
  849. * </p>
  850. *
  851. * @memberof Cesium3DTileset.prototype
  852. *
  853. * @type {Object}
  854. * @readonly
  855. *
  856. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  857. *
  858. * @example
  859. * console.log('Maximum building height: ' + tileset.properties.height.maximum);
  860. * console.log('Minimum building height: ' + tileset.properties.height.minimum);
  861. *
  862. * @see Cesium3DTileFeature#getProperty
  863. * @see Cesium3DTileFeature#setProperty
  864. */
  865. properties : {
  866. get : function() {
  867. //>>includeStart('debug', pragmas.debug);
  868. if (!this.ready) {
  869. throw new DeveloperError('The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.');
  870. }
  871. //>>includeEnd('debug');
  872. return this._properties;
  873. }
  874. },
  875. /**
  876. * When <code>true</code>, the tileset's root tile is loaded and the tileset is ready to render.
  877. * This is set to <code>true</code> right before {@link Cesium3DTileset#readyPromise} is resolved.
  878. *
  879. * @memberof Cesium3DTileset.prototype
  880. *
  881. * @type {Boolean}
  882. * @readonly
  883. *
  884. * @default false
  885. */
  886. ready : {
  887. get : function() {
  888. return defined(this._root);
  889. }
  890. },
  891. /**
  892. * Gets the promise that will be resolved when the tileset's root tile is loaded and the tileset is ready to render.
  893. * <p>
  894. * This promise is resolved at the end of the frame before the first frame the tileset is rendered in.
  895. * </p>
  896. *
  897. * @memberof Cesium3DTileset.prototype
  898. *
  899. * @type {Promise.<Cesium3DTileset>}
  900. * @readonly
  901. *
  902. * @example
  903. * tileset.readyPromise.then(function(tileset) {
  904. * // tile.properties is not defined until readyPromise resolves.
  905. * var properties = tileset.properties;
  906. * if (Cesium.defined(properties)) {
  907. * for (var name in properties) {
  908. * console.log(properties[name]);
  909. * }
  910. * }
  911. * });
  912. */
  913. readyPromise : {
  914. get : function() {
  915. return this._readyPromise.promise;
  916. }
  917. },
  918. /**
  919. * When <code>true</code>, all tiles that meet the screen space error this frame are loaded. The tileset is
  920. * completely loaded for this view.
  921. *
  922. * @memberof Cesium3DTileset.prototype
  923. *
  924. * @type {Boolean}
  925. * @readonly
  926. *
  927. * @default false
  928. *
  929. * @see Cesium3DTileset#allTilesLoaded
  930. */
  931. tilesLoaded : {
  932. get : function() {
  933. return this._tilesLoaded;
  934. }
  935. },
  936. /**
  937. * The url to a tileset JSON file.
  938. *
  939. * @memberof Cesium3DTileset.prototype
  940. *
  941. * @type {String}
  942. * @readonly
  943. */
  944. url : {
  945. get : function() {
  946. return this._url;
  947. }
  948. },
  949. /**
  950. * The base path that non-absolute paths in tileset JSON file are relative to.
  951. *
  952. * @memberof Cesium3DTileset.prototype
  953. *
  954. * @type {String}
  955. * @readonly
  956. * @deprecated
  957. */
  958. basePath : {
  959. get : function() {
  960. deprecationWarning('Cesium3DTileset.basePath', 'Cesium3DTileset.basePath has been deprecated. All tiles are relative to the url of the tileset JSON file that contains them. Use the url property instead.');
  961. return this._basePath;
  962. }
  963. },
  964. /**
  965. * The style, defined using the
  966. * {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language},
  967. * applied to each feature in the tileset.
  968. * <p>
  969. * Assign <code>undefined</code> to remove the style, which will restore the visual
  970. * appearance of the tileset to its default when no style was applied.
  971. * </p>
  972. * <p>
  973. * The style is applied to a tile before the {@link Cesium3DTileset#tileVisible}
  974. * event is raised, so code in <code>tileVisible</code> can manually set a feature's
  975. * properties (e.g. color and show) after the style is applied. When
  976. * a new style is assigned any manually set properties are overwritten.
  977. * </p>
  978. *
  979. * @memberof Cesium3DTileset.prototype
  980. *
  981. * @type {Cesium3DTileStyle}
  982. *
  983. * @default undefined
  984. *
  985. * @example
  986. * tileset.style = new Cesium.Cesium3DTileStyle({
  987. * color : {
  988. * conditions : [
  989. * ['${Height} >= 100', 'color("purple", 0.5)'],
  990. * ['${Height} >= 50', 'color("red")'],
  991. * ['true', 'color("blue")']
  992. * ]
  993. * },
  994. * show : '${Height} > 0',
  995. * meta : {
  996. * description : '"Building id ${id} has height ${Height}."'
  997. * }
  998. * });
  999. *
  1000. * @see {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language}
  1001. */
  1002. style : {
  1003. get : function() {
  1004. return this._styleEngine.style;
  1005. },
  1006. set : function(value) {
  1007. this._styleEngine.style = value;
  1008. }
  1009. },
  1010. /**
  1011. * The maximum screen space error used to drive level of detail refinement. This value helps determine when a tile
  1012. * refines to its descendants, and therefore plays a major role in balancing performance with visual quality.
  1013. * <p>
  1014. * A tile's screen space error is roughly equivalent to the number of pixels wide that would be drawn if a sphere with a
  1015. * radius equal to the tile's <b>geometric error</b> were rendered at the tile's position. If this value exceeds
  1016. * <code>maximumScreenSpaceError</code> the tile refines to its descendants.
  1017. * </p>
  1018. * <p>
  1019. * Depending on the tileset, <code>maximumScreenSpaceError</code> may need to be tweaked to achieve the right balance.
  1020. * Higher values provide better performance but lower visual quality.
  1021. * </p>
  1022. *
  1023. * @memberof Cesium3DTileset.prototype
  1024. *
  1025. * @type {Number}
  1026. * @default 16
  1027. *
  1028. * @exception {DeveloperError} <code>maximumScreenSpaceError</code> must be greater than or equal to zero.
  1029. */
  1030. maximumScreenSpaceError : {
  1031. get : function() {
  1032. return this._maximumScreenSpaceError;
  1033. },
  1034. set : function(value) {
  1035. //>>includeStart('debug', pragmas.debug);
  1036. Check.typeOf.number.greaterThanOrEquals('maximumScreenSpaceError', value, 0);
  1037. //>>includeEnd('debug');
  1038. this._maximumScreenSpaceError = value;
  1039. }
  1040. },
  1041. /**
  1042. * The maximum amount of GPU memory (in MB) that may be used to cache tiles. This value is estimated from
  1043. * geometry, textures, and batch table textures of loaded tiles. For point clouds, this value also
  1044. * includes per-point metadata.
  1045. * <p>
  1046. * Tiles not in view are unloaded to enforce this.
  1047. * </p>
  1048. * <p>
  1049. * If decreasing this value results in unloading tiles, the tiles are unloaded the next frame.
  1050. * </p>
  1051. * <p>
  1052. * If tiles sized more than <code>maximumMemoryUsage</code> are needed
  1053. * to meet the desired screen space error, determined by {@link Cesium3DTileset#maximumScreenSpaceError},
  1054. * for the current view, then the memory usage of the tiles loaded will exceed
  1055. * <code>maximumMemoryUsage</code>. For example, if the maximum is 256 MB, but
  1056. * 300 MB of tiles are needed to meet the screen space error, then 300 MB of tiles may be loaded. When
  1057. * these tiles go out of view, they will be unloaded.
  1058. * </p>
  1059. *
  1060. * @memberof Cesium3DTileset.prototype
  1061. *
  1062. * @type {Number}
  1063. * @default 512
  1064. *
  1065. * @exception {DeveloperError} <code>maximumMemoryUsage</code> must be greater than or equal to zero.
  1066. * @see Cesium3DTileset#totalMemoryUsageInBytes
  1067. */
  1068. maximumMemoryUsage : {
  1069. get : function() {
  1070. return this._maximumMemoryUsage;
  1071. },
  1072. set : function(value) {
  1073. //>>includeStart('debug', pragmas.debug);
  1074. Check.typeOf.number.greaterThanOrEquals('value', value, 0);
  1075. //>>includeEnd('debug');
  1076. this._maximumMemoryUsage = value;
  1077. }
  1078. },
  1079. /**
  1080. * The root tile.
  1081. *
  1082. * @memberOf Cesium3DTileset.prototype
  1083. *
  1084. * @type {Cesium3DTile}
  1085. * @readonly
  1086. *
  1087. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1088. */
  1089. root : {
  1090. get : function() {
  1091. //>>includeStart('debug', pragmas.debug);
  1092. if (!this.ready) {
  1093. throw new DeveloperError('The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.');
  1094. }
  1095. //>>includeEnd('debug');
  1096. return this._root;
  1097. }
  1098. },
  1099. /**
  1100. * The tileset's bounding sphere.
  1101. *
  1102. * @memberof Cesium3DTileset.prototype
  1103. *
  1104. * @type {BoundingSphere}
  1105. * @readonly
  1106. *
  1107. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1108. *
  1109. * @example
  1110. * var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
  1111. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json'
  1112. * }));
  1113. *
  1114. * tileset.readyPromise.then(function(tileset) {
  1115. * // Set the camera to view the newly added tileset
  1116. * viewer.camera.viewBoundingSphere(tileset.boundingSphere, new Cesium.HeadingPitchRange(0, -0.5, 0));
  1117. * });
  1118. */
  1119. boundingSphere : {
  1120. get : function() {
  1121. //>>includeStart('debug', pragmas.debug);
  1122. if (!this.ready) {
  1123. throw new DeveloperError('The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.');
  1124. }
  1125. //>>includeEnd('debug');
  1126. this._root.updateTransform(this._modelMatrix);
  1127. return this._root.boundingSphere;
  1128. }
  1129. },
  1130. /**
  1131. * A 4x4 transformation matrix that transforms the entire tileset.
  1132. *
  1133. * @memberof Cesium3DTileset.prototype
  1134. *
  1135. * @type {Matrix4}
  1136. * @default Matrix4.IDENTITY
  1137. *
  1138. * @example
  1139. * // Adjust a tileset's height from the globe's surface.
  1140. * var heightOffset = 20.0;
  1141. * var boundingSphere = tileset.boundingSphere;
  1142. * var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
  1143. * var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
  1144. * var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
  1145. * var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
  1146. * tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
  1147. */
  1148. modelMatrix : {
  1149. get : function() {
  1150. return this._modelMatrix;
  1151. },
  1152. set : function(value) {
  1153. this._modelMatrix = Matrix4.clone(value, this._modelMatrix);
  1154. }
  1155. },
  1156. /**
  1157. * Returns the time, in milliseconds, since the tileset was loaded and first updated.
  1158. *
  1159. * @memberof Cesium3DTileset.prototype
  1160. *
  1161. * @type {Number}
  1162. * @readonly
  1163. */
  1164. timeSinceLoad : {
  1165. get : function() {
  1166. return this._timeSinceLoad;
  1167. }
  1168. },
  1169. /**
  1170. * The total amount of GPU memory in bytes used by the tileset. This value is estimated from
  1171. * geometry, texture, and batch table textures of loaded tiles. For point clouds, this value also
  1172. * includes per-point metadata.
  1173. *
  1174. * @memberof Cesium3DTileset.prototype
  1175. *
  1176. * @type {Number}
  1177. * @readonly
  1178. *
  1179. * @see Cesium3DTileset#maximumMemoryUsage
  1180. */
  1181. totalMemoryUsageInBytes : {
  1182. get : function() {
  1183. var statistics = this._statistics;
  1184. return statistics.texturesByteLength + statistics.geometryByteLength + statistics.batchTableByteLength;
  1185. }
  1186. },
  1187. /**
  1188. * @private
  1189. */
  1190. clippingPlanesOriginMatrix : {
  1191. get : function() {
  1192. if (!defined(this._clippingPlanesOriginMatrix)) {
  1193. return Matrix4.IDENTITY;
  1194. }
  1195. if (this._clippingPlanesOriginMatrixDirty) {
  1196. Matrix4.multiply(this.root.computedTransform, this._initialClippingPlanesOriginMatrix, this._clippingPlanesOriginMatrix);
  1197. this._clippingPlanesOriginMatrixDirty = false;
  1198. }
  1199. return this._clippingPlanesOriginMatrix;
  1200. }
  1201. },
  1202. /**
  1203. * @private
  1204. */
  1205. styleEngine : {
  1206. get : function() {
  1207. return this._styleEngine;
  1208. }
  1209. },
  1210. /**
  1211. * @private
  1212. */
  1213. statistics : {
  1214. get : function() {
  1215. return this._statistics;
  1216. }
  1217. },
  1218. /**
  1219. * Determines whether terrain, 3D Tiles or both will be classified by this tileset.
  1220. * <p>
  1221. * This option is only applied to tilesets containing batched 3D models, geometry data, or vector data. Even when undefined, vector data and geometry data
  1222. * must render as classifications and will default to rendering on both terrain and other 3D Tiles tilesets.
  1223. * </p>
  1224. * <p>
  1225. * When enabled for batched 3D model tilesets, there are a few requirements/limitations on the glTF:
  1226. * <ul>
  1227. * <li>POSITION and _BATCHID semantics are required.</li>
  1228. * <li>All indices with the same batch id must occupy contiguous sections of the index buffer.</li>
  1229. * <li>All shaders and techniques are ignored. The generated shader simply multiplies the position by the model-view-projection matrix.</li>
  1230. * <li>The only supported extensions are CESIUM_RTC and WEB3D_quantized_attributes.</li>
  1231. * <li>Only one node is supported.</li>
  1232. * <li>Only one mesh per node is supported.</li>
  1233. * <li>Only one primitive per mesh is supported.</li>
  1234. * </ul>
  1235. * </p>
  1236. *
  1237. * @memberof Cesium3DTileset.prototype
  1238. *
  1239. * @type {ClassificationType}
  1240. * @default undefined
  1241. *
  1242. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1243. * @readonly
  1244. */
  1245. classificationType : {
  1246. get : function() {
  1247. return this._classificationType;
  1248. }
  1249. },
  1250. /**
  1251. * Gets an ellipsoid describing the shape of the globe.
  1252. *
  1253. * @memberof Cesium3DTileset.prototype
  1254. *
  1255. * @type {Ellipsoid}
  1256. * @readonly
  1257. */
  1258. ellipsoid : {
  1259. get : function() {
  1260. return this._ellipsoid;
  1261. }
  1262. },
  1263. /**
  1264. * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred.
  1265. * Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}.
  1266. * Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, essentially disabling the effect.
  1267. *
  1268. * @memberof Cesium3DTileset.prototype
  1269. *
  1270. * @type {Number}
  1271. * @default 0.3
  1272. */
  1273. foveatedConeSize : {
  1274. get : function() {
  1275. return this._foveatedConeSize;
  1276. },
  1277. set : function(value) {
  1278. //>>includeStart('debug', pragmas.debug);
  1279. Check.typeOf.number.greaterThanOrEquals('foveatedConeSize', value, 0.0);
  1280. Check.typeOf.number.lessThanOrEquals('foveatedConeSize', value, 1.0);
  1281. //>>includeEnd('debug');
  1282. this._foveatedConeSize = value;
  1283. }
  1284. },
  1285. /**
  1286. * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone.
  1287. * The screen space error will be raised starting with this value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}.
  1288. *
  1289. * @memberof Cesium3DTileset.prototype
  1290. *
  1291. * @type {Number}
  1292. * @default 0.0
  1293. */
  1294. foveatedMinimumScreenSpaceErrorRelaxation : {
  1295. get : function() {
  1296. return this._foveatedMinimumScreenSpaceErrorRelaxation;
  1297. },
  1298. set : function(value) {
  1299. //>>includeStart('debug', pragmas.debug);
  1300. Check.typeOf.number.greaterThanOrEquals('foveatedMinimumScreenSpaceErrorRelaxation', value, 0.0);
  1301. Check.typeOf.number.lessThanOrEquals('foveatedMinimumScreenSpaceErrorRelaxation', value, this.maximumScreenSpaceError);
  1302. //>>includeEnd('debug');
  1303. this._foveatedMinimumScreenSpaceErrorRelaxation = value;
  1304. }
  1305. },
  1306. /**
  1307. * Returns the <code>extras</code> property at the top-level of the tileset JSON, which contains application specific metadata.
  1308. * Returns <code>undefined</code> if <code>extras</code> does not exist.
  1309. *
  1310. * @memberof Cesium3DTileset.prototype
  1311. *
  1312. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1313. *
  1314. * @type {*}
  1315. * @readonly
  1316. *
  1317. * @see {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification#specifying-extensions-and-application-specific-extras|Extras in the 3D Tiles specification.}
  1318. */
  1319. extras : {
  1320. get : function() {
  1321. //>>includeStart('debug', pragmas.debug);
  1322. if (!this.ready) {
  1323. throw new DeveloperError('The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.');
  1324. }
  1325. //>>includeEnd('debug');
  1326. return this._extras;
  1327. }
  1328. },
  1329. /**
  1330. * Cesium adds lighting from the earth, sky, atmosphere, and star skybox. This cartesian is used to scale the final
  1331. * diffuse and specular lighting contribution from those sources to the final color. A value of 0.0 will disable those light sources.
  1332. *
  1333. * @memberof Cesium3DTileset.prototype
  1334. *
  1335. * @type {Cartesian2}
  1336. * @default Cartesian2(1.0, 1.0)
  1337. */
  1338. imageBasedLightingFactor : {
  1339. get : function() {
  1340. return this._imageBasedLightingFactor;
  1341. },
  1342. set : function(value) {
  1343. //>>includeStart('debug', pragmas.debug);
  1344. Check.typeOf.object('imageBasedLightingFactor', value);
  1345. Check.typeOf.number.greaterThanOrEquals('imageBasedLightingFactor.x', value.x, 0.0);
  1346. Check.typeOf.number.lessThanOrEquals('imageBasedLightingFactor.x', value.x, 1.0);
  1347. Check.typeOf.number.greaterThanOrEquals('imageBasedLightingFactor.y', value.y, 0.0);
  1348. Check.typeOf.number.lessThanOrEquals('imageBasedLightingFactor.y', value.y, 1.0);
  1349. //>>includeEnd('debug');
  1350. Cartesian2.clone(value, this._imageBasedLightingFactor);
  1351. }
  1352. }
  1353. });
  1354. /**
  1355. * Provides a hook to override the method used to request the tileset json
  1356. * useful when fetching tilesets from remote servers
  1357. * @param {Resource|String} tilesetUrl The url of the json file to be fetched
  1358. * @returns {Promise.<Object>} A promise that resolves with the fetched json data
  1359. */
  1360. Cesium3DTileset.loadJson = function(tilesetUrl) {
  1361. var resource = Resource.createIfNeeded(tilesetUrl);
  1362. return resource.fetchJson();
  1363. };
  1364. /**
  1365. * Marks the tileset's {@link Cesium3DTileset#style} as dirty, which forces all
  1366. * features to re-evaluate the style in the next frame each is visible.
  1367. */
  1368. Cesium3DTileset.prototype.makeStyleDirty = function() {
  1369. this._styleEngine.makeDirty();
  1370. };
  1371. /**
  1372. * Loads the main tileset JSON file or a tileset JSON file referenced from a tile.
  1373. *
  1374. * @private
  1375. */
  1376. Cesium3DTileset.prototype.loadTileset = function(resource, tilesetJson, parentTile) {
  1377. var asset = tilesetJson.asset;
  1378. if (!defined(asset)) {
  1379. throw new RuntimeError('Tileset must have an asset property.');
  1380. }
  1381. if (asset.version !== '0.0' && asset.version !== '1.0') {
  1382. throw new RuntimeError('The tileset must be 3D Tiles version 0.0 or 1.0.');
  1383. }
  1384. var statistics = this._statistics;
  1385. var tilesetVersion = asset.tilesetVersion;
  1386. if (defined(tilesetVersion)) {
  1387. // Append the tileset version to the resource
  1388. this._basePath += '?v=' + tilesetVersion;
  1389. resource.setQueryParameters({ v: tilesetVersion });
  1390. }
  1391. // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.
  1392. // Get the basePath relative to the external tileset.
  1393. var rootTile = new Cesium3DTile(this, resource, tilesetJson.root, parentTile);
  1394. // If there is a parentTile, add the root of the currently loading tileset
  1395. // to parentTile's children, and update its _depth.
  1396. if (defined(parentTile)) {
  1397. parentTile.children.push(rootTile);
  1398. rootTile._depth = parentTile._depth + 1;
  1399. }
  1400. var stack = [];
  1401. stack.push(rootTile);
  1402. while (stack.length > 0) {
  1403. var tile = stack.pop();
  1404. ++statistics.numberOfTilesTotal;
  1405. this._allTilesAdditive = this._allTilesAdditive && (tile.refine === Cesium3DTileRefine.ADD);
  1406. var children = tile._header.children;
  1407. if (defined(children)) {
  1408. var length = children.length;
  1409. for (var i = 0; i < length; ++i) {
  1410. var childHeader = children[i];
  1411. var childTile = new Cesium3DTile(this, resource, childHeader, tile);
  1412. tile.children.push(childTile);
  1413. childTile._depth = tile._depth + 1;
  1414. stack.push(childTile);
  1415. }
  1416. }
  1417. if (this._cullWithChildrenBounds) {
  1418. Cesium3DTileOptimizations.checkChildrenWithinParent(tile);
  1419. }
  1420. }
  1421. return rootTile;
  1422. };
  1423. var scratchPositionNormal = new Cartesian3();
  1424. var scratchCartographic = new Cartographic();
  1425. var scratchMatrix = new Matrix4();
  1426. var scratchCenter = new Cartesian3();
  1427. var scratchPosition = new Cartesian3();
  1428. var scratchDirection = new Cartesian3();
  1429. function updateDynamicScreenSpaceError(tileset, frameState) {
  1430. var up;
  1431. var direction;
  1432. var height;
  1433. var minimumHeight;
  1434. var maximumHeight;
  1435. var camera = frameState.camera;
  1436. var root = tileset._root;
  1437. var tileBoundingVolume = root.contentBoundingVolume;
  1438. if (tileBoundingVolume instanceof TileBoundingRegion) {
  1439. up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
  1440. direction = camera.directionWC;
  1441. height = camera.positionCartographic.height;
  1442. minimumHeight = tileBoundingVolume.minimumHeight;
  1443. maximumHeight = tileBoundingVolume.maximumHeight;
  1444. } else {
  1445. // Transform camera position and direction into the local coordinate system of the tileset
  1446. var transformLocal = Matrix4.inverseTransformation(root.computedTransform, scratchMatrix);
  1447. var ellipsoid = frameState.mapProjection.ellipsoid;
  1448. var boundingVolume = tileBoundingVolume.boundingVolume;
  1449. var centerLocal = Matrix4.multiplyByPoint(transformLocal, boundingVolume.center, scratchCenter);
  1450. if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {
  1451. // The tileset is defined in WGS84. Approximate the minimum and maximum height.
  1452. var centerCartographic = Cartographic.fromCartesian(centerLocal, ellipsoid, scratchCartographic);
  1453. up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
  1454. direction = camera.directionWC;
  1455. height = camera.positionCartographic.height;
  1456. minimumHeight = 0.0;
  1457. maximumHeight = centerCartographic.height * 2.0;
  1458. } else {
  1459. // The tileset is defined in local coordinates (z-up)
  1460. var positionLocal = Matrix4.multiplyByPoint(transformLocal, camera.positionWC, scratchPosition);
  1461. up = Cartesian3.UNIT_Z;
  1462. direction = Matrix4.multiplyByPointAsVector(transformLocal, camera.directionWC, scratchDirection);
  1463. direction = Cartesian3.normalize(direction, direction);
  1464. height = positionLocal.z;
  1465. if (tileBoundingVolume instanceof TileOrientedBoundingBox) {
  1466. // Assuming z-up, the last component stores the half-height of the box
  1467. var boxHeight = root._header.boundingVolume.box[11];
  1468. minimumHeight = centerLocal.z - boxHeight;
  1469. maximumHeight = centerLocal.z + boxHeight;
  1470. } else if (tileBoundingVolume instanceof TileBoundingSphere) {
  1471. var radius = boundingVolume.radius;
  1472. minimumHeight = centerLocal.z - radius;
  1473. maximumHeight = centerLocal.z + radius;
  1474. }
  1475. }
  1476. }
  1477. // The range where the density starts to lessen. Start at the quarter height of the tileset.
  1478. var heightFalloff = tileset.dynamicScreenSpaceErrorHeightFalloff;
  1479. var heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;
  1480. var heightFar = maximumHeight;
  1481. var t = CesiumMath.clamp((height - heightClose) / (heightFar - heightClose), 0.0, 1.0);
  1482. // Increase density as the camera tilts towards the horizon
  1483. var dot = Math.abs(Cartesian3.dot(direction, up));
  1484. var horizonFactor = 1.0 - dot;
  1485. // Weaken the horizon factor as the camera height increases, implying the camera is further away from the tileset.
  1486. // The goal is to increase density for the "street view", not when viewing the tileset from a distance.
  1487. horizonFactor = horizonFactor * (1.0 - t);
  1488. var density = tileset.dynamicScreenSpaceErrorDensity;
  1489. density *= horizonFactor;
  1490. tileset._dynamicScreenSpaceErrorComputedDensity = density;
  1491. }
  1492. ///////////////////////////////////////////////////////////////////////////
  1493. function requestContent(tileset, tile) {
  1494. if (tile.hasEmptyContent) {
  1495. return;
  1496. }
  1497. var statistics = tileset._statistics;
  1498. var expired = tile.contentExpired;
  1499. var requested = tile.requestContent();
  1500. if (!requested) {
  1501. ++statistics.numberOfAttemptedRequests;
  1502. return;
  1503. }
  1504. if (expired) {
  1505. if (tile.hasTilesetContent) {
  1506. destroySubtree(tileset, tile);
  1507. } else {
  1508. statistics.decrementLoadCounts(tile.content);
  1509. --statistics.numberOfTilesWithContentReady;
  1510. }
  1511. }
  1512. ++statistics.numberOfPendingRequests;
  1513. tileset._requestedTilesInFlight.push(tile);
  1514. tile.contentReadyToProcessPromise.then(addToProcessingQueue(tileset, tile));
  1515. tile.contentReadyPromise.then(handleTileSuccess(tileset, tile)).otherwise(handleTileFailure(tileset, tile));
  1516. }
  1517. function sortRequestByPriority(a, b) {
  1518. return a._priority - b._priority;
  1519. }
  1520. /**
  1521. * Perform any pass invariant tasks here. Called after the render pass.
  1522. * @private
  1523. */
  1524. Cesium3DTileset.prototype.postPassesUpdate = function(frameState) {
  1525. if (!this.ready) {
  1526. return;
  1527. }
  1528. cancelOutOfViewRequests(this, frameState);
  1529. raiseLoadProgressEvent(this, frameState);
  1530. this._cache.unloadTiles(this, unloadTile);
  1531. };
  1532. /**
  1533. * Perform any pass invariant tasks here. Called before any passes are executed.
  1534. * @private
  1535. */
  1536. Cesium3DTileset.prototype.prePassesUpdate = function(frameState) {
  1537. if (!this.ready) {
  1538. return;
  1539. }
  1540. processTiles(this, frameState);
  1541. // Update clipping planes
  1542. var clippingPlanes = this._clippingPlanes;
  1543. this._clippingPlanesOriginMatrixDirty = true;
  1544. if (defined(clippingPlanes) && clippingPlanes.enabled) {
  1545. clippingPlanes.update(frameState);
  1546. }
  1547. if (!defined(this._loadTimestamp)) {
  1548. this._loadTimestamp = JulianDate.clone(frameState.time);
  1549. }
  1550. this._timeSinceLoad = Math.max(JulianDate.secondsDifference(frameState.time, this._loadTimestamp) * 1000, 0.0);
  1551. this._skipLevelOfDetail = this.skipLevelOfDetail && !defined(this._classificationType) && !this._disableSkipLevelOfDetail && !this._allTilesAdditive;
  1552. if (this.dynamicScreenSpaceError) {
  1553. updateDynamicScreenSpaceError(this, frameState);
  1554. }
  1555. if (frameState.newFrame) {
  1556. this._cache.reset();
  1557. }
  1558. };
  1559. function cancelOutOfViewRequests(tileset, frameState) {
  1560. var requestedTilesInFlight = tileset._requestedTilesInFlight;
  1561. var removeCount = 0;
  1562. var length = requestedTilesInFlight.length;
  1563. for (var i = 0; i < length; ++i) {
  1564. var tile = requestedTilesInFlight[i];
  1565. // NOTE: This is framerate dependant so make sure the threshold check is small
  1566. var outOfView = (frameState.frameNumber - tile._touchedFrame) >= 1;
  1567. if (tile._contentState !== Cesium3DTileContentState.LOADING) {
  1568. // No longer fetching from host, don't need to track it anymore. Gets marked as LOADING in Cesium3DTile::requestContent().
  1569. ++removeCount;
  1570. continue;
  1571. } else if (outOfView) {
  1572. // RequestScheduler will take care of cancelling it
  1573. tile._request.cancel();
  1574. ++removeCount;
  1575. continue;
  1576. }
  1577. if (removeCount > 0) {
  1578. requestedTilesInFlight[i - removeCount] = tile;
  1579. }
  1580. }
  1581. requestedTilesInFlight.length -= removeCount;
  1582. }
  1583. function requestTiles(tileset, isAsync) {
  1584. // Sort requests by priority before making any requests.
  1585. // This makes it less likely that requests will be cancelled after being issued.
  1586. var requestedTiles = tileset._requestedTiles;
  1587. var length = requestedTiles.length;
  1588. requestedTiles.sort(sortRequestByPriority);
  1589. for (var i = 0; i < length; ++i) {
  1590. requestContent(tileset, requestedTiles[i]);
  1591. }
  1592. }
  1593. function addToProcessingQueue(tileset, tile) {
  1594. return function() {
  1595. tileset._processingQueue.push(tile);
  1596. --tileset._statistics.numberOfPendingRequests;
  1597. ++tileset._statistics.numberOfTilesProcessing;
  1598. };
  1599. }
  1600. function handleTileFailure(tileset, tile) {
  1601. return function(error) {
  1602. if (tileset._processingQueue.indexOf(tile) >= 0) {
  1603. // Failed during processing
  1604. --tileset._statistics.numberOfTilesProcessing;
  1605. } else {
  1606. // Failed when making request
  1607. --tileset._statistics.numberOfPendingRequests;
  1608. }
  1609. var url = tile._contentResource.url;
  1610. var message = defined(error.message) ? error.message : error.toString();
  1611. if (tileset.tileFailed.numberOfListeners > 0) {
  1612. tileset.tileFailed.raiseEvent({
  1613. url : url,
  1614. message : message
  1615. });
  1616. } else {
  1617. console.log('A 3D tile failed to load: ' + url);
  1618. console.log('Error: ' + message);
  1619. }
  1620. };
  1621. }
  1622. function handleTileSuccess(tileset, tile) {
  1623. return function() {
  1624. --tileset._statistics.numberOfTilesProcessing;
  1625. if (!tile.hasTilesetContent) {
  1626. // RESEARCH_IDEA: ability to unload tiles (without content) for an
  1627. // external tileset when all the tiles are unloaded.
  1628. tileset._statistics.incrementLoadCounts(tile.content);
  1629. ++tileset._statistics.numberOfTilesWithContentReady;
  1630. ++tileset._statistics.numberOfLoadedTilesTotal;
  1631. // Add to the tile cache. Previously expired tiles are already in the cache and won't get re-added.
  1632. tileset._cache.add(tile);
  1633. }
  1634. tileset.tileLoad.raiseEvent(tile);
  1635. };
  1636. }
  1637. function filterProcessingQueue(tileset) {
  1638. var tiles = tileset._processingQueue;
  1639. var length = tiles.length;
  1640. var removeCount = 0;
  1641. for (var i = 0; i < length; ++i) {
  1642. var tile = tiles[i];
  1643. if (tile._contentState !== Cesium3DTileContentState.PROCESSING) {
  1644. ++removeCount;
  1645. continue;
  1646. }
  1647. if (removeCount > 0) {
  1648. tiles[i - removeCount] = tile;
  1649. }
  1650. }
  1651. tiles.length -= removeCount;
  1652. }
  1653. function processTiles(tileset, frameState) {
  1654. filterProcessingQueue(tileset);
  1655. var tiles = tileset._processingQueue;
  1656. var length = tiles.length;
  1657. // Process tiles in the PROCESSING state so they will eventually move to the READY state.
  1658. for (var i = 0; i < length; ++i) {
  1659. tiles[i].process(tileset, frameState);
  1660. }
  1661. }
  1662. ///////////////////////////////////////////////////////////////////////////
  1663. var scratchCartesian = new Cartesian3();
  1664. var stringOptions = {
  1665. maximumFractionDigits : 3
  1666. };
  1667. function formatMemoryString(memorySizeInBytes) {
  1668. var memoryInMegabytes = memorySizeInBytes / 1048576;
  1669. if (memoryInMegabytes < 1.0) {
  1670. return memoryInMegabytes.toLocaleString(undefined, stringOptions);
  1671. }
  1672. return Math.round(memoryInMegabytes).toLocaleString();
  1673. }
  1674. function computeTileLabelPosition(tile) {
  1675. var boundingVolume = tile.boundingVolume.boundingVolume;
  1676. var halfAxes = boundingVolume.halfAxes;
  1677. var radius = boundingVolume.radius;
  1678. var position = Cartesian3.clone(boundingVolume.center, scratchCartesian);
  1679. if (defined(halfAxes)) {
  1680. position.x += 0.75 * (halfAxes[0] + halfAxes[3] + halfAxes[6]);
  1681. position.y += 0.75 * (halfAxes[1] + halfAxes[4] + halfAxes[7]);
  1682. position.z += 0.75 * (halfAxes[2] + halfAxes[5] + halfAxes[8]);
  1683. } else if (defined(radius)) {
  1684. var normal = Cartesian3.normalize(boundingVolume.center, scratchCartesian);
  1685. normal = Cartesian3.multiplyByScalar(normal, 0.75 * radius, scratchCartesian);
  1686. position = Cartesian3.add(normal, boundingVolume.center, scratchCartesian);
  1687. }
  1688. return position;
  1689. }
  1690. function addTileDebugLabel(tile, tileset, position) {
  1691. var labelString = '';
  1692. var attributes = 0;
  1693. if (tileset.debugShowGeometricError) {
  1694. labelString += '\nGeometric error: ' + tile.geometricError;
  1695. attributes++;
  1696. }
  1697. if (tileset.debugShowRenderingStatistics) {
  1698. labelString += '\nCommands: ' + tile.commandsLength;
  1699. attributes++;
  1700. // Don't display number of points or triangles if 0.
  1701. var numberOfPoints = tile.content.pointsLength;
  1702. if (numberOfPoints > 0) {
  1703. labelString += '\nPoints: ' + tile.content.pointsLength;
  1704. attributes++;
  1705. }
  1706. var numberOfTriangles = tile.content.trianglesLength;
  1707. if (numberOfTriangles > 0) {
  1708. labelString += '\nTriangles: ' + tile.content.trianglesLength;
  1709. attributes++;
  1710. }
  1711. labelString += '\nFeatures: ' + tile.content.featuresLength;
  1712. attributes ++;
  1713. }
  1714. if (tileset.debugShowMemoryUsage) {
  1715. labelString += '\nTexture Memory: ' + formatMemoryString(tile.content.texturesByteLength);
  1716. labelString += '\nGeometry Memory: ' + formatMemoryString(tile.content.geometryByteLength);
  1717. attributes += 2;
  1718. }
  1719. if (tileset.debugShowUrl) {
  1720. labelString += '\nUrl: ' + tile._header.content.uri;
  1721. attributes++;
  1722. }
  1723. var newLabel = {
  1724. text : labelString.substring(1),
  1725. position : position,
  1726. font : (19-attributes) + 'px sans-serif',
  1727. showBackground : true,
  1728. disableDepthTestDistance : Number.POSITIVE_INFINITY
  1729. };
  1730. return tileset._tileDebugLabels.add(newLabel);
  1731. }
  1732. function updateTileDebugLabels(tileset, frameState) {
  1733. var i;
  1734. var tile;
  1735. var selectedTiles = tileset._selectedTiles;
  1736. var selectedLength = selectedTiles.length;
  1737. var emptyTiles = tileset._emptyTiles;
  1738. var emptyLength = emptyTiles.length;
  1739. tileset._tileDebugLabels.removeAll();
  1740. if (tileset.debugPickedTileLabelOnly) {
  1741. if (defined(tileset.debugPickedTile)) {
  1742. var position = (defined(tileset.debugPickPosition)) ? tileset.debugPickPosition : computeTileLabelPosition(tileset.debugPickedTile);
  1743. var label = addTileDebugLabel(tileset.debugPickedTile, tileset, position);
  1744. label.pixelOffset = new Cartesian2(15, -15); // Offset to avoid picking the label.
  1745. }
  1746. } else {
  1747. for (i = 0; i < selectedLength; ++i) {
  1748. tile = selectedTiles[i];
  1749. addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
  1750. }
  1751. for (i = 0; i < emptyLength; ++i) {
  1752. tile = emptyTiles[i];
  1753. if (tile.hasTilesetContent) {
  1754. addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
  1755. }
  1756. }
  1757. }
  1758. tileset._tileDebugLabels.update(frameState);
  1759. }
  1760. function updateTiles(tileset, frameState, isRender) {
  1761. tileset._styleEngine.applyStyle(tileset, frameState);
  1762. var statistics = tileset._statistics;
  1763. var commandList = frameState.commandList;
  1764. var numberOfInitialCommands = commandList.length;
  1765. var selectedTiles = tileset._selectedTiles;
  1766. var selectedLength = selectedTiles.length;
  1767. var emptyTiles = tileset._emptyTiles;
  1768. var emptyLength = emptyTiles.length;
  1769. var tileVisible = tileset.tileVisible;
  1770. var i;
  1771. var tile;
  1772. var bivariateVisibilityTest = tileset._skipLevelOfDetail && tileset._hasMixedContent && frameState.context.stencilBuffer && selectedLength > 0;
  1773. tileset._backfaceCommands.length = 0;
  1774. if (bivariateVisibilityTest) {
  1775. if (!defined(tileset._stencilClearCommand)) {
  1776. tileset._stencilClearCommand = new ClearCommand({
  1777. stencil : 0,
  1778. pass : Pass.CESIUM_3D_TILE,
  1779. renderState : RenderState.fromCache({
  1780. stencilMask : StencilConstants.SKIP_LOD_MASK
  1781. })
  1782. });
  1783. }
  1784. commandList.push(tileset._stencilClearCommand);
  1785. }
  1786. var lengthBeforeUpdate = commandList.length;
  1787. for (i = 0; i < selectedLength; ++i) {
  1788. tile = selectedTiles[i];
  1789. // Raise the tileVisible event before update in case the tileVisible event
  1790. // handler makes changes that update needs to apply to WebGL resources
  1791. if (isRender) {
  1792. tileVisible.raiseEvent(tile);
  1793. }
  1794. tile.update(tileset, frameState);
  1795. statistics.incrementSelectionCounts(tile.content);
  1796. ++statistics.selected;
  1797. }
  1798. for (i = 0; i < emptyLength; ++i) {
  1799. tile = emptyTiles[i];
  1800. tile.update(tileset, frameState);
  1801. }
  1802. var addedCommandsLength = commandList.length - lengthBeforeUpdate;
  1803. tileset._backfaceCommands.trim();
  1804. if (bivariateVisibilityTest) {
  1805. /**
  1806. * Consider 'effective leaf' tiles as selected tiles that have no selected descendants. They may have children,
  1807. * but they are currently our effective leaves because they do not have selected descendants. These tiles
  1808. * are those where with tile._finalResolution === true.
  1809. * Let 'unresolved' tiles be those with tile._finalResolution === false.
  1810. *
  1811. * 1. Render just the backfaces of unresolved tiles in order to lay down z
  1812. * 2. Render all frontfaces wherever tile._selectionDepth > stencilBuffer.
  1813. * Replace stencilBuffer with tile._selectionDepth, when passing the z test.
  1814. * Because children are always drawn before ancestors {@link Cesium3DTilesetTraversal#traverseAndSelect},
  1815. * this effectively draws children first and does not draw ancestors if a descendant has already
  1816. * been drawn at that pixel.
  1817. * Step 1 prevents child tiles from appearing on top when they are truly behind ancestor content.
  1818. * If they are behind the backfaces of the ancestor, then they will not be drawn.
  1819. *
  1820. * NOTE: Step 2 sometimes causes visual artifacts when backfacing child content has some faces that
  1821. * partially face the camera and are inside of the ancestor content. Because they are inside, they will
  1822. * not be culled by the depth writes in Step 1, and because they partially face the camera, the stencil tests
  1823. * will draw them on top of the ancestor content.
  1824. *
  1825. * NOTE: Because we always render backfaces of unresolved tiles, if the camera is looking at the backfaces
  1826. * of an object, they will always be drawn while loading, even if backface culling is enabled.
  1827. */
  1828. var backfaceCommands = tileset._backfaceCommands.values;
  1829. var backfaceCommandsLength = backfaceCommands.length;
  1830. commandList.length += backfaceCommandsLength;
  1831. // copy commands to the back of the commandList
  1832. for (i = addedCommandsLength - 1; i >= 0; --i) {
  1833. commandList[lengthBeforeUpdate + backfaceCommandsLength + i] = commandList[lengthBeforeUpdate + i];
  1834. }
  1835. // move backface commands to the front of the commandList
  1836. for (i = 0; i < backfaceCommandsLength; ++i) {
  1837. commandList[lengthBeforeUpdate + i] = backfaceCommands[i];
  1838. }
  1839. }
  1840. // Number of commands added by each update above
  1841. addedCommandsLength = commandList.length - numberOfInitialCommands;
  1842. statistics.numberOfCommands = addedCommandsLength;
  1843. // Only run EDL if simple attenuation is on
  1844. if (isRender &&
  1845. tileset.pointCloudShading.attenuation &&
  1846. tileset.pointCloudShading.eyeDomeLighting &&
  1847. (addedCommandsLength > 0)) {
  1848. tileset._pointCloudEyeDomeLighting.update(frameState, numberOfInitialCommands, tileset.pointCloudShading);
  1849. }
  1850. if (isRender) {
  1851. if (tileset.debugShowGeometricError || tileset.debugShowRenderingStatistics || tileset.debugShowMemoryUsage || tileset.debugShowUrl) {
  1852. if (!defined(tileset._tileDebugLabels)) {
  1853. tileset._tileDebugLabels = new LabelCollection();
  1854. }
  1855. updateTileDebugLabels(tileset, frameState);
  1856. } else {
  1857. tileset._tileDebugLabels = tileset._tileDebugLabels && tileset._tileDebugLabels.destroy();
  1858. }
  1859. }
  1860. }
  1861. var scratchStack = [];
  1862. function destroySubtree(tileset, tile) {
  1863. var root = tile;
  1864. var stack = scratchStack;
  1865. stack.push(tile);
  1866. while (stack.length > 0) {
  1867. tile = stack.pop();
  1868. var children = tile.children;
  1869. var length = children.length;
  1870. for (var i = 0; i < length; ++i) {
  1871. stack.push(children[i]);
  1872. }
  1873. if (tile !== root) {
  1874. destroyTile(tileset, tile);
  1875. --tileset._statistics.numberOfTilesTotal;
  1876. }
  1877. }
  1878. root.children = [];
  1879. }
  1880. function unloadTile(tileset, tile) {
  1881. tileset.tileUnload.raiseEvent(tile);
  1882. tileset._statistics.decrementLoadCounts(tile.content);
  1883. --tileset._statistics.numberOfTilesWithContentReady;
  1884. tile.unloadContent();
  1885. }
  1886. function destroyTile(tileset, tile) {
  1887. tileset._cache.unloadTile(tileset, tile, unloadTile);
  1888. tile.destroy();
  1889. }
  1890. /**
  1891. * Unloads all tiles that weren't selected the previous frame. This can be used to
  1892. * explicitly manage the tile cache and reduce the total number of tiles loaded below
  1893. * {@link Cesium3DTileset#maximumMemoryUsage}.
  1894. * <p>
  1895. * Tile unloads occur at the next frame to keep all the WebGL delete calls
  1896. * within the render loop.
  1897. * </p>
  1898. */
  1899. Cesium3DTileset.prototype.trimLoadedTiles = function() {
  1900. this._cache.trim();
  1901. };
  1902. ///////////////////////////////////////////////////////////////////////////
  1903. function raiseLoadProgressEvent(tileset, frameState) {
  1904. var statistics = tileset._statistics;
  1905. var statisticsLast = tileset._statisticsLast;
  1906. var numberOfPendingRequests = statistics.numberOfPendingRequests;
  1907. var numberOfTilesProcessing = statistics.numberOfTilesProcessing;
  1908. var lastNumberOfPendingRequest = statisticsLast.numberOfPendingRequests;
  1909. var lastNumberOfTilesProcessing = statisticsLast.numberOfTilesProcessing;
  1910. Cesium3DTilesetStatistics.clone(statistics, statisticsLast);
  1911. var progressChanged = (numberOfPendingRequests !== lastNumberOfPendingRequest) || (numberOfTilesProcessing !== lastNumberOfTilesProcessing);
  1912. if (progressChanged) {
  1913. frameState.afterRender.push(function() {
  1914. tileset.loadProgress.raiseEvent(numberOfPendingRequests, numberOfTilesProcessing);
  1915. });
  1916. }
  1917. tileset._tilesLoaded = (statistics.numberOfPendingRequests === 0) && (statistics.numberOfTilesProcessing === 0) && (statistics.numberOfAttemptedRequests === 0);
  1918. // Events are raised (added to the afterRender queue) here since promises
  1919. // may resolve outside of the update loop that then raise events, e.g.,
  1920. // model's readyPromise.
  1921. if (progressChanged && tileset._tilesLoaded) {
  1922. frameState.afterRender.push(function() {
  1923. tileset.allTilesLoaded.raiseEvent();
  1924. });
  1925. if (!tileset._initialTilesLoaded) {
  1926. tileset._initialTilesLoaded = true;
  1927. frameState.afterRender.push(function() {
  1928. tileset.initialTilesLoaded.raiseEvent();
  1929. });
  1930. }
  1931. }
  1932. }
  1933. function resetMinimumMaximum(tileset) {
  1934. tileset._heatmap.resetMinimumMaximum();
  1935. tileset._minimumPriority.depth = Number.MAX_VALUE;
  1936. tileset._maximumPriority.depth = -Number.MAX_VALUE;
  1937. tileset._minimumPriority.foveatedFactor = Number.MAX_VALUE;
  1938. tileset._maximumPriority.foveatedFactor = -Number.MAX_VALUE;
  1939. tileset._minimumPriority.distance = Number.MAX_VALUE;
  1940. tileset._maximumPriority.distance = -Number.MAX_VALUE;
  1941. tileset._minimumPriority.reverseScreenSpaceError = Number.MAX_VALUE;
  1942. tileset._maximumPriority.reverseScreenSpaceError = -Number.MAX_VALUE;
  1943. }
  1944. ///////////////////////////////////////////////////////////////////////////
  1945. function update(tileset, frameState, passStatistics, passOptions) {
  1946. if (frameState.mode === SceneMode.MORPHING) {
  1947. return false;
  1948. }
  1949. if (!tileset.ready) {
  1950. return false;
  1951. }
  1952. var statistics = tileset._statistics;
  1953. statistics.clear();
  1954. var isRender = passOptions.isRender;
  1955. // Resets the visibility check for each pass
  1956. ++tileset._updatedVisibilityFrame;
  1957. // Update any tracked min max values
  1958. resetMinimumMaximum(tileset);
  1959. var ready = passOptions.traversal.selectTiles(tileset, frameState);
  1960. if (passOptions.requestTiles) {
  1961. requestTiles(tileset);
  1962. }
  1963. updateTiles(tileset, frameState, isRender);
  1964. // Update pass statistics
  1965. Cesium3DTilesetStatistics.clone(statistics, passStatistics);
  1966. if (isRender) {
  1967. var credits = tileset._credits;
  1968. if (defined(credits) && statistics.selected !== 0) {
  1969. var length = credits.length;
  1970. for (var i = 0; i < length; ++i) {
  1971. frameState.creditDisplay.addCredit(credits[i]);
  1972. }
  1973. }
  1974. }
  1975. return ready;
  1976. }
  1977. /**
  1978. * @private
  1979. */
  1980. Cesium3DTileset.prototype.update = function(frameState) {
  1981. this.updateForPass(frameState, frameState.tilesetPassState);
  1982. };
  1983. /**
  1984. * @private
  1985. */
  1986. Cesium3DTileset.prototype.updateForPass = function(frameState, tilesetPassState) {
  1987. //>>includeStart('debug', pragmas.debug);
  1988. Check.typeOf.object('frameState', frameState);
  1989. Check.typeOf.object('tilesetPassState', tilesetPassState);
  1990. //>>includeEnd('debug');
  1991. var pass = tilesetPassState.pass;
  1992. if ((pass === Cesium3DTilePass.PRELOAD && (!this.preloadWhenHidden || this.show)) ||
  1993. (pass === Cesium3DTilePass.PRELOAD_FLIGHT && (!this.preloadFlightDestinations || (!this.show && !this.preloadWhenHidden))) ||
  1994. (pass === Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK && ((!this.cullRequestsWhileMoving && this.foveatedTimeDelay <= 0) || !this.show))) {
  1995. return;
  1996. }
  1997. var originalCommandList = frameState.commandList;
  1998. var originalCamera = frameState.camera;
  1999. var originalCullingVolume = frameState.cullingVolume;
  2000. tilesetPassState.ready = false;
  2001. var passOptions = Cesium3DTilePass.getPassOptions(pass);
  2002. var ignoreCommands = passOptions.ignoreCommands;
  2003. var commandList = defaultValue(tilesetPassState.commandList, originalCommandList);
  2004. var commandStart = commandList.length;
  2005. frameState.commandList = commandList;
  2006. frameState.camera = defaultValue(tilesetPassState.camera, originalCamera);
  2007. frameState.cullingVolume = defaultValue(tilesetPassState.cullingVolume, originalCullingVolume);
  2008. var passStatistics = this._statisticsPerPass[pass];
  2009. if (this.show || ignoreCommands) {
  2010. this._pass = pass;
  2011. tilesetPassState.ready = update(this, frameState, passStatistics, passOptions);
  2012. }
  2013. if (ignoreCommands) {
  2014. commandList.length = commandStart;
  2015. }
  2016. frameState.commandList = originalCommandList;
  2017. frameState.camera = originalCamera;
  2018. frameState.cullingVolume = originalCullingVolume;
  2019. };
  2020. /**
  2021. * <code>true</code> if the tileset JSON file lists the extension in extensionsUsed; otherwise, <code>false</code>.
  2022. * @param {String} extensionName The name of the extension to check.
  2023. *
  2024. * @returns {Boolean} <code>true</code> if the tileset JSON file lists the extension in extensionsUsed; otherwise, <code>false</code>.
  2025. */
  2026. Cesium3DTileset.prototype.hasExtension = function(extensionName) {
  2027. if (!defined(this._extensionsUsed)) {
  2028. return false;
  2029. }
  2030. return (this._extensionsUsed.indexOf(extensionName) > -1);
  2031. };
  2032. /**
  2033. * Returns true if this object was destroyed; otherwise, false.
  2034. * <br /><br />
  2035. * If this object was destroyed, it should not be used; calling any function other than
  2036. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  2037. *
  2038. * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  2039. *
  2040. * @see Cesium3DTileset#destroy
  2041. */
  2042. Cesium3DTileset.prototype.isDestroyed = function() {
  2043. return false;
  2044. };
  2045. /**
  2046. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  2047. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  2048. * <br /><br />
  2049. * Once an object is destroyed, it should not be used; calling any function other than
  2050. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  2051. * assign the return value (<code>undefined</code>) to the object as done in the example.
  2052. *
  2053. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  2054. *
  2055. * @example
  2056. * tileset = tileset && tileset.destroy();
  2057. *
  2058. * @see Cesium3DTileset#isDestroyed
  2059. */
  2060. Cesium3DTileset.prototype.destroy = function() {
  2061. this._tileDebugLabels = this._tileDebugLabels && this._tileDebugLabels.destroy();
  2062. this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
  2063. // Traverse the tree and destroy all tiles
  2064. if (defined(this._root)) {
  2065. var stack = scratchStack;
  2066. stack.push(this._root);
  2067. while (stack.length > 0) {
  2068. var tile = stack.pop();
  2069. tile.destroy();
  2070. var children = tile.children;
  2071. var length = children.length;
  2072. for (var i = 0; i < length; ++i) {
  2073. stack.push(children[i]);
  2074. }
  2075. }
  2076. }
  2077. this._root = undefined;
  2078. return destroyObject(this);
  2079. };
  2080. /**
  2081. * Optimization option. Used as a callback when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how much to raise the screen space error for tiles outside the foveated cone,
  2082. * interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}.
  2083. *
  2084. * @callback Cesium3DTileset~foveatedInterpolationCallback
  2085. * @default Math.lerp
  2086. *
  2087. * @param {Number} p The start value to interpolate.
  2088. * @param {Number} q The end value to interpolate.
  2089. * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  2090. * @returns {Number} The interpolated value.
  2091. */
  2092. export default Cesium3DTileset;