ModelVisualizer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. var defaultScale = 1.0;
  18. var defaultMinimumPixelSize = 0.0;
  19. var defaultIncrementallyLoadTextures = true;
  20. var defaultClampAnimations = true;
  21. var defaultShadows = ShadowMode.ENABLED;
  22. var defaultHeightReference = HeightReference.NONE;
  23. var defaultSilhouetteColor = Color.RED;
  24. var defaultSilhouetteSize = 0.0;
  25. var defaultColor = Color.WHITE;
  26. var defaultColorBlendMode = ColorBlendMode.HIGHLIGHT;
  27. var defaultColorBlendAmount = 0.5;
  28. var defaultImageBasedLightingFactor = new Cartesian2(1.0, 1.0);
  29. var modelMatrixScratch = new Matrix4();
  30. var 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(ModelVisualizer.prototype._onCollectionChanged, this);
  49. this._scene = scene;
  50. this._primitives = scene.primitives;
  51. this._entityCollection = entityCollection;
  52. this._modelHash = {};
  53. this._entitiesToVisualize = new AssociativeArray();
  54. this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
  55. }
  56. /**
  57. * Updates models created this visualizer to match their
  58. * Entity counterpart at the given time.
  59. *
  60. * @param {JulianDate} time The time to update to.
  61. * @returns {Boolean} This function always returns true.
  62. */
  63. ModelVisualizer.prototype.update = function(time) {
  64. //>>includeStart('debug', pragmas.debug);
  65. if (!defined(time)) {
  66. throw new DeveloperError('time is required.');
  67. }
  68. //>>includeEnd('debug');
  69. var entities = this._entitiesToVisualize.values;
  70. var modelHash = this._modelHash;
  71. var primitives = this._primitives;
  72. for (var i = 0, len = entities.length; i < len; i++) {
  73. var entity = entities[i];
  74. var modelGraphics = entity._model;
  75. var resource;
  76. var modelData = modelHash[entity.id];
  77. var show = entity.isShowing && entity.isAvailable(time) && Property.getValueOrDefault(modelGraphics._show, time, true);
  78. var modelMatrix;
  79. if (show) {
  80. modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);
  81. resource = Resource.createIfNeeded(Property.getValueOrUndefined(modelGraphics._uri, time));
  82. show = defined(modelMatrix) && defined(resource);
  83. }
  84. if (!show) {
  85. if (defined(modelData)) {
  86. modelData.modelPrimitive.show = false;
  87. }
  88. continue;
  89. }
  90. var model = defined(modelData) ? modelData.modelPrimitive : undefined;
  91. if (!defined(model) || resource.url !== modelData.url) {
  92. if (defined(model)) {
  93. primitives.removeAndDestroy(model);
  94. delete modelHash[entity.id];
  95. }
  96. model = Model.fromGltf({
  97. url : resource,
  98. incrementallyLoadTextures : Property.getValueOrDefault(modelGraphics._incrementallyLoadTextures, time, defaultIncrementallyLoadTextures),
  99. scene : this._scene
  100. });
  101. model.id = entity;
  102. primitives.add(model);
  103. modelData = {
  104. modelPrimitive : model,
  105. url : resource.url,
  106. animationsRunning : false,
  107. nodeTransformationsScratch : {},
  108. articulationsScratch : {},
  109. loadFail : false
  110. };
  111. modelHash[entity.id] = modelData;
  112. checkModelLoad(model, entity, modelHash);
  113. }
  114. model.show = true;
  115. model.scale = Property.getValueOrDefault(modelGraphics._scale, time, defaultScale);
  116. model.minimumPixelSize = Property.getValueOrDefault(modelGraphics._minimumPixelSize, time, defaultMinimumPixelSize);
  117. model.maximumScale = Property.getValueOrUndefined(modelGraphics._maximumScale, time);
  118. model.modelMatrix = Matrix4.clone(modelMatrix, model.modelMatrix);
  119. model.shadows = Property.getValueOrDefault(modelGraphics._shadows, time, defaultShadows);
  120. model.heightReference = Property.getValueOrDefault(modelGraphics._heightReference, time, defaultHeightReference);
  121. model.distanceDisplayCondition = Property.getValueOrUndefined(modelGraphics._distanceDisplayCondition, time);
  122. model.silhouetteColor = Property.getValueOrDefault(modelGraphics._silhouetteColor, time, defaultSilhouetteColor, model._silhouetteColor);
  123. model.silhouetteSize = Property.getValueOrDefault(modelGraphics._silhouetteSize, time, defaultSilhouetteSize);
  124. model.color = Property.getValueOrDefault(modelGraphics._color, time, defaultColor, model._color);
  125. model.colorBlendMode = Property.getValueOrDefault(modelGraphics._colorBlendMode, time, defaultColorBlendMode);
  126. model.colorBlendAmount = Property.getValueOrDefault(modelGraphics._colorBlendAmount, time, defaultColorBlendAmount);
  127. model.clippingPlanes = Property.getValueOrUndefined(modelGraphics._clippingPlanes, time);
  128. model.clampAnimations = Property.getValueOrDefault(modelGraphics._clampAnimations, time, defaultClampAnimations);
  129. model.imageBasedLightingFactor = Property.getValueOrDefault(modelGraphics._imageBasedLightingFactor, time, defaultImageBasedLightingFactor);
  130. model.lightColor = Property.getValueOrUndefined(modelGraphics._lightColor, time);
  131. if (model.ready) {
  132. var runAnimations = Property.getValueOrDefault(modelGraphics._runAnimations, time, true);
  133. if (modelData.animationsRunning !== runAnimations) {
  134. if (runAnimations) {
  135. model.activeAnimations.addAll({
  136. loop : ModelAnimationLoop.REPEAT
  137. });
  138. } else {
  139. model.activeAnimations.removeAll();
  140. }
  141. modelData.animationsRunning = runAnimations;
  142. }
  143. // Apply node transformations
  144. var nodeTransformations = Property.getValueOrUndefined(modelGraphics._nodeTransformations, time, modelData.nodeTransformationsScratch);
  145. if (defined(nodeTransformations)) {
  146. var nodeNames = Object.keys(nodeTransformations);
  147. for (var nodeIndex = 0, nodeLength = nodeNames.length; nodeIndex < nodeLength; ++nodeIndex) {
  148. var nodeName = nodeNames[nodeIndex];
  149. var nodeTransformation = nodeTransformations[nodeName];
  150. if (!defined(nodeTransformation)) {
  151. continue;
  152. }
  153. var modelNode = model.getNode(nodeName);
  154. if (!defined(modelNode)) {
  155. continue;
  156. }
  157. var transformationMatrix = Matrix4.fromTranslationRotationScale(nodeTransformation, nodeMatrixScratch);
  158. modelNode.matrix = Matrix4.multiply(modelNode.originalMatrix, transformationMatrix, transformationMatrix);
  159. }
  160. }
  161. // Apply articulations
  162. var anyArticulationUpdated = false;
  163. var articulations = Property.getValueOrUndefined(modelGraphics._articulations, time, modelData.articulationsScratch);
  164. if (defined(articulations)) {
  165. var articulationStageKeys = Object.keys(articulations);
  166. for (var s = 0, numKeys = articulationStageKeys.length; s < numKeys; ++s) {
  167. var key = articulationStageKeys[s];
  168. var articulationStageValue = articulations[key];
  169. if (!defined(articulationStageValue)) {
  170. continue;
  171. }
  172. anyArticulationUpdated = true;
  173. model.setArticulationStage(key, articulationStageValue);
  174. }
  175. }
  176. if (anyArticulationUpdated) {
  177. model.applyArticulations();
  178. }
  179. }
  180. }
  181. return true;
  182. };
  183. /**
  184. * Returns true if this object was destroyed; otherwise, false.
  185. *
  186. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  187. */
  188. ModelVisualizer.prototype.isDestroyed = function() {
  189. return false;
  190. };
  191. /**
  192. * Removes and destroys all primitives created by this instance.
  193. */
  194. ModelVisualizer.prototype.destroy = function() {
  195. this._entityCollection.collectionChanged.removeEventListener(ModelVisualizer.prototype._onCollectionChanged, this);
  196. var entities = this._entitiesToVisualize.values;
  197. var modelHash = this._modelHash;
  198. var primitives = this._primitives;
  199. for (var i = entities.length - 1; i > -1; i--) {
  200. removeModel(this, entities[i], modelHash, primitives);
  201. }
  202. return destroyObject(this);
  203. };
  204. /**
  205. * Computes a bounding sphere which encloses the visualization produced for the specified entity.
  206. * The bounding sphere is in the fixed frame of the scene's globe.
  207. *
  208. * @param {Entity} entity The entity whose bounding sphere to compute.
  209. * @param {BoundingSphere} result The bounding sphere onto which to store the result.
  210. * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
  211. * BoundingSphereState.PENDING if the result is still being computed, or
  212. * BoundingSphereState.FAILED if the entity has no visualization in the current scene.
  213. * @private
  214. */
  215. ModelVisualizer.prototype.getBoundingSphere = function(entity, result) {
  216. //>>includeStart('debug', pragmas.debug);
  217. if (!defined(entity)) {
  218. throw new DeveloperError('entity is required.');
  219. }
  220. if (!defined(result)) {
  221. throw new DeveloperError('result is required.');
  222. }
  223. //>>includeEnd('debug');
  224. var modelData = this._modelHash[entity.id];
  225. if (!defined(modelData) || modelData.loadFail) {
  226. return BoundingSphereState.FAILED;
  227. }
  228. var model = modelData.modelPrimitive;
  229. if (!defined(model) || !model.show) {
  230. return BoundingSphereState.FAILED;
  231. }
  232. if (!model.ready) {
  233. return BoundingSphereState.PENDING;
  234. }
  235. if (model.heightReference === HeightReference.NONE) {
  236. BoundingSphere.transform(model.boundingSphere, model.modelMatrix, result);
  237. } else {
  238. if (!defined(model._clampedModelMatrix)) {
  239. return BoundingSphereState.PENDING;
  240. }
  241. BoundingSphere.transform(model.boundingSphere, model._clampedModelMatrix, result);
  242. }
  243. return BoundingSphereState.DONE;
  244. };
  245. /**
  246. * @private
  247. */
  248. ModelVisualizer.prototype._onCollectionChanged = function(entityCollection, added, removed, changed) {
  249. var i;
  250. var entity;
  251. var entities = this._entitiesToVisualize;
  252. var modelHash = this._modelHash;
  253. var primitives = this._primitives;
  254. for (i = added.length - 1; i > -1; i--) {
  255. entity = added[i];
  256. if (defined(entity._model) && defined(entity._position)) {
  257. entities.set(entity.id, entity);
  258. }
  259. }
  260. for (i = changed.length - 1; i > -1; i--) {
  261. entity = changed[i];
  262. if (defined(entity._model) && defined(entity._position)) {
  263. clearNodeTransformationsArticulationsScratch(entity, modelHash);
  264. entities.set(entity.id, entity);
  265. } else {
  266. removeModel(this, entity, modelHash, primitives);
  267. entities.remove(entity.id);
  268. }
  269. }
  270. for (i = removed.length - 1; i > -1; i--) {
  271. entity = removed[i];
  272. removeModel(this, entity, modelHash, primitives);
  273. entities.remove(entity.id);
  274. }
  275. };
  276. function removeModel(visualizer, entity, modelHash, primitives) {
  277. var modelData = modelHash[entity.id];
  278. if (defined(modelData)) {
  279. primitives.removeAndDestroy(modelData.modelPrimitive);
  280. delete modelHash[entity.id];
  281. }
  282. }
  283. function clearNodeTransformationsArticulationsScratch(entity, modelHash) {
  284. var modelData = modelHash[entity.id];
  285. if (defined(modelData)) {
  286. modelData.nodeTransformationsScratch = {};
  287. modelData.articulationsScratch = {};
  288. }
  289. }
  290. function checkModelLoad(model, entity, modelHash){
  291. model.readyPromise.otherwise(function(error){
  292. console.error(error);
  293. modelHash[entity.id].loadFail = true;
  294. });
  295. }
  296. export default ModelVisualizer;