All files / engine/Source/Scene/Model ModelSceneGraph.js

95.38% Statements 310/325
82.25% Branches 51/62
100% Functions 29/29
95.08% Lines 290/305

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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099                                                                                      1536x 1536x     1536x 1535x                     1534x                   1534x                   1534x                   1534x                   1534x                   1534x                       1534x                   1534x                       1534x         1534x         1534x   1534x 1534x   1534x               1534x   1534x     1x                     10275x                           49x                             5x                             3444x           1534x 1534x 1534x       1534x 1534x   1534x 1534x   1534x 1534x 13x 13x         13x 13x     1534x 1534x           1534x   1534x 1534x 1534x 1534x 1620x   1620x           1620x       1534x 1534x   1534x 1534x 9x 9x               1534x 1534x 1534x 9x 9x       9x 9x   9x 9x       1534x       3013x 3013x   3013x           3013x           3013x             1x     18x 18x         18x 18x                                     18x                                       1956x 1956x     1956x 1956x 336x 336x           336x         336x       1956x               1956x 1956x 1565x                 1956x 1956x 1956x 9x       1956x 1956x 586x 586x 586x     1956x     1x 1x 1x 1x                       1x 1746x 1745x 1745x                                         1x 1746x 1746x     1746x   1746x 1746x   1746x 3885x 3885x     1746x 2285x       2285x       2285x 2285x   2285x       2285x   2285x 2367x   2367x             2285x 1776x   1776x 1776x   1776x       1776x     1776x 20699x 20699x               1745x                                             1x     1745x   1745x           1745x             1745x 2284x       2284x       2284x 2284x 2284x 1775x     1775x   1775x         1775x         1775x           1775x         1775x               1745x           1745x           1745x           1745x           1745x 1745x                           1x       1745x 2284x       2284x       2284x   2284x 1775x     1775x   1775x       1775x                         1x 1746x 1746x   1746x 1746x   1746x 48x       1746x 4x     1742x 785x     1742x 34x     1742x       1742x 10x     1742x             1742x 1344x     1742x 1664x       1x     10820x 14570x       14570x       14570x 14570x 14570x       14570x 14570x 45x     14570x 10912x 10912x               1x       1479x 1479x 18x         1479x 1479x 1488x 1488x                 1x 45x 45x   45x                                                                           9506x 3x     9503x 9503x 1205x 1205x                 9503x 9503x 9503x 8377x 8377x                   8288x 8288x 8288x 8301x 8301x 8301x                   1x                     1x 5x 5x 5x                   5x 5x     1x                     1x 26x 26x 26x         26x 26x     1x                     1x     1x 1x   1x                   1x 1x     1x 1x 1x                         1x         8256x 8256x     8256x 8256x       8256x 8256x 8256x   8256x             8256x 8256x         8345x 8345x   8345x 8345x 8345x 8345x 8345x           8345x 11x       8345x 8322x                       1x       24x 24x       24x 24x   24x 24x 24x                   1x 1540x 1540x 19x 19x 19x            
import BoundingSphere from "../../Core/BoundingSphere.js";
import Cartesian3 from "../../Core/Cartesian3.js";
import Check from "../../Core/Check.js";
import Frozen from "../../Core/Frozen.js";
import defined from "../../Core/defined.js";
import Matrix4 from "../../Core/Matrix4.js";
import Transforms from "../../Core/Transforms.js";
import SceneMode from "../SceneMode.js";
import SplitDirection from "../SplitDirection.js";
import TilesetPipelineStage from "./TilesetPipelineStage.js";
import AtmospherePipelineStage from "./AtmospherePipelineStage.js";
import ImageBasedLightingPipelineStage from "./ImageBasedLightingPipelineStage.js";
import ModelArticulation from "./ModelArticulation.js";
import ModelColorPipelineStage from "./ModelColorPipelineStage.js";
import ModelClippingPlanesPipelineStage from "./ModelClippingPlanesPipelineStage.js";
import ModelClippingPolygonsPipelineStage from "./ModelClippingPolygonsPipelineStage.js";
import ModelNode from "./ModelNode.js";
import ModelRuntimeNode from "./ModelRuntimeNode.js";
import ModelRuntimePrimitive from "./ModelRuntimePrimitive.js";
import ModelSkin from "./ModelSkin.js";
import ModelUtility from "./ModelUtility.js";
import ModelRenderResources from "./ModelRenderResources.js";
import ModelSilhouettePipelineStage from "./ModelSilhouettePipelineStage.js";
import ModelSplitterPipelineStage from "./ModelSplitterPipelineStage.js";
import ModelType from "./ModelType.js";
import NodeRenderResources from "./NodeRenderResources.js";
import PrimitiveRenderResources from "./PrimitiveRenderResources.js";
import ModelDrawCommands from "./ModelDrawCommands.js";
import addAllToArray from "../../Core/addAllToArray.js";
 
