ModelVisualizer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import AssociativeArray from "../Core/AssociativeArray.js";
  2. import BoundingSphere from "../Core/BoundingSphere.js";
  3. import Cartesian2 from "../Core/Cartesian2.js";
  4. import Color from "../Core/Color.js";
  5. import defined from "../Core/defined.js";
  6. import destroyObject from "../Core/destroyObject.js";
  7. import DeveloperError from "../Core/DeveloperError.js";
  8. import Matrix4 from "../Core/Matrix4.js";
  9. import Resource from "../Core/Resource.js";
  10. import ColorBlendMode from "../Scene/ColorBlendMode.js";
  11. import HeightReference from "../Scene/HeightReference.js";
  12. import Model from "../Scene/Model.js";
  13. import ModelAnimationLoop from "../Scene/ModelAnimationLoop.js";
  14. import ShadowMode from "../Scene/ShadowMode.js";
  15. import BoundingSphereState from "./BoundingSphereState.js";
  16. import Property from "./Property.js";
  17. const defaultScale = 1.0;
  18. const defaultMinimumPixelSize = 0.0;
  19. const defaultIncrementallyLoadTextures = true;
  20. const defaultClampAnimations = true;
  21. const defaultShadows = ShadowMode.ENABLED;
  22. const defaultHeightReference = HeightReference.NONE;
  23. const defaultSilhouetteColor = Color.RED;
  24. const defaultSilhouetteSize = 0.0;
  25. const defaultColor = Color.WHITE;
  26. const defaultColorBlendMode = ColorBlendMode.HIGHLIGHT;
  27. const defaultColorBlendAmount = 0.5;
  28. const defaultImageBasedLightingFactor = new Cartesian2(1.0, 1.0);
  29. const modelMatrixScratch = new Matrix4();
  30. const nodeMatrixScratch = new Matrix4();
  31. /**
  32. * A {@link Visualizer} which maps {@link Entity#model} to a {@link Model}.
  33. * @alias ModelVisualizer
  34. * @constructor
  35. *
  36. * @param {Scene} scene The scene the primitives will be rendered in.
  37. * @param {EntityCollection} entityCollection The entityCollection to visualize.
  38. */
  39. function ModelVisualizer(scene, entityCollection) {
  40. //>>includeStart('debug', pragmas.debug);
  41. if (!defined(scene)) {
  42. throw new DeveloperError("scene is required.");
  43. }
  44. if (!defined(entityCollection)) {
  45. throw new DeveloperError("entityCollection is required.");
  46. }
  47. //>>includeEnd('debug');
  48. entityCollection.collectionChanged.addEventListener(
  49. ModelVisualizer.prototype._onCollectionChanged,
  50. this
  51. );
  52. this._scene = scene;
  53. this._primitives = scene.primitives;
  54. this._entityCollection = entityCollection;
  55. this._modelHash = {};
  56. this._entitiesToVisualize = new AssociativeArray();
  57. this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  58. }
  59. /**
  60. * Updates models created this visualizer to match their
  61. * Entity counterpart at the given time.
  62. *
  63. * @param {JulianDate} time The time to update to.
  64. * @returns {Boolean} This function always returns true.
  65. */
  66. ModelVisualizer.prototype.update = function (time) {
  67. //>>includeStart('debug', pragmas.debug);
  68. if (!defined(time)) {
  69. throw new DeveloperError("time is required.");
  70. }
  71. //>>includeEnd('debug');
  72. const entities = this._entitiesToVisualize.values;
  73. const modelHash = this._modelHash;
  74. const primitives = this._primitives;
  75. for (let i = 0, len = entities.length; i < len; i++) {
  76. const entity = entities[i];
  77. const modelGraphics = entity._model;
  78. let resource;
  79. let modelData = modelHash[entity.id];
  80. let show =
  81. entity.isShowing &&
  82. entity.isAvailable(time) &&
  83. Property.getValueOrDefault(modelGraphics._show, time, true);
  84. let modelMatrix;
  85. if (show) {
  86. modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);
  87. resource = Resource.createIfNeeded(
  88. Property.getValueOrUndefined(modelGraphics._uri, time)
  89. );
  90. show = defined(modelMatrix) && defined(resource);
  91. }
  92. if (!show) {
  93. if (defined(modelData)) {
  94. modelData.modelPrimitive.show = false;
  95. }
  96. continue;
  97. }
  98. let model = defined(modelData) ? modelData.modelPrimitive : undefined;
  99. if (!defined(model) || resource.url !== modelData.url) {
  100. if (defined(model)) {
  101. primitives.removeAndDestroy(model);
  102. delete modelHash[entity.id];
  103. }
  104. model = Model.fromGltf({
  105. url: resource,
  106. incrementallyLoadTextures: Property.getValueOrDefault(
  107. modelGraphics._incrementallyLoadTextures,
  108. time,
  109. defaultIncrementallyLoadTextures
  110. ),
  111. scene: this._scene,
  112. });
  113. model.id = entity;
  114. primitives.add(model);
  115. modelData = {
  116. modelPrimitive: model,
  117. url: resource.url,
  118. animationsRunning: false,
  119. nodeTransformationsScratch: {},
  120. articulationsScratch: {},
  121. loadFail: false,
  122. };
  123. modelHash[entity.id] = modelData;
  124. checkModelLoad(model, entity, modelHash);
  125. }
  126. model.show = true;
  127. model.scale = Property.getValueOrDefault(
  128. modelGraphics._scale,
  129. time,
  130. defaultScale
  131. );
  132. model.minimumPixelSize = Property.getValueOrDefault(
  133. modelGraphics._minimumPixelSize,
  134. time,
  135. defaultMinimumPixelSize
  136. );
  137. model.maximumScale = Property.getValueOrUndefined(
  138. modelGraphics._maximumScale,
  139. time
  140. );
  141. model.modelMatrix = Matrix4.clone(modelMatrix, model.modelMatrix);
  142. model.shadows = Property.getValueOrDefault(
  143. modelGraphics._shadows,
  144. time,
  145. defaultShadows
  146. );
  147. model.heightReference = Property.getValueOrDefault(
  148. modelGraphics._heightReference,
  149. time,
  150. defaultHeightReference
  151. );
  152. model.distanceDisplayCondition = Property.getValueOrUndefined(
  153. modelGraphics._distanceDisplayCondition,
  154. time
  155. );
  156. model.silhouetteColor = Property.getValueOrDefault(
  157. modelGraphics._silhouetteColor,
  158. time,
  159. defaultSilhouetteColor,
  160. model._silhouetteColor
  161. );
  162. model.silhouetteSize = Property.getValueOrDefault(
  163. modelGraphics._silhouetteSize,
  164. time,
  165. defaultSilhouetteSize
  166. );
  167. model.color = Property.getValueOrDefault(
  168. modelGraphics._color,
  169. time,
  170. defaultColor,
  171. model._color
  172. );
  173. model.colorBlendMode = Property.getValueOrDefault(
  174. modelGraphics._colorBlendMode,
  175. time,
  176. defaultColorBlendMode
  177. );
  178. model.colorBlendAmount = Property.getValueOrDefault(
  179. modelGraphics._colorBlendAmount,
  180. time,
  181. defaultColorBlendAmount
  182. );
  183. model.clippingPlanes = Property.getValueOrUndefined(
  184. modelGraphics._clippingPlanes,
  185. time
  186. );
  187. model.clampAnimations = Property.getValueOrDefault(
  188. modelGraphics._clampAnimations,
  189. time,
  190. defaultClampAnimations
  191. );
  192. model.imageBasedLighting.imageBasedLightingFactor = Property.getValueOrDefault(
  193. modelGraphics._imageBasedLightingFactor,
  194. time,
  195. defaultImageBasedLightingFactor
  196. );
  197. model.lightColor = Property.getValueOrUndefined(
  198. modelGraphics._lightColor,
  199. time
  200. );
  201. if (model.ready) {
  202. const runAnimations = Property.getValueOrDefault(
  203. modelGraphics._runAnimations,
  204. time,
  205. true
  206. );
  207. if (modelData.animationsRunning !== runAnimations) {
  208. if (runAnimations) {
  209. model.activeAnimations.addAll({
  210. loop: ModelAnimationLoop.REPEAT,
  211. });
  212. } else {
  213. model.activeAnimations.removeAll();
  214. }
  215. modelData.animationsRunning = runAnimations;
  216. }
  217. // Apply node transformations
  218. const nodeTransformations = Property.getValueOrUndefined(
  219. modelGraphics._nodeTransformations,
  220. time,
  221. modelData.nodeTransformationsScratch
  222. );
  223. if (defined(nodeTransformations)) {
  224. const nodeNames = Object.keys(nodeTransformations);
  225. for (
  226. let nodeIndex = 0, nodeLength = nodeNames.length;
  227. nodeIndex < nodeLength;
  228. ++nodeIndex
  229. ) {
  230. const nodeName = nodeNames[nodeIndex];
  231. const nodeTransformation = nodeTransformations[nodeName];
  232. if (!defined(nodeTransformation)) {
  233. continue;
  234. }
  235. const modelNode = model.getNode(nodeName);
  236. if (!defined(modelNode)) {
  237. continue;
  238. }
  239. const transformationMatrix = Matrix4.fromTranslationRotationScale(
  240. nodeTransformation,
  241. nodeMatrixScratch
  242. );
  243. modelNode.matrix = Matrix4.multiply(
  244. modelNode.originalMatrix,
  245. transformationMatrix,
  246. transformationMatrix
  247. );
  248. }
  249. }
  250. // Apply articulations
  251. let anyArticulationUpdated = false;
  252. const articulations = Property.getValueOrUndefined(
  253. modelGraphics._articulations,
  254. time,
  255. modelData.articulationsScratch
  256. );
  257. if (defined(articulations)) {
  258. const articulationStageKeys = Object.keys(articulations);
  259. for (
  260. let s = 0, numKeys = articulationStageKeys.length;
  261. s < numKeys;
  262. ++s
  263. ) {
  264. const key = articulationStageKeys[s];
  265. const articulationStageValue = articulations[key];
  266. if (!defined(articulationStageValue)) {
  267. continue;
  268. }
  269. anyArticulationUpdated = true;
  270. model.setArticulationStage(key, articulationStageValue);
  271. }
  272. }
  273. if (anyArticulationUpdated) {
  274. model.applyArticulations();
  275. }
  276. }
  277. }
  278. return true;
  279. };
  280. /**
  281. * Returns true if this object was destroyed; otherwise, false.
  282. *
  283. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  284. */
  285. ModelVisualizer.prototype.isDestroyed = function () {
  286. return false;
  287. };
  288. /**
  289. * Removes and destroys all primitives created by this instance.
  290. */
  291. ModelVisualizer.prototype.destroy = function () {
  292. this._entityCollection.collectionChanged.removeEventListener(
  293. ModelVisualizer.prototype._onCollectionChanged,
  294. this
  295. );
  296. const entities = this._entitiesToVisualize.values;
  297. const modelHash = this._modelHash;
  298. const primitives = this._primitives;
  299. for (let i = entities.length - 1; i > -1; i--) {
  300. removeModel(this, entities[i], modelHash, primitives);
  301. }
  302. return destroyObject(this);
  303. };
  304. /**
  305. * Computes a bounding sphere which encloses the visualization produced for the specified entity.
  306. * The bounding sphere is in the fixed frame of the scene's globe.
  307. *
  308. * @param {Entity} entity The entity whose bounding sphere to compute.
  309. * @param {BoundingSphere} result The bounding sphere onto which to store the result.
  310. * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
  311. * BoundingSphereState.PENDING if the result is still being computed, or
  312. * BoundingSphereState.FAILED if the entity has no visualization in the current scene.
  313. * @private
  314. */
  315. ModelVisualizer.prototype.getBoundingSphere = function (entity, result) {
  316. //>>includeStart('debug', pragmas.debug);
  317. if (!defined(entity)) {
  318. throw new DeveloperError("entity is required.");
  319. }
  320. if (!defined(result)) {
  321. throw new DeveloperError("result is required.");
  322. }
  323. //>>includeEnd('debug');
  324. const modelData = this._modelHash[entity.id];
  325. if (!defined(modelData) || modelData.loadFail) {
  326. return BoundingSphereState.FAILED;
  327. }
  328. const model = modelData.modelPrimitive;
  329. if (!defined(model) || !model.show) {
  330. return BoundingSphereState.FAILED;
  331. }
  332. if (!model.ready) {
  333. return BoundingSphereState.PENDING;
  334. }
  335. if (model.heightReference === HeightReference.NONE) {
  336. BoundingSphere.transform(model.boundingSphere, model.modelMatrix, result);
  337. } else {
  338. if (!defined(model._clampedModelMatrix)) {
  339. return BoundingSphereState.PENDING;
  340. }
  341. BoundingSphere.transform(
  342. model.boundingSphere,
  343. model._clampedModelMatrix,
  344. result
  345. );
  346. }
  347. return BoundingSphereState.DONE;
  348. };
  349. /**
  350. * @private
  351. */
  352. ModelVisualizer.prototype._onCollectionChanged = function (
  353. entityCollection,
  354. added,
  355. removed,
  356. changed
  357. ) {
  358. let i;
  359. let entity;
  360. const entities = this._entitiesToVisualize;
  361. const modelHash = this._modelHash;
  362. const primitives = this._primitives;
  363. for (i = added.length - 1; i > -1; i--) {
  364. entity = added[i];
  365. if (defined(entity._model) && defined(entity._position)) {
  366. entities.set(entity.id, entity);
  367. }
  368. }
  369. for (i = changed.length - 1; i > -1; i--) {
  370. entity = changed[i];
  371. if (defined(entity._model) && defined(entity._position)) {
  372. clearNodeTransformationsArticulationsScratch(entity, modelHash);
  373. entities.set(entity.id, entity);
  374. } else {
  375. removeModel(this, entity, modelHash, primitives);
  376. entities.remove(entity.id);
  377. }
  378. }
  379. for (i = removed.length - 1; i > -1; i--) {
  380. entity = removed[i];
  381. removeModel(this, entity, modelHash, primitives);
  382. entities.remove(entity.id);
  383. }
  384. };
  385. function removeModel(visualizer, entity, modelHash, primitives) {
  386. const modelData = modelHash[entity.id];
  387. if (defined(modelData)) {
  388. primitives.removeAndDestroy(modelData.modelPrimitive);
  389. delete modelHash[entity.id];
  390. }
  391. }
  392. function clearNodeTransformationsArticulationsScratch(entity, modelHash) {
  393. const modelData = modelHash[entity.id];
  394. if (defined(modelData)) {
  395. modelData.nodeTransformationsScratch = {};
  396. modelData.articulationsScratch = {};
  397. }
  398. }
  399. function checkModelLoad(model, entity, modelHash) {
  400. model.readyPromise.catch(function (error) {
  401. console.error(error);
  402. modelHash[entity.id].loadFail = true;
  403. });
  404. }
  405. export default ModelVisualizer;