All files / engine/Source/DataSources ModelVisualizer.js

91.66% Statements 198/216
75.26% Branches 70/93
90% Functions 9/10
91.46% Lines 193/211

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561                                              1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x   1x 1x 1x                       206x 205x     204x         204x 204x 204x 204x 204x   204x                   16x 16x   16x 16x             14x       14x 14x 14x 14x                           2x       2x 2x                     1x   816x 1x       815x 815x 815x   815x 725x 725x     725x   725x         725x 725x 725x     725x     725x             725x 16x         16x                       16x   16x           16x             16x                 725x 725x 700x     25x 25x           25x           25x         25x       25x 25x         25x         25x       25x           25x         25x           25x         25x         25x       25x         25x           25x           25x 2x 2x     25x 25x             25x   25x 12x         12x 12x 12x           12x       12x         12x 1x 1x 1x       1x   1x 1x       1x 1x       1x       1x                 12x 12x         12x 1x 1x 1x       10x   10x 10x       10x 10x       12x 1x         815x               1x 17x           1x 198x       198x 198x 198x 198x 14x   198x     1x 1x                       1x   47x 1x   46x 1x       45x 45x 4x     41x 2x     39x 39x 18x     21x 13x     8x 8x   8x 8x 6x 6x 6x 6x 6x         6x 6x 6x 3x   3x       6x 6x 6x     2x 2x           1x               279x 279x 279x   279x 41x 41x 1x       279x 43x 43x 25x 25x   18x 18x       279x 2x 2x 2x         34x 34x 15x 15x         25x 25x              
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import Matrix4 from "../Core/Matrix4.js";
import Resource from "../Core/Resource.js";
import ColorBlendMode from "../Scene/ColorBlendMode.js";
import HeightReference, {
  isHeightReferenceClamp,
} from "../Scene/HeightReference.js";
import Model from "../Scene/Model/Model.js";
import ModelAnimationLoop from "../Scene/ModelAnimationLoop.js";
import ShadowMode from "../Scene/ShadowMode.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
import Cartographic from "../Core/Cartographic.js";
 
const defaultScale = 1.0;
const defaultEnableVerticalExaggeration = true;
const defaultMinimumPixelSize = 0.0;
const defaultIncrementallyLoadTextures = true;
const defaultClampAnimations = true;
const defaultShadows = ShadowMode.ENABLED;
const defaultHeightReference = HeightReference.NONE;
const defaultSilhouetteColor = Color.RED;
const defaultSilhouetteSize = 0.0;
const defaultColor = Color.WHITE;
const defaultColorBlendMode = ColorBlendMode.HIGHLIGHT;
const defaultColorBlendAmount = 0.5;
const defaultImageBasedLightingFactor = new Cartesian2(1.0, 1.0);
const defaultEnvironmentMapOptions = {
  maximumPositionEpsilon: Number.POSITIVE_INFINITY,
};
 
const modelMatrixScratch = new Matrix4();
const nodeMatrixScratch = new Matrix4();
 
const scratchColor = new Color();
const scratchArray = new Array(4);
const scratchCartesian = new Cartesian3();
 
/**
 * A {@link Visualizer} which maps {@link Entity#model} to a {@link Model}.
 * @alias ModelVisualizer
 * @constructor
 *
 * @param {Scene} scene The scene the primitives will be rendered in.
 * @param {EntityCollection} entityCollection The entityCollection to visualize.
 */
function ModelVisualizer(scene, entityCollection) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("scene", scene);
  Check.typeOf.object("entityCollection", entityCollection);
  //>>includeEnd('debug');
 
  entityCollection.collectionChanged.addEventListener(
    ModelVisualizer.prototype._onCollectionChanged,
    this,
  );
 
  this._scene = scene;
  this._primitives = scene.primitives;
  this._entityCollection = entityCollection;
  this._modelHash = {};
  this._entitiesToVisualize = new AssociativeArray();
 
  this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
 