/**
 * An in memory representation of the scene graph for a {@link Model}
 *
 * @param {object} options An object containing the following options
 * @param {Model} options.model The model this scene graph belongs to
 * @param {ModelComponents} options.modelComponents The model components describing the model
 *
 * @alias ModelSceneGraph
 * @constructor
 *
 * @private
 */
function ModelSceneGraph(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const components = options.modelComponents;
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options.model", options.model);
  Check.typeOf.object("options.modelComponents", components);
  //>>includeEnd('debug');
 
  /**
   * A reference to the {@link Model} that owns this scene graph.
   *
   * @type {Model}
   * @readonly
   *
   * @private
   */
  this._model = options.model;
 
  /**
   * The model components that represent the contents of the 3D model file.
   *
   * @type {ModelComponents}
   * @readonly
   *
   * @private
   */
  this._components = components;
 
  /**
   * Pipeline stages to apply across the model.
   *
   * @type {object[]}
   * @readonly
   *
   * @private
   */
  this._pipelineStages = [];
 
  /**
   * Update stages to apply across the model.
   *
   * @type {object[]}
   * @readonly
   *
   * @private
   */
  this._updateStages = [];
 
  /**
   * The runtime nodes that make up the scene graph
   *
   * @type {ModelRuntimeNode[]}
   * @readonly
   *
   * @private
   */
  this._runtimeNodes = [];
 
  /**
   * The indices of the root nodes in the runtime nodes array.
   *
   * @type {number[]}
   * @readonly
   *
   * @private
   */
  this._rootNodes = [];
 
  /**
   * The indices of the skinned nodes in the runtime nodes array. These refer
   * to the nodes that will be manipulated by their skin, as opposed to the nodes
   * acting as joints for the skin.
   *
   * @type {number[]}
   * @readonly
   *
   * @private
   */
  this._skinnedNodes = [];
 
  /**
   * The runtime skins that affect nodes in the scene graph.
   *
   * @type {ModelSkin[]}
   * @readonly
   *
   * @private
   */
  this._runtimeSkins = [];
 
  /**
   * Pipeline stages to apply to this model. This
   * is an array of classes, each with a static method called
   * <code>process()</code>
   *
   * @type {object[]}
   * @readonly
   *
   * @private
   */
  this.modelPipelineStages = [];
 
  // The scene graph's bounding sphere is model space, so that
  // the model's bounding sphere can be recomputed when given a
  // new model matrix.
  this._boundingSphere = undefined;
 
  // The 2D bounding sphere is in world space. This is checked
  // by the draw commands to see if the model is over the IDL,
  // and if so, renders the primitives using extra commands.
  this._boundingSphere2D = undefined;
 
  this._computedModelMatrix = Matrix4.clone(Matrix4.IDENTITY);
  this._computedModelMatrix2D = Matrix4.clone(Matrix4.IDENTITY);
 
  this._axisCorrectionMatrix = ModelUtility.getAxisCorrectionMatrix(
    components.upAxis,
    components.forwardAxis,
    new Matrix4(),
  );
 
  // Store articulations from the AGI_articulations extension
  // by name in a dictionary for easy retrieval.
  this._runtimeArticulations = {};
 
  initialize(this);
}
 
Object.defineProperties(ModelSceneGraph.prototype, {
  /**
   * The model components this scene graph represents.
   *
   * @type {ModelComponents}
   * @readonly
   *
   * @private
   */
  components: {
    get: function () {
      return this._components;
    },
  },
 
  /**
   * The axis-corrected model matrix.
   *
   * @type {Matrix4}
   * @readonly
   *
   * @private
   */
  computedModelMatrix: {
    get: function () {
      return this._computedModelMatrix;
    },
  },
 
  /**
   * A matrix to correct from y-up in some model formats (e.g. glTF) to the
   * z-up coordinate system Cesium uses.
   *
   * @type {Matrix4}
   * @readonly
   *
   * @private
   */
  axisCorrectionMatrix: {
    get: function () {
      return this._axisCorrectionMatrix;
    },
  },
 
  /**
   * The bounding sphere containing all the primitives in the scene graph
   * in model space.
   *
   * @type {BoundingSphere}
   * @readonly
   *
   * @private
   */
  boundingSphere: {
    get: function () {
      return this._boundingSphere;
    },
  },
});
 