async function createModelPrimitive(
  visualizer,
  entity,
  resource,
  incrementallyLoadTextures,
  environmentMapOptions,
) {
  const primitives = visualizer._primitives;
  const modelHash = visualizer._modelHash;
 
  try {
    const model = await Model.fromGltfAsync({
      url: resource,
      incrementallyLoadTextures: incrementallyLoadTextures,
      scene: visualizer._scene,
      environmentMapOptions: environmentMapOptions,
    });
 
    Iif (visualizer.isDestroyed() || !defined(modelHash[entity.id])) {
      return;
    }
 
    model.id = entity;
    primitives.add(model);
    modelHash[entity.id].modelPrimitive = model;
    model.errorEvent.addEventListener((error) => {
      if (!defined(modelHash[entity.id])) {
        return;
      }
 
      console.log(error);
 
      // Texture failures when incrementallyLoadTextures
      // will not affect the ability to compute the bounding sphere
      if (error.name !== "TextureError" && model.incrementallyLoadTextures) {
        modelHash[entity.id].loadFailed = true;
      }
    });
  } catch (error) {
    Iif (visualizer.isDestroyed() || !defined(modelHash[entity.id])) {
      return;
    }
 
    console.log(error);
    modelHash[entity.id].loadFailed = true;
  }
}
 
/**
 * Updates models created this visualizer to match their
 * Entity counterpart at the given time.
 *
 * @param {JulianDate} time The time to update to.
 * @returns {boolean} This function always returns true.
 */