function initialize(sceneGraph) {
  const components = sceneGraph._components;
  const scene = components.scene;
  const model = sceneGraph._model;
 
  // If the model has a height reference that modifies the model matrix,
  // it will be accounted for in updateModelMatrix.
  const modelMatrix = model.modelMatrix;
  computeModelMatrix(sceneGraph, modelMatrix);
 
  const articulations = components.articulations;
  const articulationsLength = articulations.length;
 
  const runtimeArticulations = sceneGraph._runtimeArticulations;
  for (let i = 0; i < articulationsLength; i++) {
    const articulation = articulations[i];
    const runtimeArticulation = new ModelArticulation({
      articulation: articulation,
      sceneGraph: sceneGraph,
    });
 
    const name = runtimeArticulation.name;
    runtimeArticulations[name] = runtimeArticulation;
  }
 
  const nodes = components.nodes;
  const nodesLength = nodes.length;
 
  // Initialize this array to be the same size as the nodes array in
  // the model file. This is so the node indices remain the same. However,
  // only nodes reachable from the scene's root node will be populated, the
  // rest will be undefined
  sceneGraph._runtimeNodes = new Array(nodesLength);
 
  const rootNodes = scene.nodes;
  const rootNodesLength = rootNodes.length;
  const transformToRoot = Matrix4.IDENTITY;
  for (let i = 0; i < rootNodesLength; i++) {
    const rootNode = scene.nodes[i];
 
    const rootNodeIndex = traverseAndCreateSceneGraph(
      sceneGraph,
      rootNode,
      transformToRoot,
    );
 
    sceneGraph._rootNodes.push(rootNodeIndex);
  }
 
  // Handle skins after all runtime nodes are created
  const skins = components.skins;
  const runtimeSkins = sceneGraph._runtimeSkins;
 
  const skinsLength = skins.length;
  for (let i = 0; i < skinsLength; i++) {
    const skin = skins[i];
    runtimeSkins.push(
      new ModelSkin({
        skin: skin,
        sceneGraph: sceneGraph,
      }),
    );
  }
 
  const skinnedNodes = sceneGraph._skinnedNodes;
  const skinnedNodesLength = skinnedNodes.length;
  for (let i = 0; i < skinnedNodesLength; i++) {
    const skinnedNodeIndex = skinnedNodes[i];
    const skinnedNode = sceneGraph._runtimeNodes[skinnedNodeIndex];
 
    // Use the index of the skin in the model components to find
    // the corresponding runtime skin.
    const skin = nodes[skinnedNodeIndex].skin;
    const skinIndex = skin.index;
 
    skinnedNode._runtimeSkin = runtimeSkins[skinIndex];
    skinnedNode.updateJointMatrices();
  }
 
  // Ensure articulations are applied with their initial values to their target nodes.
  sceneGraph.applyArticulations();
}
 
function computeModelMatrix(sceneGraph, modelMatrix) {
  const components = sceneGraph._components;
  const model = sceneGraph._model;
 
  sceneGraph._computedModelMatrix = Matrix4.multiplyTransformation(
    modelMatrix,
    components.transform,
    sceneGraph._computedModelMatrix,
  );
 
  sceneGraph._computedModelMatrix = Matrix4.multiplyTransformation(
    sceneGraph._computedModelMatrix,
    sceneGraph._axisCorrectionMatrix,
    sceneGraph._computedModelMatrix,
  );
 
  sceneGraph._computedModelMatrix = Matrix4.multiplyByUniformScale(
    sceneGraph._computedModelMatrix,
    model.computedScale,
    sceneGraph._computedModelMatrix,
  );
}
 
const scratchComputedTranslation = new Cartesian3();
 
function computeModelMatrix2D(sceneGraph, frameState) {
  const computedModelMatrix = sceneGraph._computedModelMatrix;
  const translation = Matrix4.getTranslation(
    computedModelMatrix,
    scratchComputedTranslation,
  );
 
  if (!Cartesian3.equals(translation, Cartesian3.ZERO)) {
    sceneGraph._computedModelMatrix2D = Transforms.basisTo2D(
      frameState.mapProjection,
      computedModelMatrix,
      sceneGraph._computedModelMatrix2D,
    );
  } else E{
    const center = sceneGraph.boundingSphere.center;
    const to2D = Transforms.ellipsoidTo2DModelMatrix(
      frameState.mapProjection,
      center,
      sceneGraph._computedModelMatrix2D,
    );
    sceneGraph._computedModelMatrix2D = Matrix4.multiply(
      to2D,
      computedModelMatrix,
      sceneGraph._computedModelMatrix2D,
    );
  }
 
  sceneGraph._boundingSphere2D = BoundingSphere.transform(
    sceneGraph._boundingSphere,
    sceneGraph._computedModelMatrix2D,
    sceneGraph._boundingSphere2D,
  );
}
 