ModelVisualizer.prototype.update = function (time) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(time)) {
    throw new DeveloperError("time is required.");
  }
  //>>includeEnd('debug');
 
  const entities = this._entitiesToVisualize.values;
  const modelHash = this._modelHash;
  const primitives = this._primitives;
 
  for (let i = 0, len = entities.length; i < len; i++) {
    const entity = entities[i];
    const modelGraphics = entity._model;
 
    let resource;
    let modelData = modelHash[entity.id];
    let show =
      entity.isShowing &&
      entity.isAvailable(time) &&
      Property.getValueOrDefault(modelGraphics._show, time, true);
 
    let modelMatrix;
    Eif (show) {
      modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);
      resource = Resource.createIfNeeded(
        Property.getValueOrUndefined(modelGraphics._uri, time),
      );
      show = defined(modelMatrix) && defined(resource);
    }
 
    Iif (!show) {
      if (defined(modelData) && modelData.modelPrimitive) {
        modelData.modelPrimitive.show = false;
      }
      continue;
    }
 
    if (!defined(modelData) || resource.url !== modelData.url) {
      Iif (defined(modelData?.modelPrimitive)) {
        primitives.removeAndDestroy(modelData.modelPrimitive);
        delete modelHash[entity.id];
      }
 
      modelData = {
        modelPrimitive: undefined,
        url: resource.url,
        animationsRunning: false,
        nodeTransformationsScratch: {},
        articulationsScratch: {},
        loadFailed: false,
        modelUpdated: false,
        environmentMapOptionsScratch: {
          ...defaultEnvironmentMapOptions,
        },
      };
      modelHash[entity.id] = modelData;
 
      const incrementallyLoadTextures = Property.getValueOrDefault(
        modelGraphics._incrementallyLoadTextures,
        time,
        defaultIncrementallyLoadTextures,
      );
 
      const environmentMapOptions = Property.getValueOrDefault(
        modelGraphics._environmentMapOptions,
        time,
        defaultEnvironmentMapOptions,
        modelData.environmentMapOptionsScratch,
      );
 
      createModelPrimitive(
        this,
        entity,
        resource,
        incrementallyLoadTextures,
        environmentMapOptions,
      );
    }
 
    const model = modelData.modelPrimitive;
    if (!defined(model)) {
      continue;
    }
 
    model.show = true;
    model.scale = Property.getValueOrDefault(
      modelGraphics._scale,
      time,
      defaultScale,
    );
 
    model.enableVerticalExaggeration = Property.getValueOrDefault(
      modelGraphics._enableVerticalExaggeration,
      time,
      defaultEnableVerticalExaggeration,
    );
 
    model.minimumPixelSize = Property.getValueOrDefault(
      modelGraphics._minimumPixelSize,
      time,
      defaultMinimumPixelSize,
    );
    model.maximumScale = Property.getValueOrUndefined(
      modelGraphics._maximumScale,
      time,
    );
    model.modelMatrix = Matrix4.clone(modelMatrix, model.modelMatrix);
    model.shadows = Property.getValueOrDefault(
      modelGraphics._shadows,
      time,
      defaultShadows,
    );
    model.heightReference = Property.getValueOrDefault(
      modelGraphics._heightReference,
      time,
      defaultHeightReference,
    );
    model.distanceDisplayCondition = Property.getValueOrUndefined(
      modelGraphics._distanceDisplayCondition,
      time,
    );
    model.silhouetteColor = Property.getValueOrDefault(
      modelGraphics._silhouetteColor,
      time,
      defaultSilhouetteColor,
      scratchColor,
    );
    model.silhouetteSize = Property.getValueOrDefault(
      modelGraphics._silhouetteSize,
      time,
      defaultSilhouetteSize,
    );
    model.color = Property.getValueOrDefault(
      modelGraphics._color,
      time,
      defaultColor,
      scratchColor,
    );
    model.colorBlendMode = Property.getValueOrDefault(
      modelGraphics._colorBlendMode,
      time,
      defaultColorBlendMode,
    );
    model.colorBlendAmount = Property.getValueOrDefault(
      modelGraphics._colorBlendAmount,
      time,
      defaultColorBlendAmount,
    );
    model.clippingPlanes = Property.getValueOrUndefined(
      modelGraphics._clippingPlanes,
      time,
    );
    model.clampAnimations = Property.getValueOrDefault(
      modelGraphics._clampAnimations,
      time,
      defaultClampAnimations,
    );
    model.imageBasedLighting.imageBasedLightingFactor =
      Property.getValueOrDefault(
        modelGraphics._imageBasedLightingFactor,
        time,
        defaultImageBasedLightingFactor,
      );
    let lightColor = Property.getValueOrUndefined(
      modelGraphics._lightColor,
      time,
    );
 
    // Convert from Color to Cartesian3
    if (defined(lightColor)) {
      Color.pack(lightColor, scratchArray, 0);
      lightColor = Cartesian3.unpack(scratchArray, 0, scratchCartesian);
    }
 
    model.lightColor = lightColor;
    model.customShader = Property.getValueOrUndefined(
      modelGraphics._customShader,
      time,
    );
 
    // It's possible for getBoundingSphere to run before
    // model becomes ready and these properties are updated
    modelHash[entity.id].modelUpdated = true;
 
    if (model.ready) {
      const runAnimations = Property.getValueOrDefault(
        modelGraphics._runAnimations,
        time,
        true,
      );
      Eif (modelData.animationsRunning !== runAnimations) {
        if (runAnimations) {
          model.activeAnimations.addAll({
            loop: ModelAnimationLoop.REPEAT,
          });
        } else E{
          model.activeAnimations.removeAll();
        }
        modelData.animationsRunning = runAnimations;
      }
 
      // Apply node transformations
      const nodeTransformations = Property.getValueOrUndefined(
        modelGraphics._nodeTransformations,
        time,
        modelData.nodeTransformationsScratch,
      );
      if (defined(nodeTransformations)) {
        const nodeNames = Object.keys(nodeTransformations);
        for (
          let nodeIndex = 0, nodeLength = nodeNames.length;
          nodeIndex < nodeLength;
          ++nodeIndex
        ) {
          const nodeName = nodeNames[nodeIndex];
 
          const nodeTransformation = nodeTransformations[nodeName];
          Iif (!defined(nodeTransformation)) {
            continue;
          }
 
          const modelNode = model.getNode(nodeName);
          Iif (!defined(modelNode)) {
            continue;
          }
 
          const transformationMatrix = Matrix4.fromTranslationRotationScale(
            nodeTransformation,
            nodeMatrixScratch,
          );
          modelNode.matrix = Matrix4.multiply(
            modelNode.originalMatrix,
            transformationMatrix,
            transformationMatrix,
          );
        }
      }
 
      // Apply articulations
      let anyArticulationUpdated = false;
      const articulations = Property.getValueOrUndefined(
        modelGraphics._articulations,
        time,
        modelData.articulationsScratch,
      );
      if (defined(articulations)) {
        const articulationStageKeys = Object.keys(articulations);
        for (
          let s = 0, numKeys = articulationStageKeys.length;
          s < numKeys;
          ++s
        ) {
          const key = articulationStageKeys[s];
 
          const articulationStageValue = articulations[key];
          Iif (!defined(articulationStageValue)) {
            continue;
          }
 
          anyArticulationUpdated = true;
          model.setArticulationStage(key, articulationStageValue);
        }
      }
 
      if (anyArticulationUpdated) {
        model.applyArticulations();
      }
    }
  }
 
  return true;
};
 
/**
 * Returns true if this object was destroyed; otherwise, false.
 *
 * @returns {boolean} True if this object was destroyed; otherwise, false.
 */
ModelVisualizer.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Removes and destroys all primitives created by this instance.
 */