/**
 * Recursively traverse through the nodes in the scene graph to create
 * their runtime versions, using a post-order depth-first traversal.
 *
 * @param {ModelSceneGraph} sceneGraph The scene graph
 * @param {ModelComponents.Node} node The current node
 * @param {Matrix4} transformToRoot The transforms of this node's ancestors.
 * @returns {number} The index of this node in the runtimeNodes array.
 *
 * @private
 */
function traverseAndCreateSceneGraph(sceneGraph, node, transformToRoot) {
  // The indices of the children of this node in the runtimeNodes array.
  const childrenIndices = [];
  const transform = ModelUtility.getNodeTransform(node);
 
  // Traverse through scene graph.
  const childrenLength = node.children.length;
  for (let i = 0; i < childrenLength; i++) {
    const childNode = node.children[i];
    const childNodeTransformToRoot = Matrix4.multiplyTransformation(
      transformToRoot,
      transform,
      new Matrix4(),
    );
 
    const childIndex = traverseAndCreateSceneGraph(
      sceneGraph,
      childNode,
      childNodeTransformToRoot,
    );
    childrenIndices.push(childIndex);
  }
 
  // Process node and mesh primitives.
  const runtimeNode = new ModelRuntimeNode({
    node: node,
    transform: transform,
    transformToRoot: transformToRoot,
    children: childrenIndices,
    sceneGraph: sceneGraph,
  });
 
  const primitivesLength = node.primitives.length;
  for (let i = 0; i < primitivesLength; i++) {
    runtimeNode.runtimePrimitives.push(
      new ModelRuntimePrimitive({
        primitive: node.primitives[i],
        node: node,
        model: sceneGraph._model,
      }),
    );
  }
 
  const index = node.index;
  sceneGraph._runtimeNodes[index] = runtimeNode;
  if (defined(node.skin)) {
    sceneGraph._skinnedNodes.push(index);
  }
 
  // Create and store the public version of the runtime node.
  const name = node.name;
  if (defined(name)) {
    const model = sceneGraph._model;
    const publicNode = new ModelNode(model, runtimeNode);
    model._nodesByName[name] = publicNode;
  }
 
  return index;
}
 
const scratchModelPositionMin = new Cartesian3();
const scratchModelPositionMax = new Cartesian3();
const scratchPrimitivePositionMin = new Cartesian3();
const scratchPrimitivePositionMax = new Cartesian3();
 
/**
 * Generates the {@link ModelDrawCommand} for each primitive in the model.
 * If the model is used for classification, a {@link ClassificationModelDrawCommand}
 * is generated for each primitive instead.
 *
 * @param {FrameState} frameState The current frame state. This is needed to
 * allocate GPU resources as needed.
 *
 * @private
 */
ModelSceneGraph.prototype.buildDrawCommands = function (frameState) {
  const modelRenderResources = this.buildRenderResources(frameState);
  this.computeBoundingVolumes(modelRenderResources);
  this.createDrawCommands(modelRenderResources, frameState);
};
 
/**
 * Generates the {@link ModelRenderResources} for the model.
 *
 * This will traverse the model, nodes and primitives of the scene graph,
 * and perform the following tasks:
 *
 * - configure the pipeline stages by calling `configurePipeline`,
 *   `runtimeNode.configurePipeline`, and `runtimePrimitive.configurePipeline`
 * - create the `ModelRenderResources`, `NodeRenderResources`, and
 *   `PrimitiveRenderResources`
 * - Process the render resources with the respective pipelines
 *
 * @param {FrameState} frameState The current frame state. This is needed to
 * allocate GPU resources as needed.
 * @returns {ModelRenderResources} The model render resources
 *
 * @private
 */
ModelSceneGraph.prototype.buildRenderResources = function (frameState) {
  const model = this._model;
  const modelRenderResources = new ModelRenderResources(model);
 
  // Reset the memory counts before running the pipeline
  model.statistics.clear();
 
  this.configurePipeline(frameState);
  const modelPipelineStages = this.modelPipelineStages;
 
  for (let i = 0; i < modelPipelineStages.length; i++) {
    const modelPipelineStage = modelPipelineStages[i];
    modelPipelineStage.process(modelRenderResources, model, frameState);
  }
 
  for (let i = 0; i < this._runtimeNodes.length; i++) {
    const runtimeNode = this._runtimeNodes[i];
 
    // If a node in the model was unreachable from the scene graph, there will
    // be no corresponding runtime node and therefore should be skipped.
    Iif (!defined(runtimeNode)) {
      continue;
    }
 
    runtimeNode.configurePipeline();
    const nodePipelineStages = runtimeNode.pipelineStages;
 
    const nodeRenderResources = new NodeRenderResources(
      modelRenderResources,
      runtimeNode,
    );
    modelRenderResources.nodeRenderResources[i] = nodeRenderResources;
 
    for (let j = 0; j < nodePipelineStages.length; j++) {
      const nodePipelineStage = nodePipelineStages[j];
 
      nodePipelineStage.process(
        nodeRenderResources,
        runtimeNode.node,
        frameState,
      );
    }
 
    for (let j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
      const runtimePrimitive = runtimeNode.runtimePrimitives[j];
 
      runtimePrimitive.configurePipeline(frameState);
      const primitivePipelineStages = runtimePrimitive.pipelineStages;
 
      const primitiveRenderResources = new PrimitiveRenderResources(
        nodeRenderResources,
        runtimePrimitive,
      );
      nodeRenderResources.primitiveRenderResources[j] =
        primitiveRenderResources;
 
      for (let k = 0; k < primitivePipelineStages.length; k++) {
        const primitivePipelineStage = primitivePipelineStages[k];
        primitivePipelineStage.process(
          primitiveRenderResources,
          runtimePrimitive.primitive,
          frameState,
        );
      }
    }
  }
  return modelRenderResources;
};
 
/**
 * Computes the bounding volumes for the scene graph and the model.
 *
 * This will traverse the model, nodes and primitives of the scene graph,
 * and compute the bounding volumes. Specifically, it will compute
 *
 * - this._boundingSphere
 * - model._boundingSphere
 *
 * With the latter being modified as of
 *
 * - model._initialRadius = model._boundingSphere.radius;
 * - model._boundingSphere.radius *= model._clampedScale;
 *
 * NOTE: This contains some bugs. See https://github.com/CesiumGS/cesium/issues/12108
 *
 * @param {ModelRenderResources} modelRenderResources The model render resources
 *
 * @private
 */
ModelSceneGraph.prototype.computeBoundingVolumes = function (
  modelRenderResources,
) {
  const model = this._model;
 
  const modelPositionMin = Cartesian3.fromElements(
    Number.MAX_VALUE,
    Number.MAX_VALUE,
    Number.MAX_VALUE,
    scratchModelPositionMin,
  );
  const modelPositionMax = Cartesian3.fromElements(
    -Number.MAX_VALUE,
    -Number.MAX_VALUE,
    -Number.MAX_VALUE,
    scratchModelPositionMax,
  );
 
  for (let i = 0; i < this._runtimeNodes.length; i++) {
    const runtimeNode = this._runtimeNodes[i];
 
    // If a node in the model was unreachable from the scene graph, there will
    // be no corresponding runtime node and therefore should be skipped.
    Iif (!defined(runtimeNode)) {
      continue;
    }
 
    const nodeRenderResources = modelRenderResources.nodeRenderResources[i];
    const nodeTransform = runtimeNode.computedTransform;
    for (let j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
      const runtimePrimitive = runtimeNode.runtimePrimitives[j];
 
      const primitiveRenderResources =
        nodeRenderResources.primitiveRenderResources[j];
 
      runtimePrimitive.boundingSphere = BoundingSphere.clone(
        primitiveRenderResources.boundingSphere,
        new BoundingSphere(),
      );
 
      const primitivePositionMin = Matrix4.multiplyByPoint(
        nodeTransform,
        primitiveRenderResources.positionMin,
        scratchPrimitivePositionMin,
      );
      const primitivePositionMax = Matrix4.multiplyByPoint(
        nodeTransform,
        primitiveRenderResources.positionMax,
        scratchPrimitivePositionMax,
      );
 
      Cartesian3.minimumByComponent(
        modelPositionMin,
        primitivePositionMin,
        modelPositionMin,
      );
      Cartesian3.maximumByComponent(
        modelPositionMax,
        primitivePositionMax,
        modelPositionMax,
      );
    }
  }
 
  this._boundingSphere = BoundingSphere.fromCornerPoints(
    modelPositionMin,
    modelPositionMax,
    new BoundingSphere(),
  );
 
  this._boundingSphere = BoundingSphere.transformWithoutScale(
    this._boundingSphere,
    this._axisCorrectionMatrix,
    this._boundingSphere,
  );
 
  this._boundingSphere = BoundingSphere.transform(
    this._boundingSphere,
    this._components.transform,
    this._boundingSphere,
  );
 
  model._boundingSphere = BoundingSphere.transform(
    this._boundingSphere,
    model.modelMatrix,
    model._boundingSphere,
  );
 
  model._initialRadius = model._boundingSphere.radius;
  model._boundingSphere.radius *= model._clampedScale;
};
 
/**
 * Creates the draw commands for the primitives in the scene graph.
 *
 * This will traverse the model, nodes and primitives of the scene graph,
 * and create the respective draw commands for the primitives, storing
 * them as the `runtimePrimitive.drawCommand`, respectively.
 *
 * @param {ModelRenderResources} modelRenderResources The model render resources
 *
 * @private
 */