ModelVisualizer.prototype.destroy = function () {
  this._entityCollection.collectionChanged.removeEventListener(
    ModelVisualizer.prototype._onCollectionChanged,
    this,
  );
  const entities = this._entitiesToVisualize.values;
  const modelHash = this._modelHash;
  const primitives = this._primitives;
  for (let i = entities.length - 1; i > -1; i--) {
    removeModel(this, entities[i], modelHash, primitives);
  }
  return destroyObject(this);
};
 
const scratchPosition = new Cartesian3();
const scratchCartographic = new Cartographic();
/**
 * Computes a bounding sphere which encloses the visualization produced for the specified entity.
 * The bounding sphere is in the fixed frame of the scene's globe.
 *
 * @param {Entity} entity The entity whose bounding sphere to compute.
 * @param {BoundingSphere} result The bounding sphere onto which to store the result.
 * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
 *                       BoundingSphereState.PENDING if the result is still being computed, or
 *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
 * @private
 */
ModelVisualizer.prototype.getBoundingSphere = function (entity, result) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(entity)) {
    throw new DeveloperError("entity is required.");
  }
  if (!defined(result)) {
    throw new DeveloperError("result is required.");
  }
  //>>includeEnd('debug');
 
  const modelData = this._modelHash[entity.id];
  if (!defined(modelData)) {
    return BoundingSphereState.FAILED;
  }
 
  if (modelData.loadFailed) {
    return BoundingSphereState.FAILED;
  }
 
  const model = modelData.modelPrimitive;
  if (!defined(model) || !model.show) {
    return BoundingSphereState.PENDING;
  }
 
  if (!model.ready || !modelData.modelUpdated) {
    return BoundingSphereState.PENDING;
  }
 
  const scene = this._scene;
  const ellipsoid = scene.ellipsoid ?? Ellipsoid.default;
 
  const hasHeightReference = model.heightReference !== HeightReference.NONE;
  if (hasHeightReference) {
    const modelMatrix = model.modelMatrix;
    scratchPosition.x = modelMatrix[12];
    scratchPosition.y = modelMatrix[13];
    scratchPosition.z = modelMatrix[14];
    const cartoPosition = ellipsoid.cartesianToCartographic(
      scratchPosition,
      scratchCartographic,
    );
 
    const height = scene.getHeight(cartoPosition, model.heightReference);
    Eif (defined(height)) {
      if (isHeightReferenceClamp(model.heightReference)) {
        cartoPosition.height = height;
      } else {
        cartoPosition.height += height;
      }
    }
 
    BoundingSphere.clone(model.boundingSphere, result);
    result.center = ellipsoid.cartographicToCartesian(cartoPosition);
    return BoundingSphereState.DONE;
  }
 
  BoundingSphere.clone(model.boundingSphere, result);
  return BoundingSphereState.DONE;
};
 
/**
 * @private
 */
ModelVisualizer.prototype._onCollectionChanged = function (
  entityCollection,
  added,
  removed,
  changed,
) {
  let i;
  let entity;
  const entities = this._entitiesToVisualize;
  const modelHash = this._modelHash;
  const primitives = this._primitives;
 
  for (i = added.length - 1; i > -1; i--) {
    entity = added[i];
    if (defined(entity._model) && defined(entity._position)) {
      entities.set(entity.id, entity);
    }
  }
 
  for (i = changed.length - 1; i > -1; i--) {
    entity = changed[i];
    if (defined(entity._model) && defined(entity._position)) {
      clearNodeTransformationsArticulationsScratch(entity, modelHash);
      entities.set(entity.id, entity);
    } else {
      removeModel(this, entity, modelHash, primitives);
      entities.remove(entity.id);
    }
  }
 
  for (i = removed.length - 1; i > -1; i--) {
    entity = removed[i];
    removeModel(this, entity, modelHash, primitives);
    entities.remove(entity.id);
  }
};
 
function removeModel(visualizer, entity, modelHash, primitives) {
  const modelData = modelHash[entity.id];
  if (defined(modelData)) {
    primitives.removeAndDestroy(modelData.modelPrimitive);
    delete modelHash[entity.id];
  }
}
 
function clearNodeTransformationsArticulationsScratch(entity, modelHash) {
  const modelData = modelHash[entity.id];
  Iif (defined(modelData)) {
    modelData.nodeTransformationsScratch = {};
    modelData.articulationsScratch = {};
  }
}
 
export default ModelVisualizer;