ModelSceneGraph.prototype.createDrawCommands = function (
  modelRenderResources,
  frameState,
) {
  for (let i = 0; i < this._runtimeNodes.length; i++) {
    const runtimeNode = this._runtimeNodes[i];
 
    // If a node in the model was unreachable from the scene graph, there will
    // be no corresponding runtime node and therefore should be skipped.
    Iif (!defined(runtimeNode)) {
      continue;
    }
 
    const nodeRenderResources = modelRenderResources.nodeRenderResources[i];
 
    for (let j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
      const runtimePrimitive = runtimeNode.runtimePrimitives[j];
 
      const primitiveRenderResources =
        nodeRenderResources.primitiveRenderResources[j];
 
      const drawCommand = ModelDrawCommands.buildModelDrawCommand(
        primitiveRenderResources,
        frameState,
      );
      runtimePrimitive.drawCommand = drawCommand;
    }
  }
};
 
/**
 * Configure the model pipeline stages. If the pipeline needs to be re-run, call
 * this method again to ensure the correct sequence of pipeline stages are
 * used.
 *
 * @param {FrameState} frameState
 * @private
 */
ModelSceneGraph.prototype.configurePipeline = function (frameState) {
  const modelPipelineStages = this.modelPipelineStages;
  modelPipelineStages.length = 0;
 
  const model = this._model;
  const fogRenderable = frameState.fog.enabled && frameState.fog.renderable;
 
  if (defined(model.color)) {
    modelPipelineStages.push(ModelColorPipelineStage);
  }
 
  // Skip these pipeline stages for classification models.
  if (defined(model.classificationType)) {
    return;
  }
 
  if (model.imageBasedLighting.enabled) {
    modelPipelineStages.push(ImageBasedLightingPipelineStage);
  }
 
  if (model.isClippingEnabled()) {
    modelPipelineStages.push(ModelClippingPlanesPipelineStage);
  }
 
  Iif (model.isClippingPolygonsEnabled()) {
    modelPipelineStages.push(ModelClippingPolygonsPipelineStage);
  }
 
  if (model.hasSilhouette(frameState)) {
    modelPipelineStages.push(ModelSilhouettePipelineStage);
  }
 
  Iif (
    defined(model.splitDirection) &&
    model.splitDirection !== SplitDirection.NONE
  ) {
    modelPipelineStages.push(ModelSplitterPipelineStage);
  }
 
  if (ModelType.is3DTiles(model.type)) {
    modelPipelineStages.push(TilesetPipelineStage);
  }
 
  if (fogRenderable) {
    modelPipelineStages.push(AtmospherePipelineStage);
  }
};
 
ModelSceneGraph.prototype.update = function (frameState, updateForAnimations) {
  let i, j, k;
 
  for (i = 0; i < this._runtimeNodes.length; i++) {
    const runtimeNode = this._runtimeNodes[i];
 
    // If a node in the model was unreachable from the scene graph, there will
    // be no corresponding runtime node and therefore should be skipped.
    Iif (!defined(runtimeNode)) {
      continue;
    }
 
    for (j = 0; j < runtimeNode.updateStages.length; j++) {
      const nodeUpdateStage = runtimeNode.updateStages[j];
      nodeUpdateStage.update(runtimeNode, this, frameState);
    }
 
    const disableAnimations =
      frameState.mode !== SceneMode.SCENE3D && this._model._projectTo2D;
    if (updateForAnimations && !disableAnimations) {
      this.updateJointMatrices();
    }
 
    for (j = 0; j < runtimeNode.runtimePrimitives.length; j++) {
      const runtimePrimitive = runtimeNode.runtimePrimitives[j];
      for (k = 0; k < runtimePrimitive.updateStages.length; k++) {
        const stage = runtimePrimitive.updateStages[k];
        stage.update(runtimePrimitive, this);
      }
    }
  }
};
 
ModelSceneGraph.prototype.updateModelMatrix = function (
  modelMatrix,
  frameState,
) {
  computeModelMatrix(this, modelMatrix);
  if (frameState.mode !== SceneMode.SCENE3D) {
    computeModelMatrix2D(this, frameState);
  }
 
  // Mark all root nodes as dirty. Any and all children will be
  // affected recursively in the update stage.
  const rootNodes = this._rootNodes;
  for (let i = 0; i < rootNodes.length; i++) {
    const node = this._runtimeNodes[rootNodes[i]];
    node._transformDirty = true;
  }
};
 
/**
 * Updates the joint matrices for the skins and nodes of the model.
 *
 * @private
 */
ModelSceneGraph.prototype.updateJointMatrices = function () {
  const skinnedNodes = this._skinnedNodes;
  const length = skinnedNodes.length;
 
  for (let i = 0; i < length; i++) {
    const nodeIndex = skinnedNodes[i];
    const runtimeNode = this._runtimeNodes[nodeIndex];
    runtimeNode.updateJointMatrices();
  }
};
 
/**
 * A callback to be applied once at each runtime primitive in the
 * scene graph
 * @callback traverseSceneGraphCallback
 *
 * @param {ModelRuntimePrimitive} runtimePrimitive The runtime primitive for the current step of the traversal
 * @param {object} [options] A dictionary of additional options to be passed to the callback, or undefined if the callback does not need any additional information.
 *
 * @private
 */
 
/**
 * Recursively traverse through the runtime nodes in the scene graph
 * using a post-order depth-first traversal to perform a callback on
 * their runtime primitives.
 *
 * @param {ModelSceneGraph} sceneGraph The scene graph.
 * @param {ModelRuntimeNode} runtimeNode The current runtime node.
 * @param {boolean} visibleNodesOnly Whether to only traverse nodes that are visible.
 * @param {traverseSceneGraphCallback} callback The callback to perform on the runtime primitives of the node.
 * @param {object} [callbackOptions] A dictionary of additional options to be passed to the callback, if needed.
 *
 * @private
 */
function traverseSceneGraph(
  sceneGraph,
  runtimeNode,
  visibleNodesOnly,
  callback,
  callbackOptions,
) {
  if (visibleNodesOnly && !runtimeNode.show) {
    return;
  }
 
  const childrenLength = runtimeNode.children.length;
  for (let i = 0; i < childrenLength; i++) {
    const childRuntimeNode = runtimeNode.getChild(i);
    traverseSceneGraph(
      sceneGraph,
      childRuntimeNode,
      visibleNodesOnly,
      callback,
      callbackOptions,
    );
  }
 
  const runtimePrimitives = runtimeNode.runtimePrimitives;
  const runtimePrimitivesLength = runtimePrimitives.length;
  for (let j = 0; j < runtimePrimitivesLength; j++) {
    const runtimePrimitive = runtimePrimitives[j];
    callback(runtimePrimitive, callbackOptions);
  }
}
 
function forEachRuntimePrimitive(
  sceneGraph,
  visibleNodesOnly,
  callback,
  callbackOptions,
) {
  const rootNodes = sceneGraph._rootNodes;
  const rootNodesLength = rootNodes.length;
  for (let i = 0; i < rootNodesLength; i++) {
    const rootNodeIndex = rootNodes[i];
    const runtimeNode = sceneGraph._runtimeNodes[rootNodeIndex];
    traverseSceneGraph(
      sceneGraph,
      runtimeNode,
      visibleNodesOnly,
      callback,
      callbackOptions,
    );
  }
}
 
const scratchBackFaceCullingOptions = {
  backFaceCulling: undefined,
};
 
/**
 * Traverses through all draw commands and changes the back-face culling setting.
 *
 * @param {boolean} backFaceCulling The new value for the back-face culling setting.
 *
 * @private
 */
ModelSceneGraph.prototype.updateBackFaceCulling = function (backFaceCulling) {
  const backFaceCullingOptions = scratchBackFaceCullingOptions;
  backFaceCullingOptions.backFaceCulling = backFaceCulling;
  forEachRuntimePrimitive(
    this,
    false,
    updatePrimitiveBackFaceCulling,
    backFaceCullingOptions,
  );
};
 
// Callback is defined here to avoid allocating a closure in the render loop
function updatePrimitiveBackFaceCulling(runtimePrimitive, options) {
  const drawCommand = runtimePrimitive.drawCommand;
  drawCommand.backFaceCulling = options.backFaceCulling;
}
 
const scratchShadowOptions = {
  shadowMode: undefined,
};
 
/**
 * Traverses through all draw commands and changes the shadow settings.
 *
 * @param {ShadowMode} shadowMode The new shadow settings.
 *
 * @private
 */
ModelSceneGraph.prototype.updateShadows = function (shadowMode) {
  const shadowOptions = scratchShadowOptions;
  shadowOptions.shadowMode = shadowMode;
  forEachRuntimePrimitive(this, false, updatePrimitiveShadows, shadowOptions);
};
 
// Callback is defined here to avoid allocating a closure in the render loop
function updatePrimitiveShadows(runtimePrimitive, options) {
  const drawCommand = runtimePrimitive.drawCommand;
  drawCommand.shadows = options.shadowMode;
}
 
const scratchShowBoundingVolumeOptions = {
  debugShowBoundingVolume: undefined,
};
 
/**
 * Traverses through all draw commands and changes whether to show the debug bounding volume.
 *
 * @param {boolean} debugShowBoundingVolume The new value for showing the debug bounding volume.
 *
 * @private
 */
ModelSceneGraph.prototype.updateShowBoundingVolume = function (
  debugShowBoundingVolume,
) {
  const showBoundingVolumeOptions = scratchShowBoundingVolumeOptions;
  showBoundingVolumeOptions.debugShowBoundingVolume = debugShowBoundingVolume;
 
  forEachRuntimePrimitive(
    this,
    false,
    updatePrimitiveShowBoundingVolume,
    showBoundingVolumeOptions,
  );
};
 
// Callback is defined here to avoid allocating a closure in the render loop
function updatePrimitiveShowBoundingVolume(runtimePrimitive, options) {
  const drawCommand = runtimePrimitive.drawCommand;
  drawCommand.debugShowBoundingVolume = options.debugShowBoundingVolume;
}
 
const scratchSilhouetteCommands = [];
const scratchEdgeCommands = [];
const scratchPushDrawCommandOptions = {
  frameState: undefined,
  hasSilhouette: undefined,
};
 
/**
 * Traverses through the scene graph and pushes the draw commands associated
 * with each primitive to the frame state's command list.
 *
 * @param {FrameState} frameState The frame state.
 *
 * @private
 */
ModelSceneGraph.prototype.pushDrawCommands = function (frameState) {
  // If a model has silhouettes, the commands that draw the silhouettes for
  // each primitive can only be invoked after the entire model has drawn.
  // Otherwise, the silhouette may draw on top of the model. This requires
  // gathering the original commands and the silhouette commands separately.
  const silhouetteCommands = scratchSilhouetteCommands;
  silhouetteCommands.length = 0;
 
  // Gather edge commands for the edge pass
  const edgeCommands = scratchEdgeCommands;
  edgeCommands.length = 0;
 
  // Since this function is called each frame, the options object is
  // preallocated in a scratch variable
  const pushDrawCommandOptions = scratchPushDrawCommandOptions;
  pushDrawCommandOptions.hasSilhouette = this._model.hasSilhouette(frameState);
  pushDrawCommandOptions.frameState = frameState;
 
  forEachRuntimePrimitive(
    this,
    true,
    pushPrimitiveDrawCommands,
    pushDrawCommandOptions,
  );
 
  addAllToArray(frameState.commandList, silhouetteCommands);
  addAllToArray(frameState.commandList, edgeCommands);
};
 
// Callback is defined here to avoid allocating a closure in the render loop
function pushPrimitiveDrawCommands(runtimePrimitive, options) {
  const frameState = options.frameState;
  const hasSilhouette = options.hasSilhouette;
 
  const passes = frameState.passes;
  const silhouetteCommands = scratchSilhouetteCommands;
  const edgeCommands = scratchEdgeCommands;
  const primitiveDrawCommand = runtimePrimitive.drawCommand;
  primitiveDrawCommand.pushCommands(frameState, frameState.commandList);
 
  // If a model has silhouettes, the commands that draw the silhouettes for
  // each primitive can only be invoked after the entire model has drawn.
  // Otherwise, the silhouette may draw on top of the model. This requires
  // gathering the original commands and the silhouette commands separately.
  if (hasSilhouette && !passes.pick) {
    primitiveDrawCommand.pushSilhouetteCommands(frameState, silhouetteCommands);
  }
 
  // Add edge commands to the edge pass
  if (defined(primitiveDrawCommand.pushEdgeCommands)) {
    primitiveDrawCommand.pushEdgeCommands(frameState, edgeCommands);
  }
}
 
/**
 * Sets the current value of an articulation stage.
 *
 * @param {string} articulationStageKey The name of the articulation, a space, and the name of the stage.
 * @param {number} value The numeric value of this stage of the articulation.
 *
 * @private
 */
ModelSceneGraph.prototype.setArticulationStage = function (
  articulationStageKey,
  value,
) {
  const names = articulationStageKey.split(" ");
  Iif (names.length !== 2) {
    return;
  }
 
  const articulationName = names[0];
  const stageName = names[1];
 
  const runtimeArticulation = this._runtimeArticulations[articulationName];
  Eif (defined(runtimeArticulation)) {
    runtimeArticulation.setArticulationStage(stageName, value);
  }
};
 
/**
 * Applies any modified articulation stages to the matrix of each node that participates
 * in any articulation.  Note that this will overwrite any nodeTransformations on participating nodes.
 *
 * @private
 */
ModelSceneGraph.prototype.applyArticulations = function () {
  const runtimeArticulations = this._runtimeArticulations;
  for (const articulationName in runtimeArticulations) {
    Eif (runtimeArticulations.hasOwnProperty(articulationName)) {
      const articulation = runtimeArticulations[articulationName];
      articulation.apply();
    }
  }
};
 
export default ModelSceneGraph;