Primitive.js 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547
  1. import BoundingSphere from "../Core/BoundingSphere.js";
  2. import Cartesian2 from "../Core/Cartesian2.js";
  3. import Cartesian3 from "../Core/Cartesian3.js";
  4. import Cartesian4 from "../Core/Cartesian4.js";
  5. import Cartographic from "../Core/Cartographic.js";
  6. import clone from "../Core/clone.js";
  7. import Color from "../Core/Color.js";
  8. import combine from "../Core/combine.js";
  9. import ComponentDatatype from "../Core/ComponentDatatype.js";
  10. import defaultValue from "../Core/defaultValue.js";
  11. import defined from "../Core/defined.js";
  12. import deprecationWarning from "../Core/deprecationWarning.js";
  13. import destroyObject from "../Core/destroyObject.js";
  14. import DeveloperError from "../Core/DeveloperError.js";
  15. import EncodedCartesian3 from "../Core/EncodedCartesian3.js";
  16. import FeatureDetection from "../Core/FeatureDetection.js";
  17. import Geometry from "../Core/Geometry.js";
  18. import GeometryAttribute from "../Core/GeometryAttribute.js";
  19. import GeometryAttributes from "../Core/GeometryAttributes.js";
  20. import GeometryOffsetAttribute from "../Core/GeometryOffsetAttribute.js";
  21. import Intersect from "../Core/Intersect.js";
  22. import Matrix4 from "../Core/Matrix4.js";
  23. import Plane from "../Core/Plane.js";
  24. import RuntimeError from "../Core/RuntimeError.js";
  25. import subdivideArray from "../Core/subdivideArray.js";
  26. import TaskProcessor from "../Core/TaskProcessor.js";
  27. import BufferUsage from "../Renderer/BufferUsage.js";
  28. import ContextLimits from "../Renderer/ContextLimits.js";
  29. import DrawCommand from "../Renderer/DrawCommand.js";
  30. import Pass from "../Renderer/Pass.js";
  31. import RenderState from "../Renderer/RenderState.js";
  32. import ShaderProgram from "../Renderer/ShaderProgram.js";
  33. import ShaderSource from "../Renderer/ShaderSource.js";
  34. import VertexArray from "../Renderer/VertexArray.js";
  35. import BatchTable from "./BatchTable.js";
  36. import CullFace from "./CullFace.js";
  37. import DepthFunction from "./DepthFunction.js";
  38. import PrimitivePipeline from "./PrimitivePipeline.js";
  39. import PrimitiveState from "./PrimitiveState.js";
  40. import SceneMode from "./SceneMode.js";
  41. import ShadowMode from "./ShadowMode.js";
  42. /**
  43. * A primitive represents geometry in the {@link Scene}. The geometry can be from a single {@link GeometryInstance}
  44. * as shown in example 1 below, or from an array of instances, even if the geometry is from different
  45. * geometry types, e.g., an {@link RectangleGeometry} and an {@link EllipsoidGeometry} as shown in Code Example 2.
  46. * <p>
  47. * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
  48. * {@link Material} and {@link RenderState}. Roughly, the geometry instance defines the structure and placement,
  49. * and the appearance defines the visual characteristics. Decoupling geometry and appearance allows us to mix
  50. * and match most of them and add a new geometry or appearance independently of each other.
  51. * </p>
  52. * <p>
  53. * Combining multiple instances into one primitive is called batching, and significantly improves performance for static data.
  54. * Instances can be individually picked; {@link Scene#pick} returns their {@link GeometryInstance#id}. Using
  55. * per-instance appearances like {@link PerInstanceColorAppearance}, each instance can also have a unique color.
  56. * </p>
  57. * <p>
  58. * {@link Geometry} can either be created and batched on a web worker or the main thread. The first two examples
  59. * show geometry that will be created on a web worker by using the descriptions of the geometry. The third example
  60. * shows how to create the geometry on the main thread by explicitly calling the <code>createGeometry</code> method.
  61. * </p>
  62. *
  63. * @alias Primitive
  64. * @constructor
  65. *
  66. * @param {object} [options] Object with the following properties:
  67. * @param {GeometryInstance[]|GeometryInstance} [options.geometryInstances] The geometry instances - or a single geometry instance - to render.
  68. * @param {Appearance} [options.appearance] The appearance used to render the primitive.
  69. * @param {Appearance} [options.depthFailAppearance] The appearance used to shade this primitive when it fails the depth test.
  70. * @param {boolean} [options.show=true] Determines if this primitive will be shown.
  71. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the primitive (all geometry instances) from model to world coordinates.
  72. * @param {boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
  73. * @param {boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
  74. * @param {boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
  75. * @param {boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
  76. * @param {boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved.
  77. * @param {boolean} [options.cull=true] When <code>true</code>, the renderer frustum culls and horizon culls the primitive's commands based on their bounding volume. Set this to <code>false</code> for a small performance gain if you are manually culling the primitive.
  78. * @param {boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready.
  79. * @param {boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
  80. * @param {ShadowMode} [options.shadows=ShadowMode.DISABLED] Determines whether this primitive casts or receives shadows from light sources.
  81. *
  82. * @example
  83. * // 1. Draw a translucent ellipse on the surface with a checkerboard pattern
  84. * const instance = new Cesium.GeometryInstance({
  85. * geometry : new Cesium.EllipseGeometry({
  86. * center : Cesium.Cartesian3.fromDegrees(-100.0, 20.0),
  87. * semiMinorAxis : 500000.0,
  88. * semiMajorAxis : 1000000.0,
  89. * rotation : Cesium.Math.PI_OVER_FOUR,
  90. * vertexFormat : Cesium.VertexFormat.POSITION_AND_ST
  91. * }),
  92. * id : 'object returned when this instance is picked and to get/set per-instance attributes'
  93. * });
  94. * scene.primitives.add(new Cesium.Primitive({
  95. * geometryInstances : instance,
  96. * appearance : new Cesium.EllipsoidSurfaceAppearance({
  97. * material : Cesium.Material.fromType('Checkerboard')
  98. * })
  99. * }));
  100. *
  101. * @example
  102. * // 2. Draw different instances each with a unique color
  103. * const rectangleInstance = new Cesium.GeometryInstance({
  104. * geometry : new Cesium.RectangleGeometry({
  105. * rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0),
  106. * vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
  107. * }),
  108. * id : 'rectangle',
  109. * attributes : {
  110. * color : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
  111. * }
  112. * });
  113. * const ellipsoidInstance = new Cesium.GeometryInstance({
  114. * geometry : new Cesium.EllipsoidGeometry({
  115. * radii : new Cesium.Cartesian3(500000.0, 500000.0, 1000000.0),
  116. * vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL
  117. * }),
  118. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  119. * Cesium.Cartesian3.fromDegrees(-95.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 500000.0), new Cesium.Matrix4()),
  120. * id : 'ellipsoid',
  121. * attributes : {
  122. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  123. * }
  124. * });
  125. * scene.primitives.add(new Cesium.Primitive({
  126. * geometryInstances : [rectangleInstance, ellipsoidInstance],
  127. * appearance : new Cesium.PerInstanceColorAppearance()
  128. * }));
  129. *
  130. * @example
  131. * // 3. Create the geometry on the main thread.
  132. * scene.primitives.add(new Cesium.Primitive({
  133. * geometryInstances : new Cesium.GeometryInstance({
  134. * geometry : Cesium.EllipsoidGeometry.createGeometry(new Cesium.EllipsoidGeometry({
  135. * radii : new Cesium.Cartesian3(500000.0, 500000.0, 1000000.0),
  136. * vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL
  137. * })),
  138. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  139. * Cesium.Cartesian3.fromDegrees(-95.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 500000.0), new Cesium.Matrix4()),
  140. * id : 'ellipsoid',
  141. * attributes : {
  142. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  143. * }
  144. * }),
  145. * appearance : new Cesium.PerInstanceColorAppearance(),
  146. * asynchronous : false
  147. * }));
  148. *
  149. * @see GeometryInstance
  150. * @see Appearance
  151. * @see ClassificationPrimitive
  152. * @see GroundPrimitive
  153. */
  154. function Primitive(options) {
  155. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  156. /**
  157. * The geometry instances rendered with this primitive. This may
  158. * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
  159. * is <code>true</code> when the primitive is constructed.
  160. * <p>
  161. * Changing this property after the primitive is rendered has no effect.
  162. * </p>
  163. *
  164. * @readonly
  165. * @type GeometryInstance[]|GeometryInstance
  166. *
  167. * @default undefined
  168. */
  169. this.geometryInstances = options.geometryInstances;
  170. /**
  171. * The {@link Appearance} used to shade this primitive. Each geometry
  172. * instance is shaded with the same appearance. Some appearances, like
  173. * {@link PerInstanceColorAppearance} allow giving each instance unique
  174. * properties.
  175. *
  176. * @type Appearance
  177. *
  178. * @default undefined
  179. */
  180. this.appearance = options.appearance;
  181. this._appearance = undefined;
  182. this._material = undefined;
  183. /**
  184. * The {@link Appearance} used to shade this primitive when it fails the depth test. Each geometry
  185. * instance is shaded with the same appearance. Some appearances, like
  186. * {@link PerInstanceColorAppearance} allow giving each instance unique
  187. * properties.
  188. *
  189. * <p>
  190. * When using an appearance that requires a color attribute, like PerInstanceColorAppearance,
  191. * add a depthFailColor per-instance attribute instead.
  192. * </p>
  193. *
  194. * <p>
  195. * Requires the EXT_frag_depth WebGL extension to render properly. If the extension is not supported,
  196. * there may be artifacts.
  197. * </p>
  198. * @type Appearance
  199. *
  200. * @default undefined
  201. */
  202. this.depthFailAppearance = options.depthFailAppearance;
  203. this._depthFailAppearance = undefined;
  204. this._depthFailMaterial = undefined;
  205. /**
  206. * The 4x4 transformation matrix that transforms the primitive (all geometry instances) from model to world coordinates.
  207. * When this is the identity matrix, the primitive is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
  208. * Local reference frames can be used by providing a different transformation matrix, like that returned
  209. * by {@link Transforms.eastNorthUpToFixedFrame}.
  210. *
  211. * <p>
  212. * This property is only supported in 3D mode.
  213. * </p>
  214. *
  215. * @type Matrix4
  216. *
  217. * @default Matrix4.IDENTITY
  218. *
  219. * @example
  220. * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
  221. * p.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
  222. */
  223. this.modelMatrix = Matrix4.clone(
  224. defaultValue(options.modelMatrix, Matrix4.IDENTITY)
  225. );
  226. this._modelMatrix = new Matrix4();
  227. /**
  228. * Determines if the primitive will be shown. This affects all geometry
  229. * instances in the primitive.
  230. *
  231. * @type {boolean}
  232. *
  233. * @default true
  234. */
  235. this.show = defaultValue(options.show, true);
  236. this._vertexCacheOptimize = defaultValue(options.vertexCacheOptimize, false);
  237. this._interleave = defaultValue(options.interleave, false);
  238. this._releaseGeometryInstances = defaultValue(
  239. options.releaseGeometryInstances,
  240. true
  241. );
  242. this._allowPicking = defaultValue(options.allowPicking, true);
  243. this._asynchronous = defaultValue(options.asynchronous, true);
  244. this._compressVertices = defaultValue(options.compressVertices, true);
  245. /**
  246. * When <code>true</code>, the renderer frustum culls and horizon culls the primitive's commands
  247. * based on their bounding volume. Set this to <code>false</code> for a small performance gain
  248. * if you are manually culling the primitive.
  249. *
  250. * @type {boolean}
  251. *
  252. * @default true
  253. */
  254. this.cull = defaultValue(options.cull, true);
  255. /**
  256. * This property is for debugging only; it is not for production use nor is it optimized.
  257. * <p>
  258. * Draws the bounding sphere for each draw command in the primitive.
  259. * </p>
  260. *
  261. * @type {boolean}
  262. *
  263. * @default false
  264. */
  265. this.debugShowBoundingVolume = defaultValue(
  266. options.debugShowBoundingVolume,
  267. false
  268. );
  269. /**
  270. * @private
  271. */
  272. this.rtcCenter = options.rtcCenter;
  273. //>>includeStart('debug', pragmas.debug);
  274. if (
  275. defined(this.rtcCenter) &&
  276. (!defined(this.geometryInstances) ||
  277. (Array.isArray(this.geometryInstances) &&
  278. this.geometryInstances.length !== 1))
  279. ) {
  280. throw new DeveloperError(
  281. "Relative-to-center rendering only supports one geometry instance."
  282. );
  283. }
  284. //>>includeEnd('debug');
  285. /**
  286. * Determines whether this primitive casts or receives shadows from light sources.
  287. *
  288. * @type {ShadowMode}
  289. *
  290. * @default ShadowMode.DISABLED
  291. */
  292. this.shadows = defaultValue(options.shadows, ShadowMode.DISABLED);
  293. this._translucent = undefined;
  294. this._state = PrimitiveState.READY;
  295. this._geometries = [];
  296. this._error = undefined;
  297. this._numberOfInstances = 0;
  298. this._boundingSpheres = [];
  299. this._boundingSphereWC = [];
  300. this._boundingSphereCV = [];
  301. this._boundingSphere2D = [];
  302. this._boundingSphereMorph = [];
  303. this._perInstanceAttributeCache = new Map();
  304. this._instanceIds = [];
  305. this._lastPerInstanceAttributeIndex = 0;
  306. this._va = [];
  307. this._attributeLocations = undefined;
  308. this._primitiveType = undefined;
  309. this._frontFaceRS = undefined;
  310. this._backFaceRS = undefined;
  311. this._sp = undefined;
  312. this._depthFailAppearance = undefined;
  313. this._spDepthFail = undefined;
  314. this._frontFaceDepthFailRS = undefined;
  315. this._backFaceDepthFailRS = undefined;
  316. this._pickIds = [];
  317. this._colorCommands = [];
  318. this._pickCommands = [];
  319. this._createBoundingVolumeFunction = options._createBoundingVolumeFunction;
  320. this._createRenderStatesFunction = options._createRenderStatesFunction;
  321. this._createShaderProgramFunction = options._createShaderProgramFunction;
  322. this._createCommandsFunction = options._createCommandsFunction;
  323. this._updateAndQueueCommandsFunction =
  324. options._updateAndQueueCommandsFunction;
  325. this._createPickOffsets = options._createPickOffsets;
  326. this._pickOffsets = undefined;
  327. this._createGeometryResults = undefined;
  328. this._ready = false;
  329. const primitive = this;
  330. // This is here for backwards compatibility. This promise wrapper can be removed once readyPromise is removed.
  331. this._readyPromise = new Promise((resolve, reject) => {
  332. primitive._completeLoad = (frameState, state, error) => {
  333. this._error = error;
  334. this._state = state;
  335. frameState.afterRender.push(function () {
  336. primitive._ready =
  337. primitive._state === PrimitiveState.COMPLETE ||
  338. primitive._state === PrimitiveState.FAILED;
  339. if (!defined(error)) {
  340. resolve(primitive);
  341. return true;
  342. }
  343. reject(error);
  344. });
  345. };
  346. });
  347. this._batchTable = undefined;
  348. this._batchTableAttributeIndices = undefined;
  349. this._offsetInstanceExtend = undefined;
  350. this._batchTableOffsetAttribute2DIndex = undefined;
  351. this._batchTableOffsetsUpdated = false;
  352. this._instanceBoundingSpheres = undefined;
  353. this._instanceBoundingSpheresCV = undefined;
  354. this._tempBoundingSpheres = undefined;
  355. this._recomputeBoundingSpheres = false;
  356. this._batchTableBoundingSpheresUpdated = false;
  357. this._batchTableBoundingSphereAttributeIndices = undefined;
  358. }
  359. Object.defineProperties(Primitive.prototype, {
  360. /**
  361. * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
  362. *
  363. * @memberof Primitive.prototype
  364. *
  365. * @type {boolean}
  366. * @readonly
  367. *
  368. * @default true
  369. */
  370. vertexCacheOptimize: {
  371. get: function () {
  372. return this._vertexCacheOptimize;
  373. },
  374. },
  375. /**
  376. * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
  377. *
  378. * @memberof Primitive.prototype
  379. *
  380. * @type {boolean}
  381. * @readonly
  382. *
  383. * @default false
  384. */
  385. interleave: {
  386. get: function () {
  387. return this._interleave;
  388. },
  389. },
  390. /**
  391. * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
  392. *
  393. * @memberof Primitive.prototype
  394. *
  395. * @type {boolean}
  396. * @readonly
  397. *
  398. * @default true
  399. */
  400. releaseGeometryInstances: {
  401. get: function () {
  402. return this._releaseGeometryInstances;
  403. },
  404. },
  405. /**
  406. * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved. *
  407. *
  408. * @memberof Primitive.prototype
  409. *
  410. * @type {boolean}
  411. * @readonly
  412. *
  413. * @default true
  414. */
  415. allowPicking: {
  416. get: function () {
  417. return this._allowPicking;
  418. },
  419. },
  420. /**
  421. * Determines if the geometry instances will be created and batched on a web worker.
  422. *
  423. * @memberof Primitive.prototype
  424. *
  425. * @type {boolean}
  426. * @readonly
  427. *
  428. * @default true
  429. */
  430. asynchronous: {
  431. get: function () {
  432. return this._asynchronous;
  433. },
  434. },
  435. /**
  436. * When <code>true</code>, geometry vertices are compressed, which will save memory.
  437. *
  438. * @memberof Primitive.prototype
  439. *
  440. * @type {boolean}
  441. * @readonly
  442. *
  443. * @default true
  444. */
  445. compressVertices: {
  446. get: function () {
  447. return this._compressVertices;
  448. },
  449. },
  450. /**
  451. * Determines if the primitive is complete and ready to render. If this property is
  452. * true, the primitive will be rendered the next time that {@link Primitive#update}
  453. * is called.
  454. *
  455. * @memberof Primitive.prototype
  456. *
  457. * @type {boolean}
  458. * @readonly
  459. *
  460. * @example
  461. * // Wait for a primitive to become ready before accessing attributes
  462. * const removeListener = scene.postRender.addEventListener(() => {
  463. * if (!frustumPrimitive.ready) {
  464. * return;
  465. * }
  466. *
  467. * const attributes = primitive.getGeometryInstanceAttributes('an id');
  468. * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
  469. *
  470. * removeListener();
  471. * });
  472. */
  473. ready: {
  474. get: function () {
  475. return this._ready;
  476. },
  477. },
  478. /**
  479. * Gets a promise that resolves when the primitive is ready to render.
  480. * @memberof Primitive.prototype
  481. * @type {Promise<Primitive>}
  482. * @readonly
  483. * @deprecated
  484. */
  485. readyPromise: {
  486. get: function () {
  487. deprecationWarning(
  488. "Primitive.readyPromise",
  489. "Primitive.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Primitive.ready to return true instead."
  490. );
  491. return this._readyPromise;
  492. },
  493. },
  494. });
  495. function getCommonPerInstanceAttributeNames(instances) {
  496. const length = instances.length;
  497. const attributesInAllInstances = [];
  498. const attributes0 = instances[0].attributes;
  499. let name;
  500. for (name in attributes0) {
  501. if (attributes0.hasOwnProperty(name) && defined(attributes0[name])) {
  502. const attribute = attributes0[name];
  503. let inAllInstances = true;
  504. // Does this same attribute exist in all instances?
  505. for (let i = 1; i < length; ++i) {
  506. const otherAttribute = instances[i].attributes[name];
  507. if (
  508. !defined(otherAttribute) ||
  509. attribute.componentDatatype !== otherAttribute.componentDatatype ||
  510. attribute.componentsPerAttribute !==
  511. otherAttribute.componentsPerAttribute ||
  512. attribute.normalize !== otherAttribute.normalize
  513. ) {
  514. inAllInstances = false;
  515. break;
  516. }
  517. }
  518. if (inAllInstances) {
  519. attributesInAllInstances.push(name);
  520. }
  521. }
  522. }
  523. return attributesInAllInstances;
  524. }
  525. const scratchGetAttributeCartesian2 = new Cartesian2();
  526. const scratchGetAttributeCartesian3 = new Cartesian3();
  527. const scratchGetAttributeCartesian4 = new Cartesian4();
  528. function getAttributeValue(value) {
  529. const componentsPerAttribute = value.length;
  530. if (componentsPerAttribute === 1) {
  531. return value[0];
  532. } else if (componentsPerAttribute === 2) {
  533. return Cartesian2.unpack(value, 0, scratchGetAttributeCartesian2);
  534. } else if (componentsPerAttribute === 3) {
  535. return Cartesian3.unpack(value, 0, scratchGetAttributeCartesian3);
  536. } else if (componentsPerAttribute === 4) {
  537. return Cartesian4.unpack(value, 0, scratchGetAttributeCartesian4);
  538. }
  539. }
  540. function createBatchTable(primitive, context) {
  541. const geometryInstances = primitive.geometryInstances;
  542. const instances = Array.isArray(geometryInstances)
  543. ? geometryInstances
  544. : [geometryInstances];
  545. const numberOfInstances = instances.length;
  546. if (numberOfInstances === 0) {
  547. return;
  548. }
  549. const names = getCommonPerInstanceAttributeNames(instances);
  550. const length = names.length;
  551. const attributes = [];
  552. const attributeIndices = {};
  553. const boundingSphereAttributeIndices = {};
  554. let offset2DIndex;
  555. const firstInstance = instances[0];
  556. let instanceAttributes = firstInstance.attributes;
  557. let i;
  558. let name;
  559. let attribute;
  560. for (i = 0; i < length; ++i) {
  561. name = names[i];
  562. attribute = instanceAttributes[name];
  563. attributeIndices[name] = i;
  564. attributes.push({
  565. functionName: `czm_batchTable_${name}`,
  566. componentDatatype: attribute.componentDatatype,
  567. componentsPerAttribute: attribute.componentsPerAttribute,
  568. normalize: attribute.normalize,
  569. });
  570. }
  571. if (names.indexOf("distanceDisplayCondition") !== -1) {
  572. attributes.push(
  573. {
  574. functionName: "czm_batchTable_boundingSphereCenter3DHigh",
  575. componentDatatype: ComponentDatatype.FLOAT,
  576. componentsPerAttribute: 3,
  577. },
  578. {
  579. functionName: "czm_batchTable_boundingSphereCenter3DLow",
  580. componentDatatype: ComponentDatatype.FLOAT,
  581. componentsPerAttribute: 3,
  582. },
  583. {
  584. functionName: "czm_batchTable_boundingSphereCenter2DHigh",
  585. componentDatatype: ComponentDatatype.FLOAT,
  586. componentsPerAttribute: 3,
  587. },
  588. {
  589. functionName: "czm_batchTable_boundingSphereCenter2DLow",
  590. componentDatatype: ComponentDatatype.FLOAT,
  591. componentsPerAttribute: 3,
  592. },
  593. {
  594. functionName: "czm_batchTable_boundingSphereRadius",
  595. componentDatatype: ComponentDatatype.FLOAT,
  596. componentsPerAttribute: 1,
  597. }
  598. );
  599. boundingSphereAttributeIndices.center3DHigh = attributes.length - 5;
  600. boundingSphereAttributeIndices.center3DLow = attributes.length - 4;
  601. boundingSphereAttributeIndices.center2DHigh = attributes.length - 3;
  602. boundingSphereAttributeIndices.center2DLow = attributes.length - 2;
  603. boundingSphereAttributeIndices.radius = attributes.length - 1;
  604. }
  605. if (names.indexOf("offset") !== -1) {
  606. attributes.push({
  607. functionName: "czm_batchTable_offset2D",
  608. componentDatatype: ComponentDatatype.FLOAT,
  609. componentsPerAttribute: 3,
  610. });
  611. offset2DIndex = attributes.length - 1;
  612. }
  613. attributes.push({
  614. functionName: "czm_batchTable_pickColor",
  615. componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
  616. componentsPerAttribute: 4,
  617. normalize: true,
  618. });
  619. const attributesLength = attributes.length;
  620. const batchTable = new BatchTable(context, attributes, numberOfInstances);
  621. for (i = 0; i < numberOfInstances; ++i) {
  622. const instance = instances[i];
  623. instanceAttributes = instance.attributes;
  624. for (let j = 0; j < length; ++j) {
  625. name = names[j];
  626. attribute = instanceAttributes[name];
  627. const value = getAttributeValue(attribute.value);
  628. const attributeIndex = attributeIndices[name];
  629. batchTable.setBatchedAttribute(i, attributeIndex, value);
  630. }
  631. const pickObject = {
  632. primitive: defaultValue(instance.pickPrimitive, primitive),
  633. };
  634. if (defined(instance.id)) {
  635. pickObject.id = instance.id;
  636. }
  637. const pickId = context.createPickId(pickObject);
  638. primitive._pickIds.push(pickId);
  639. const pickColor = pickId.color;
  640. const color = scratchGetAttributeCartesian4;
  641. color.x = Color.floatToByte(pickColor.red);
  642. color.y = Color.floatToByte(pickColor.green);
  643. color.z = Color.floatToByte(pickColor.blue);
  644. color.w = Color.floatToByte(pickColor.alpha);
  645. batchTable.setBatchedAttribute(i, attributesLength - 1, color);
  646. }
  647. primitive._batchTable = batchTable;
  648. primitive._batchTableAttributeIndices = attributeIndices;
  649. primitive._batchTableBoundingSphereAttributeIndices = boundingSphereAttributeIndices;
  650. primitive._batchTableOffsetAttribute2DIndex = offset2DIndex;
  651. }
  652. function cloneAttribute(attribute) {
  653. let clonedValues;
  654. if (Array.isArray(attribute.values)) {
  655. clonedValues = attribute.values.slice(0);
  656. } else {
  657. clonedValues = new attribute.values.constructor(attribute.values);
  658. }
  659. return new GeometryAttribute({
  660. componentDatatype: attribute.componentDatatype,
  661. componentsPerAttribute: attribute.componentsPerAttribute,
  662. normalize: attribute.normalize,
  663. values: clonedValues,
  664. });
  665. }
  666. function cloneGeometry(geometry) {
  667. const attributes = geometry.attributes;
  668. const newAttributes = new GeometryAttributes();
  669. for (const property in attributes) {
  670. if (attributes.hasOwnProperty(property) && defined(attributes[property])) {
  671. newAttributes[property] = cloneAttribute(attributes[property]);
  672. }
  673. }
  674. let indices;
  675. if (defined(geometry.indices)) {
  676. const sourceValues = geometry.indices;
  677. if (Array.isArray(sourceValues)) {
  678. indices = sourceValues.slice(0);
  679. } else {
  680. indices = new sourceValues.constructor(sourceValues);
  681. }
  682. }
  683. return new Geometry({
  684. attributes: newAttributes,
  685. indices: indices,
  686. primitiveType: geometry.primitiveType,
  687. boundingSphere: BoundingSphere.clone(geometry.boundingSphere),
  688. });
  689. }
  690. function cloneInstance(instance, geometry) {
  691. return {
  692. geometry: geometry,
  693. attributes: instance.attributes,
  694. modelMatrix: Matrix4.clone(instance.modelMatrix),
  695. pickPrimitive: instance.pickPrimitive,
  696. id: instance.id,
  697. };
  698. }
  699. const positionRegex = /in\s+vec(?:3|4)\s+(.*)3DHigh;/g;
  700. Primitive._modifyShaderPosition = function (
  701. primitive,
  702. vertexShaderSource,
  703. scene3DOnly
  704. ) {
  705. let match;
  706. let forwardDecl = "";
  707. let attributes = "";
  708. let computeFunctions = "";
  709. while ((match = positionRegex.exec(vertexShaderSource)) !== null) {
  710. const name = match[1];
  711. const functionName = `vec4 czm_compute${name[0].toUpperCase()}${name.substr(
  712. 1
  713. )}()`;
  714. // Don't forward-declare czm_computePosition because computePosition.glsl already does.
  715. if (functionName !== "vec4 czm_computePosition()") {
  716. forwardDecl += `${functionName};\n`;
  717. }
  718. if (!defined(primitive.rtcCenter)) {
  719. // Use GPU RTE
  720. if (!scene3DOnly) {
  721. attributes += `in vec3 ${name}2DHigh;\nin vec3 ${name}2DLow;\n`;
  722. computeFunctions +=
  723. `${functionName}\n` +
  724. `{\n` +
  725. ` vec4 p;\n` +
  726. ` if (czm_morphTime == 1.0)\n` +
  727. ` {\n` +
  728. ` p = czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);\n` +
  729. ` }\n` +
  730. ` else if (czm_morphTime == 0.0)\n` +
  731. ` {\n` +
  732. ` p = czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy);\n` +
  733. ` }\n` +
  734. ` else\n` +
  735. ` {\n` +
  736. ` p = czm_columbusViewMorph(\n` +
  737. ` czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy),\n` +
  738. ` czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow),\n` +
  739. ` czm_morphTime);\n` +
  740. ` }\n` +
  741. ` return p;\n` +
  742. `}\n\n`;
  743. } else {
  744. computeFunctions +=
  745. `${functionName}\n` +
  746. `{\n` +
  747. ` return czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);\n` +
  748. `}\n\n`;
  749. }
  750. } else {
  751. // Use RTC
  752. vertexShaderSource = vertexShaderSource.replace(
  753. /in\s+vec(?:3|4)\s+position3DHigh;/g,
  754. ""
  755. );
  756. vertexShaderSource = vertexShaderSource.replace(
  757. /in\s+vec(?:3|4)\s+position3DLow;/g,
  758. ""
  759. );
  760. forwardDecl += "uniform mat4 u_modifiedModelView;\n";
  761. attributes += "in vec4 position;\n";
  762. computeFunctions +=
  763. `${functionName}\n` +
  764. `{\n` +
  765. ` return u_modifiedModelView * position;\n` +
  766. `}\n\n`;
  767. vertexShaderSource = vertexShaderSource.replace(
  768. /czm_modelViewRelativeToEye\s+\*\s+/g,
  769. ""
  770. );
  771. vertexShaderSource = vertexShaderSource.replace(
  772. /czm_modelViewProjectionRelativeToEye/g,
  773. "czm_projection"
  774. );
  775. }
  776. }
  777. return [forwardDecl, attributes, vertexShaderSource, computeFunctions].join(
  778. "\n"
  779. );
  780. };
  781. Primitive._appendShowToShader = function (primitive, vertexShaderSource) {
  782. if (!defined(primitive._batchTableAttributeIndices.show)) {
  783. return vertexShaderSource;
  784. }
  785. const renamedVS = ShaderSource.replaceMain(
  786. vertexShaderSource,
  787. "czm_non_show_main"
  788. );
  789. const showMain =
  790. "void main() \n" +
  791. "{ \n" +
  792. " czm_non_show_main(); \n" +
  793. " gl_Position *= czm_batchTable_show(batchId); \n" +
  794. "}";
  795. return `${renamedVS}\n${showMain}`;
  796. };
  797. Primitive._updateColorAttribute = function (
  798. primitive,
  799. vertexShaderSource,
  800. isDepthFail
  801. ) {
  802. // some appearances have a color attribute for per vertex color.
  803. // only remove if color is a per instance attribute.
  804. if (
  805. !defined(primitive._batchTableAttributeIndices.color) &&
  806. !defined(primitive._batchTableAttributeIndices.depthFailColor)
  807. ) {
  808. return vertexShaderSource;
  809. }
  810. if (vertexShaderSource.search(/in\s+vec4\s+color;/g) === -1) {
  811. return vertexShaderSource;
  812. }
  813. //>>includeStart('debug', pragmas.debug);
  814. if (
  815. isDepthFail &&
  816. !defined(primitive._batchTableAttributeIndices.depthFailColor)
  817. ) {
  818. throw new DeveloperError(
  819. "A depthFailColor per-instance attribute is required when using a depth fail appearance that uses a color attribute."
  820. );
  821. }
  822. //>>includeEnd('debug');
  823. let modifiedVS = vertexShaderSource;
  824. modifiedVS = modifiedVS.replace(/in\s+vec4\s+color;/g, "");
  825. if (!isDepthFail) {
  826. modifiedVS = modifiedVS.replace(
  827. /(\b)color(\b)/g,
  828. "$1czm_batchTable_color(batchId)$2"
  829. );
  830. } else {
  831. modifiedVS = modifiedVS.replace(
  832. /(\b)color(\b)/g,
  833. "$1czm_batchTable_depthFailColor(batchId)$2"
  834. );
  835. }
  836. return modifiedVS;
  837. };
  838. function appendPickToVertexShader(source) {
  839. const renamedVS = ShaderSource.replaceMain(source, "czm_non_pick_main");
  840. const pickMain =
  841. "out vec4 v_pickColor; \n" +
  842. "void main() \n" +
  843. "{ \n" +
  844. " czm_non_pick_main(); \n" +
  845. " v_pickColor = czm_batchTable_pickColor(batchId); \n" +
  846. "}";
  847. return `${renamedVS}\n${pickMain}`;
  848. }
  849. function appendPickToFragmentShader(source) {
  850. return `in vec4 v_pickColor;\n${source}`;
  851. }
  852. Primitive._updatePickColorAttribute = function (source) {
  853. let vsPick = source.replace(/in\s+vec4\s+pickColor;/g, "");
  854. vsPick = vsPick.replace(
  855. /(\b)pickColor(\b)/g,
  856. "$1czm_batchTable_pickColor(batchId)$2"
  857. );
  858. return vsPick;
  859. };
  860. Primitive._appendOffsetToShader = function (primitive, vertexShaderSource) {
  861. if (!defined(primitive._batchTableAttributeIndices.offset)) {
  862. return vertexShaderSource;
  863. }
  864. let attr = "in float batchId;\n";
  865. attr += "in float applyOffset;";
  866. let modifiedShader = vertexShaderSource.replace(
  867. /in\s+float\s+batchId;/g,
  868. attr
  869. );
  870. let str = "vec4 $1 = czm_computePosition();\n";
  871. str += " if (czm_sceneMode == czm_sceneMode3D)\n";
  872. str += " {\n";
  873. str +=
  874. " $1 = $1 + vec4(czm_batchTable_offset(batchId) * applyOffset, 0.0);";
  875. str += " }\n";
  876. str += " else\n";
  877. str += " {\n";
  878. str +=
  879. " $1 = $1 + vec4(czm_batchTable_offset2D(batchId) * applyOffset, 0.0);";
  880. str += " }\n";
  881. modifiedShader = modifiedShader.replace(
  882. /vec4\s+([A-Za-z0-9_]+)\s+=\s+czm_computePosition\(\);/g,
  883. str
  884. );
  885. return modifiedShader;
  886. };
  887. Primitive._appendDistanceDisplayConditionToShader = function (
  888. primitive,
  889. vertexShaderSource,
  890. scene3DOnly
  891. ) {
  892. if (
  893. !defined(primitive._batchTableAttributeIndices.distanceDisplayCondition)
  894. ) {
  895. return vertexShaderSource;
  896. }
  897. const renamedVS = ShaderSource.replaceMain(
  898. vertexShaderSource,
  899. "czm_non_distanceDisplayCondition_main"
  900. );
  901. let distanceDisplayConditionMain =
  902. "void main() \n" +
  903. "{ \n" +
  904. " czm_non_distanceDisplayCondition_main(); \n" +
  905. " vec2 distanceDisplayCondition = czm_batchTable_distanceDisplayCondition(batchId);\n" +
  906. " vec3 boundingSphereCenter3DHigh = czm_batchTable_boundingSphereCenter3DHigh(batchId);\n" +
  907. " vec3 boundingSphereCenter3DLow = czm_batchTable_boundingSphereCenter3DLow(batchId);\n" +
  908. " float boundingSphereRadius = czm_batchTable_boundingSphereRadius(batchId);\n";
  909. if (!scene3DOnly) {
  910. distanceDisplayConditionMain +=
  911. " vec3 boundingSphereCenter2DHigh = czm_batchTable_boundingSphereCenter2DHigh(batchId);\n" +
  912. " vec3 boundingSphereCenter2DLow = czm_batchTable_boundingSphereCenter2DLow(batchId);\n" +
  913. " vec4 centerRTE;\n" +
  914. " if (czm_morphTime == 1.0)\n" +
  915. " {\n" +
  916. " centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n" +
  917. " }\n" +
  918. " else if (czm_morphTime == 0.0)\n" +
  919. " {\n" +
  920. " centerRTE = czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy);\n" +
  921. " }\n" +
  922. " else\n" +
  923. " {\n" +
  924. " centerRTE = czm_columbusViewMorph(\n" +
  925. " czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy),\n" +
  926. " czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow),\n" +
  927. " czm_morphTime);\n" +
  928. " }\n";
  929. } else {
  930. distanceDisplayConditionMain +=
  931. " vec4 centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n";
  932. }
  933. distanceDisplayConditionMain +=
  934. " float radiusSq = boundingSphereRadius * boundingSphereRadius; \n" +
  935. " float distanceSq; \n" +
  936. " if (czm_sceneMode == czm_sceneMode2D) \n" +
  937. " { \n" +
  938. " distanceSq = czm_eyeHeight2D.y - radiusSq; \n" +
  939. " } \n" +
  940. " else \n" +
  941. " { \n" +
  942. " distanceSq = dot(centerRTE.xyz, centerRTE.xyz) - radiusSq; \n" +
  943. " } \n" +
  944. " distanceSq = max(distanceSq, 0.0); \n" +
  945. " float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x; \n" +
  946. " float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y; \n" +
  947. " float show = (distanceSq >= nearSq && distanceSq <= farSq) ? 1.0 : 0.0; \n" +
  948. " gl_Position *= show; \n" +
  949. "}";
  950. return `${renamedVS}\n${distanceDisplayConditionMain}`;
  951. };
  952. function modifyForEncodedNormals(primitive, vertexShaderSource) {
  953. if (!primitive.compressVertices) {
  954. return vertexShaderSource;
  955. }
  956. const containsNormal =
  957. vertexShaderSource.search(/in\s+vec3\s+normal;/g) !== -1;
  958. const containsSt = vertexShaderSource.search(/in\s+vec2\s+st;/g) !== -1;
  959. if (!containsNormal && !containsSt) {
  960. return vertexShaderSource;
  961. }
  962. const containsTangent =
  963. vertexShaderSource.search(/in\s+vec3\s+tangent;/g) !== -1;
  964. const containsBitangent =
  965. vertexShaderSource.search(/in\s+vec3\s+bitangent;/g) !== -1;
  966. let numComponents = containsSt && containsNormal ? 2.0 : 1.0;
  967. numComponents += containsTangent || containsBitangent ? 1 : 0;
  968. const type = numComponents > 1 ? `vec${numComponents}` : "float";
  969. const attributeName = "compressedAttributes";
  970. const attributeDecl = `in ${type} ${attributeName};`;
  971. let globalDecl = "";
  972. let decode = "";
  973. if (containsSt) {
  974. globalDecl += "vec2 st;\n";
  975. const stComponent =
  976. numComponents > 1 ? `${attributeName}.x` : attributeName;
  977. decode += ` st = czm_decompressTextureCoordinates(${stComponent});\n`;
  978. }
  979. if (containsNormal && containsTangent && containsBitangent) {
  980. globalDecl += "vec3 normal;\n" + "vec3 tangent;\n" + "vec3 bitangent;\n";
  981. decode += ` czm_octDecode(${attributeName}.${
  982. containsSt ? "yz" : "xy"
  983. }, normal, tangent, bitangent);\n`;
  984. } else {
  985. if (containsNormal) {
  986. globalDecl += "vec3 normal;\n";
  987. decode += ` normal = czm_octDecode(${attributeName}${
  988. numComponents > 1 ? `.${containsSt ? "y" : "x"}` : ""
  989. });\n`;
  990. }
  991. if (containsTangent) {
  992. globalDecl += "vec3 tangent;\n";
  993. decode += ` tangent = czm_octDecode(${attributeName}.${
  994. containsSt && containsNormal ? "z" : "y"
  995. });\n`;
  996. }
  997. if (containsBitangent) {
  998. globalDecl += "vec3 bitangent;\n";
  999. decode += ` bitangent = czm_octDecode(${attributeName}.${
  1000. containsSt && containsNormal ? "z" : "y"
  1001. });\n`;
  1002. }
  1003. }
  1004. let modifiedVS = vertexShaderSource;
  1005. modifiedVS = modifiedVS.replace(/in\s+vec3\s+normal;/g, "");
  1006. modifiedVS = modifiedVS.replace(/in\s+vec2\s+st;/g, "");
  1007. modifiedVS = modifiedVS.replace(/in\s+vec3\s+tangent;/g, "");
  1008. modifiedVS = modifiedVS.replace(/in\s+vec3\s+bitangent;/g, "");
  1009. modifiedVS = ShaderSource.replaceMain(modifiedVS, "czm_non_compressed_main");
  1010. const compressedMain =
  1011. `${"void main() \n" + "{ \n"}${decode} czm_non_compressed_main(); \n` +
  1012. `}`;
  1013. return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
  1014. }
  1015. function depthClampVS(vertexShaderSource) {
  1016. let modifiedVS = ShaderSource.replaceMain(
  1017. vertexShaderSource,
  1018. "czm_non_depth_clamp_main"
  1019. );
  1020. modifiedVS +=
  1021. "void main() {\n" +
  1022. " czm_non_depth_clamp_main();\n" +
  1023. " gl_Position = czm_depthClamp(gl_Position);" +
  1024. "}\n";
  1025. return modifiedVS;
  1026. }
  1027. function depthClampFS(fragmentShaderSource) {
  1028. let modifiedFS = ShaderSource.replaceMain(
  1029. fragmentShaderSource,
  1030. "czm_non_depth_clamp_main"
  1031. );
  1032. modifiedFS +=
  1033. "void main() {\n" +
  1034. " czm_non_depth_clamp_main();\n" +
  1035. " #if defined(LOG_DEPTH)\n" +
  1036. " czm_writeLogDepth();\n" +
  1037. " #else\n" +
  1038. " czm_writeDepthClamp();\n" +
  1039. " #endif\n" +
  1040. "}\n";
  1041. return modifiedFS;
  1042. }
  1043. function validateShaderMatching(shaderProgram, attributeLocations) {
  1044. // For a VAO and shader program to be compatible, the VAO must have
  1045. // all active attribute in the shader program. The VAO may have
  1046. // extra attributes with the only concern being a potential
  1047. // performance hit due to extra memory bandwidth and cache pollution.
  1048. // The shader source could have extra attributes that are not used,
  1049. // but there is no guarantee they will be optimized out.
  1050. //
  1051. // Here, we validate that the VAO has all attributes required
  1052. // to match the shader program.
  1053. const shaderAttributes = shaderProgram.vertexAttributes;
  1054. //>>includeStart('debug', pragmas.debug);
  1055. for (const name in shaderAttributes) {
  1056. if (shaderAttributes.hasOwnProperty(name)) {
  1057. if (!defined(attributeLocations[name])) {
  1058. throw new DeveloperError(
  1059. `Appearance/Geometry mismatch. The appearance requires vertex shader attribute input '${name}', which was not computed as part of the Geometry. Use the appearance's vertexFormat property when constructing the geometry.`
  1060. );
  1061. }
  1062. }
  1063. }
  1064. //>>includeEnd('debug');
  1065. }
  1066. function getUniformFunction(uniforms, name) {
  1067. return function () {
  1068. return uniforms[name];
  1069. };
  1070. }
  1071. const numberOfCreationWorkers = Math.max(
  1072. FeatureDetection.hardwareConcurrency - 1,
  1073. 1
  1074. );
  1075. let createGeometryTaskProcessors;
  1076. const combineGeometryTaskProcessor = new TaskProcessor("combineGeometry");
  1077. function loadAsynchronous(primitive, frameState) {
  1078. let instances;
  1079. let geometry;
  1080. let i;
  1081. let j;
  1082. const instanceIds = primitive._instanceIds;
  1083. if (primitive._state === PrimitiveState.READY) {
  1084. instances = Array.isArray(primitive.geometryInstances)
  1085. ? primitive.geometryInstances
  1086. : [primitive.geometryInstances];
  1087. const length = (primitive._numberOfInstances = instances.length);
  1088. const promises = [];
  1089. let subTasks = [];
  1090. for (i = 0; i < length; ++i) {
  1091. geometry = instances[i].geometry;
  1092. instanceIds.push(instances[i].id);
  1093. //>>includeStart('debug', pragmas.debug);
  1094. if (!defined(geometry._workerName)) {
  1095. throw new DeveloperError(
  1096. "_workerName must be defined for asynchronous geometry."
  1097. );
  1098. }
  1099. //>>includeEnd('debug');
  1100. subTasks.push({
  1101. moduleName: geometry._workerName,
  1102. geometry: geometry,
  1103. });
  1104. }
  1105. if (!defined(createGeometryTaskProcessors)) {
  1106. createGeometryTaskProcessors = new Array(numberOfCreationWorkers);
  1107. for (i = 0; i < numberOfCreationWorkers; i++) {
  1108. createGeometryTaskProcessors[i] = new TaskProcessor("createGeometry");
  1109. }
  1110. }
  1111. let subTask;
  1112. subTasks = subdivideArray(subTasks, numberOfCreationWorkers);
  1113. for (i = 0; i < subTasks.length; i++) {
  1114. let packedLength = 0;
  1115. const workerSubTasks = subTasks[i];
  1116. const workerSubTasksLength = workerSubTasks.length;
  1117. for (j = 0; j < workerSubTasksLength; ++j) {
  1118. subTask = workerSubTasks[j];
  1119. geometry = subTask.geometry;
  1120. if (defined(geometry.constructor.pack)) {
  1121. subTask.offset = packedLength;
  1122. packedLength += defaultValue(
  1123. geometry.constructor.packedLength,
  1124. geometry.packedLength
  1125. );
  1126. }
  1127. }
  1128. let subTaskTransferableObjects;
  1129. if (packedLength > 0) {
  1130. const array = new Float64Array(packedLength);
  1131. subTaskTransferableObjects = [array.buffer];
  1132. for (j = 0; j < workerSubTasksLength; ++j) {
  1133. subTask = workerSubTasks[j];
  1134. geometry = subTask.geometry;
  1135. if (defined(geometry.constructor.pack)) {
  1136. geometry.constructor.pack(geometry, array, subTask.offset);
  1137. subTask.geometry = array;
  1138. }
  1139. }
  1140. }
  1141. promises.push(
  1142. createGeometryTaskProcessors[i].scheduleTask(
  1143. {
  1144. subTasks: subTasks[i],
  1145. },
  1146. subTaskTransferableObjects
  1147. )
  1148. );
  1149. }
  1150. primitive._state = PrimitiveState.CREATING;
  1151. Promise.all(promises)
  1152. .then(function (results) {
  1153. primitive._createGeometryResults = results;
  1154. primitive._state = PrimitiveState.CREATED;
  1155. })
  1156. .catch(function (error) {
  1157. setReady(primitive, frameState, PrimitiveState.FAILED, error);
  1158. });
  1159. } else if (primitive._state === PrimitiveState.CREATED) {
  1160. const transferableObjects = [];
  1161. instances = Array.isArray(primitive.geometryInstances)
  1162. ? primitive.geometryInstances
  1163. : [primitive.geometryInstances];
  1164. const scene3DOnly = frameState.scene3DOnly;
  1165. const projection = frameState.mapProjection;
  1166. const promise = combineGeometryTaskProcessor.scheduleTask(
  1167. PrimitivePipeline.packCombineGeometryParameters(
  1168. {
  1169. createGeometryResults: primitive._createGeometryResults,
  1170. instances: instances,
  1171. ellipsoid: projection.ellipsoid,
  1172. projection: projection,
  1173. elementIndexUintSupported: frameState.context.elementIndexUint,
  1174. scene3DOnly: scene3DOnly,
  1175. vertexCacheOptimize: primitive.vertexCacheOptimize,
  1176. compressVertices: primitive.compressVertices,
  1177. modelMatrix: primitive.modelMatrix,
  1178. createPickOffsets: primitive._createPickOffsets,
  1179. },
  1180. transferableObjects
  1181. ),
  1182. transferableObjects
  1183. );
  1184. primitive._createGeometryResults = undefined;
  1185. primitive._state = PrimitiveState.COMBINING;
  1186. Promise.resolve(promise)
  1187. .then(function (packedResult) {
  1188. const result = PrimitivePipeline.unpackCombineGeometryResults(
  1189. packedResult
  1190. );
  1191. primitive._geometries = result.geometries;
  1192. primitive._attributeLocations = result.attributeLocations;
  1193. primitive.modelMatrix = Matrix4.clone(
  1194. result.modelMatrix,
  1195. primitive.modelMatrix
  1196. );
  1197. primitive._pickOffsets = result.pickOffsets;
  1198. primitive._offsetInstanceExtend = result.offsetInstanceExtend;
  1199. primitive._instanceBoundingSpheres = result.boundingSpheres;
  1200. primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
  1201. if (
  1202. defined(primitive._geometries) &&
  1203. primitive._geometries.length > 0
  1204. ) {
  1205. primitive._recomputeBoundingSpheres = true;
  1206. primitive._state = PrimitiveState.COMBINED;
  1207. } else {
  1208. setReady(primitive, frameState, PrimitiveState.FAILED, undefined);
  1209. }
  1210. })
  1211. .catch(function (error) {
  1212. setReady(primitive, frameState, PrimitiveState.FAILED, error);
  1213. });
  1214. }
  1215. }
  1216. function loadSynchronous(primitive, frameState) {
  1217. const instances = Array.isArray(primitive.geometryInstances)
  1218. ? primitive.geometryInstances
  1219. : [primitive.geometryInstances];
  1220. const length = (primitive._numberOfInstances = instances.length);
  1221. const clonedInstances = new Array(length);
  1222. const instanceIds = primitive._instanceIds;
  1223. let instance;
  1224. let i;
  1225. let geometryIndex = 0;
  1226. for (i = 0; i < length; i++) {
  1227. instance = instances[i];
  1228. const geometry = instance.geometry;
  1229. let createdGeometry;
  1230. if (defined(geometry.attributes) && defined(geometry.primitiveType)) {
  1231. createdGeometry = cloneGeometry(geometry);
  1232. } else {
  1233. createdGeometry = geometry.constructor.createGeometry(geometry);
  1234. }
  1235. clonedInstances[geometryIndex++] = cloneInstance(instance, createdGeometry);
  1236. instanceIds.push(instance.id);
  1237. }
  1238. clonedInstances.length = geometryIndex;
  1239. const scene3DOnly = frameState.scene3DOnly;
  1240. const projection = frameState.mapProjection;
  1241. const result = PrimitivePipeline.combineGeometry({
  1242. instances: clonedInstances,
  1243. ellipsoid: projection.ellipsoid,
  1244. projection: projection,
  1245. elementIndexUintSupported: frameState.context.elementIndexUint,
  1246. scene3DOnly: scene3DOnly,
  1247. vertexCacheOptimize: primitive.vertexCacheOptimize,
  1248. compressVertices: primitive.compressVertices,
  1249. modelMatrix: primitive.modelMatrix,
  1250. createPickOffsets: primitive._createPickOffsets,
  1251. });
  1252. primitive._geometries = result.geometries;
  1253. primitive._attributeLocations = result.attributeLocations;
  1254. primitive.modelMatrix = Matrix4.clone(
  1255. result.modelMatrix,
  1256. primitive.modelMatrix
  1257. );
  1258. primitive._pickOffsets = result.pickOffsets;
  1259. primitive._offsetInstanceExtend = result.offsetInstanceExtend;
  1260. primitive._instanceBoundingSpheres = result.boundingSpheres;
  1261. primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
  1262. if (defined(primitive._geometries) && primitive._geometries.length > 0) {
  1263. primitive._recomputeBoundingSpheres = true;
  1264. primitive._state = PrimitiveState.COMBINED;
  1265. } else {
  1266. setReady(primitive, frameState, PrimitiveState.FAILED, undefined);
  1267. }
  1268. }
  1269. function recomputeBoundingSpheres(primitive, frameState) {
  1270. const offsetIndex = primitive._batchTableAttributeIndices.offset;
  1271. if (!primitive._recomputeBoundingSpheres || !defined(offsetIndex)) {
  1272. primitive._recomputeBoundingSpheres = false;
  1273. return;
  1274. }
  1275. let i;
  1276. const offsetInstanceExtend = primitive._offsetInstanceExtend;
  1277. const boundingSpheres = primitive._instanceBoundingSpheres;
  1278. const length = boundingSpheres.length;
  1279. let newBoundingSpheres = primitive._tempBoundingSpheres;
  1280. if (!defined(newBoundingSpheres)) {
  1281. newBoundingSpheres = new Array(length);
  1282. for (i = 0; i < length; i++) {
  1283. newBoundingSpheres[i] = new BoundingSphere();
  1284. }
  1285. primitive._tempBoundingSpheres = newBoundingSpheres;
  1286. }
  1287. for (i = 0; i < length; ++i) {
  1288. let newBS = newBoundingSpheres[i];
  1289. const offset = primitive._batchTable.getBatchedAttribute(
  1290. i,
  1291. offsetIndex,
  1292. new Cartesian3()
  1293. );
  1294. newBS = boundingSpheres[i].clone(newBS);
  1295. transformBoundingSphere(newBS, offset, offsetInstanceExtend[i]);
  1296. }
  1297. const combinedBS = [];
  1298. const combinedWestBS = [];
  1299. const combinedEastBS = [];
  1300. for (i = 0; i < length; ++i) {
  1301. const bs = newBoundingSpheres[i];
  1302. const minX = bs.center.x - bs.radius;
  1303. if (
  1304. minX > 0 ||
  1305. BoundingSphere.intersectPlane(bs, Plane.ORIGIN_ZX_PLANE) !==
  1306. Intersect.INTERSECTING
  1307. ) {
  1308. combinedBS.push(bs);
  1309. } else {
  1310. combinedWestBS.push(bs);
  1311. combinedEastBS.push(bs);
  1312. }
  1313. }
  1314. let resultBS1 = combinedBS[0];
  1315. let resultBS2 = combinedEastBS[0];
  1316. let resultBS3 = combinedWestBS[0];
  1317. for (i = 1; i < combinedBS.length; i++) {
  1318. resultBS1 = BoundingSphere.union(resultBS1, combinedBS[i]);
  1319. }
  1320. for (i = 1; i < combinedEastBS.length; i++) {
  1321. resultBS2 = BoundingSphere.union(resultBS2, combinedEastBS[i]);
  1322. }
  1323. for (i = 1; i < combinedWestBS.length; i++) {
  1324. resultBS3 = BoundingSphere.union(resultBS3, combinedWestBS[i]);
  1325. }
  1326. const result = [];
  1327. if (defined(resultBS1)) {
  1328. result.push(resultBS1);
  1329. }
  1330. if (defined(resultBS2)) {
  1331. result.push(resultBS2);
  1332. }
  1333. if (defined(resultBS3)) {
  1334. result.push(resultBS3);
  1335. }
  1336. for (i = 0; i < result.length; i++) {
  1337. const boundingSphere = result[i].clone(primitive._boundingSpheres[i]);
  1338. primitive._boundingSpheres[i] = boundingSphere;
  1339. primitive._boundingSphereCV[i] = BoundingSphere.projectTo2D(
  1340. boundingSphere,
  1341. frameState.mapProjection,
  1342. primitive._boundingSphereCV[i]
  1343. );
  1344. }
  1345. Primitive._updateBoundingVolumes(
  1346. primitive,
  1347. frameState,
  1348. primitive.modelMatrix,
  1349. true
  1350. );
  1351. primitive._recomputeBoundingSpheres = false;
  1352. }
  1353. const scratchBoundingSphereCenterEncoded = new EncodedCartesian3();
  1354. const scratchBoundingSphereCartographic = new Cartographic();
  1355. const scratchBoundingSphereCenter2D = new Cartesian3();
  1356. const scratchBoundingSphere = new BoundingSphere();
  1357. function updateBatchTableBoundingSpheres(primitive, frameState) {
  1358. const hasDistanceDisplayCondition = defined(
  1359. primitive._batchTableAttributeIndices.distanceDisplayCondition
  1360. );
  1361. if (
  1362. !hasDistanceDisplayCondition ||
  1363. primitive._batchTableBoundingSpheresUpdated
  1364. ) {
  1365. return;
  1366. }
  1367. const indices = primitive._batchTableBoundingSphereAttributeIndices;
  1368. const center3DHighIndex = indices.center3DHigh;
  1369. const center3DLowIndex = indices.center3DLow;
  1370. const center2DHighIndex = indices.center2DHigh;
  1371. const center2DLowIndex = indices.center2DLow;
  1372. const radiusIndex = indices.radius;
  1373. const projection = frameState.mapProjection;
  1374. const ellipsoid = projection.ellipsoid;
  1375. const batchTable = primitive._batchTable;
  1376. const boundingSpheres = primitive._instanceBoundingSpheres;
  1377. const length = boundingSpheres.length;
  1378. for (let i = 0; i < length; ++i) {
  1379. let boundingSphere = boundingSpheres[i];
  1380. if (!defined(boundingSphere)) {
  1381. continue;
  1382. }
  1383. const modelMatrix = primitive.modelMatrix;
  1384. if (defined(modelMatrix)) {
  1385. boundingSphere = BoundingSphere.transform(
  1386. boundingSphere,
  1387. modelMatrix,
  1388. scratchBoundingSphere
  1389. );
  1390. }
  1391. const center = boundingSphere.center;
  1392. const radius = boundingSphere.radius;
  1393. let encodedCenter = EncodedCartesian3.fromCartesian(
  1394. center,
  1395. scratchBoundingSphereCenterEncoded
  1396. );
  1397. batchTable.setBatchedAttribute(i, center3DHighIndex, encodedCenter.high);
  1398. batchTable.setBatchedAttribute(i, center3DLowIndex, encodedCenter.low);
  1399. if (!frameState.scene3DOnly) {
  1400. const cartographic = ellipsoid.cartesianToCartographic(
  1401. center,
  1402. scratchBoundingSphereCartographic
  1403. );
  1404. const center2D = projection.project(
  1405. cartographic,
  1406. scratchBoundingSphereCenter2D
  1407. );
  1408. encodedCenter = EncodedCartesian3.fromCartesian(
  1409. center2D,
  1410. scratchBoundingSphereCenterEncoded
  1411. );
  1412. batchTable.setBatchedAttribute(i, center2DHighIndex, encodedCenter.high);
  1413. batchTable.setBatchedAttribute(i, center2DLowIndex, encodedCenter.low);
  1414. }
  1415. batchTable.setBatchedAttribute(i, radiusIndex, radius);
  1416. }
  1417. primitive._batchTableBoundingSpheresUpdated = true;
  1418. }
  1419. const offsetScratchCartesian = new Cartesian3();
  1420. const offsetCenterScratch = new Cartesian3();
  1421. function updateBatchTableOffsets(primitive, frameState) {
  1422. const hasOffset = defined(primitive._batchTableAttributeIndices.offset);
  1423. if (
  1424. !hasOffset ||
  1425. primitive._batchTableOffsetsUpdated ||
  1426. frameState.scene3DOnly
  1427. ) {
  1428. return;
  1429. }
  1430. const index2D = primitive._batchTableOffsetAttribute2DIndex;
  1431. const projection = frameState.mapProjection;
  1432. const ellipsoid = projection.ellipsoid;
  1433. const batchTable = primitive._batchTable;
  1434. const boundingSpheres = primitive._instanceBoundingSpheres;
  1435. const length = boundingSpheres.length;
  1436. for (let i = 0; i < length; ++i) {
  1437. let boundingSphere = boundingSpheres[i];
  1438. if (!defined(boundingSphere)) {
  1439. continue;
  1440. }
  1441. const offset = batchTable.getBatchedAttribute(
  1442. i,
  1443. primitive._batchTableAttributeIndices.offset
  1444. );
  1445. if (Cartesian3.equals(offset, Cartesian3.ZERO)) {
  1446. batchTable.setBatchedAttribute(i, index2D, Cartesian3.ZERO);
  1447. continue;
  1448. }
  1449. const modelMatrix = primitive.modelMatrix;
  1450. if (defined(modelMatrix)) {
  1451. boundingSphere = BoundingSphere.transform(
  1452. boundingSphere,
  1453. modelMatrix,
  1454. scratchBoundingSphere
  1455. );
  1456. }
  1457. let center = boundingSphere.center;
  1458. center = ellipsoid.scaleToGeodeticSurface(center, offsetCenterScratch);
  1459. let cartographic = ellipsoid.cartesianToCartographic(
  1460. center,
  1461. scratchBoundingSphereCartographic
  1462. );
  1463. const center2D = projection.project(
  1464. cartographic,
  1465. scratchBoundingSphereCenter2D
  1466. );
  1467. const newPoint = Cartesian3.add(offset, center, offsetScratchCartesian);
  1468. cartographic = ellipsoid.cartesianToCartographic(newPoint, cartographic);
  1469. const newPointProjected = projection.project(
  1470. cartographic,
  1471. offsetScratchCartesian
  1472. );
  1473. const newVector = Cartesian3.subtract(
  1474. newPointProjected,
  1475. center2D,
  1476. offsetScratchCartesian
  1477. );
  1478. const x = newVector.x;
  1479. newVector.x = newVector.z;
  1480. newVector.z = newVector.y;
  1481. newVector.y = x;
  1482. batchTable.setBatchedAttribute(i, index2D, newVector);
  1483. }
  1484. primitive._batchTableOffsetsUpdated = true;
  1485. }
  1486. function createVertexArray(primitive, frameState) {
  1487. const attributeLocations = primitive._attributeLocations;
  1488. const geometries = primitive._geometries;
  1489. const scene3DOnly = frameState.scene3DOnly;
  1490. const context = frameState.context;
  1491. const va = [];
  1492. const length = geometries.length;
  1493. for (let i = 0; i < length; ++i) {
  1494. const geometry = geometries[i];
  1495. va.push(
  1496. VertexArray.fromGeometry({
  1497. context: context,
  1498. geometry: geometry,
  1499. attributeLocations: attributeLocations,
  1500. bufferUsage: BufferUsage.STATIC_DRAW,
  1501. interleave: primitive._interleave,
  1502. })
  1503. );
  1504. if (defined(primitive._createBoundingVolumeFunction)) {
  1505. primitive._createBoundingVolumeFunction(frameState, geometry);
  1506. } else {
  1507. primitive._boundingSpheres.push(
  1508. BoundingSphere.clone(geometry.boundingSphere)
  1509. );
  1510. primitive._boundingSphereWC.push(new BoundingSphere());
  1511. if (!scene3DOnly) {
  1512. const center = geometry.boundingSphereCV.center;
  1513. const x = center.x;
  1514. const y = center.y;
  1515. const z = center.z;
  1516. center.x = z;
  1517. center.y = x;
  1518. center.z = y;
  1519. primitive._boundingSphereCV.push(
  1520. BoundingSphere.clone(geometry.boundingSphereCV)
  1521. );
  1522. primitive._boundingSphere2D.push(new BoundingSphere());
  1523. primitive._boundingSphereMorph.push(new BoundingSphere());
  1524. }
  1525. }
  1526. }
  1527. primitive._va = va;
  1528. primitive._primitiveType = geometries[0].primitiveType;
  1529. if (primitive.releaseGeometryInstances) {
  1530. primitive.geometryInstances = undefined;
  1531. }
  1532. primitive._geometries = undefined;
  1533. setReady(primitive, frameState, PrimitiveState.COMPLETE, undefined);
  1534. }
  1535. function createRenderStates(primitive, context, appearance, twoPasses) {
  1536. let renderState = appearance.getRenderState();
  1537. let rs;
  1538. if (twoPasses) {
  1539. rs = clone(renderState, false);
  1540. rs.cull = {
  1541. enabled: true,
  1542. face: CullFace.BACK,
  1543. };
  1544. primitive._frontFaceRS = RenderState.fromCache(rs);
  1545. rs.cull.face = CullFace.FRONT;
  1546. primitive._backFaceRS = RenderState.fromCache(rs);
  1547. } else {
  1548. primitive._frontFaceRS = RenderState.fromCache(renderState);
  1549. primitive._backFaceRS = primitive._frontFaceRS;
  1550. }
  1551. rs = clone(renderState, false);
  1552. if (defined(primitive._depthFailAppearance)) {
  1553. rs.depthTest.enabled = false;
  1554. }
  1555. if (defined(primitive._depthFailAppearance)) {
  1556. renderState = primitive._depthFailAppearance.getRenderState();
  1557. rs = clone(renderState, false);
  1558. rs.depthTest.func = DepthFunction.GREATER;
  1559. if (twoPasses) {
  1560. rs.cull = {
  1561. enabled: true,
  1562. face: CullFace.BACK,
  1563. };
  1564. primitive._frontFaceDepthFailRS = RenderState.fromCache(rs);
  1565. rs.cull.face = CullFace.FRONT;
  1566. primitive._backFaceDepthFailRS = RenderState.fromCache(rs);
  1567. } else {
  1568. primitive._frontFaceDepthFailRS = RenderState.fromCache(rs);
  1569. primitive._backFaceDepthFailRS = primitive._frontFaceRS;
  1570. }
  1571. }
  1572. }
  1573. function createShaderProgram(primitive, frameState, appearance) {
  1574. const context = frameState.context;
  1575. const attributeLocations = primitive._attributeLocations;
  1576. let vs = primitive._batchTable.getVertexShaderCallback()(
  1577. appearance.vertexShaderSource
  1578. );
  1579. vs = Primitive._appendOffsetToShader(primitive, vs);
  1580. vs = Primitive._appendShowToShader(primitive, vs);
  1581. vs = Primitive._appendDistanceDisplayConditionToShader(
  1582. primitive,
  1583. vs,
  1584. frameState.scene3DOnly
  1585. );
  1586. vs = appendPickToVertexShader(vs);
  1587. vs = Primitive._updateColorAttribute(primitive, vs, false);
  1588. vs = modifyForEncodedNormals(primitive, vs);
  1589. vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
  1590. let fs = appearance.getFragmentShaderSource();
  1591. fs = appendPickToFragmentShader(fs);
  1592. primitive._sp = ShaderProgram.replaceCache({
  1593. context: context,
  1594. shaderProgram: primitive._sp,
  1595. vertexShaderSource: vs,
  1596. fragmentShaderSource: fs,
  1597. attributeLocations: attributeLocations,
  1598. });
  1599. validateShaderMatching(primitive._sp, attributeLocations);
  1600. if (defined(primitive._depthFailAppearance)) {
  1601. vs = primitive._batchTable.getVertexShaderCallback()(
  1602. primitive._depthFailAppearance.vertexShaderSource
  1603. );
  1604. vs = Primitive._appendShowToShader(primitive, vs);
  1605. vs = Primitive._appendDistanceDisplayConditionToShader(
  1606. primitive,
  1607. vs,
  1608. frameState.scene3DOnly
  1609. );
  1610. vs = appendPickToVertexShader(vs);
  1611. vs = Primitive._updateColorAttribute(primitive, vs, true);
  1612. vs = modifyForEncodedNormals(primitive, vs);
  1613. vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
  1614. vs = depthClampVS(vs);
  1615. fs = primitive._depthFailAppearance.getFragmentShaderSource();
  1616. fs = appendPickToFragmentShader(fs);
  1617. fs = depthClampFS(fs);
  1618. primitive._spDepthFail = ShaderProgram.replaceCache({
  1619. context: context,
  1620. shaderProgram: primitive._spDepthFail,
  1621. vertexShaderSource: vs,
  1622. fragmentShaderSource: fs,
  1623. attributeLocations: attributeLocations,
  1624. });
  1625. validateShaderMatching(primitive._spDepthFail, attributeLocations);
  1626. }
  1627. }
  1628. const modifiedModelViewScratch = new Matrix4();
  1629. const rtcScratch = new Cartesian3();
  1630. function getUniforms(primitive, appearance, material, frameState) {
  1631. // Create uniform map by combining uniforms from the appearance and material if either have uniforms.
  1632. const materialUniformMap = defined(material) ? material._uniforms : undefined;
  1633. const appearanceUniformMap = {};
  1634. const appearanceUniforms = appearance.uniforms;
  1635. if (defined(appearanceUniforms)) {
  1636. // Convert to uniform map of functions for the renderer
  1637. for (const name in appearanceUniforms) {
  1638. if (appearanceUniforms.hasOwnProperty(name)) {
  1639. //>>includeStart('debug', pragmas.debug);
  1640. if (defined(materialUniformMap) && defined(materialUniformMap[name])) {
  1641. // Later, we could rename uniforms behind-the-scenes if needed.
  1642. throw new DeveloperError(
  1643. `Appearance and material have a uniform with the same name: ${name}`
  1644. );
  1645. }
  1646. //>>includeEnd('debug');
  1647. appearanceUniformMap[name] = getUniformFunction(
  1648. appearanceUniforms,
  1649. name
  1650. );
  1651. }
  1652. }
  1653. }
  1654. let uniforms = combine(appearanceUniformMap, materialUniformMap);
  1655. uniforms = primitive._batchTable.getUniformMapCallback()(uniforms);
  1656. if (defined(primitive.rtcCenter)) {
  1657. uniforms.u_modifiedModelView = function () {
  1658. const viewMatrix = frameState.context.uniformState.view;
  1659. Matrix4.multiply(
  1660. viewMatrix,
  1661. primitive._modelMatrix,
  1662. modifiedModelViewScratch
  1663. );
  1664. Matrix4.multiplyByPoint(
  1665. modifiedModelViewScratch,
  1666. primitive.rtcCenter,
  1667. rtcScratch
  1668. );
  1669. Matrix4.setTranslation(
  1670. modifiedModelViewScratch,
  1671. rtcScratch,
  1672. modifiedModelViewScratch
  1673. );
  1674. return modifiedModelViewScratch;
  1675. };
  1676. }
  1677. return uniforms;
  1678. }
  1679. function createCommands(
  1680. primitive,
  1681. appearance,
  1682. material,
  1683. translucent,
  1684. twoPasses,
  1685. colorCommands,
  1686. pickCommands,
  1687. frameState
  1688. ) {
  1689. const uniforms = getUniforms(primitive, appearance, material, frameState);
  1690. let depthFailUniforms;
  1691. if (defined(primitive._depthFailAppearance)) {
  1692. depthFailUniforms = getUniforms(
  1693. primitive,
  1694. primitive._depthFailAppearance,
  1695. primitive._depthFailAppearance.material,
  1696. frameState
  1697. );
  1698. }
  1699. const pass = translucent ? Pass.TRANSLUCENT : Pass.OPAQUE;
  1700. let multiplier = twoPasses ? 2 : 1;
  1701. multiplier *= defined(primitive._depthFailAppearance) ? 2 : 1;
  1702. colorCommands.length = primitive._va.length * multiplier;
  1703. const length = colorCommands.length;
  1704. let vaIndex = 0;
  1705. for (let i = 0; i < length; ++i) {
  1706. let colorCommand;
  1707. if (twoPasses) {
  1708. colorCommand = colorCommands[i];
  1709. if (!defined(colorCommand)) {
  1710. colorCommand = colorCommands[i] = new DrawCommand({
  1711. owner: primitive,
  1712. primitiveType: primitive._primitiveType,
  1713. });
  1714. }
  1715. colorCommand.vertexArray = primitive._va[vaIndex];
  1716. colorCommand.renderState = primitive._backFaceRS;
  1717. colorCommand.shaderProgram = primitive._sp;
  1718. colorCommand.uniformMap = uniforms;
  1719. colorCommand.pass = pass;
  1720. ++i;
  1721. }
  1722. colorCommand = colorCommands[i];
  1723. if (!defined(colorCommand)) {
  1724. colorCommand = colorCommands[i] = new DrawCommand({
  1725. owner: primitive,
  1726. primitiveType: primitive._primitiveType,
  1727. });
  1728. }
  1729. colorCommand.vertexArray = primitive._va[vaIndex];
  1730. colorCommand.renderState = primitive._frontFaceRS;
  1731. colorCommand.shaderProgram = primitive._sp;
  1732. colorCommand.uniformMap = uniforms;
  1733. colorCommand.pass = pass;
  1734. if (defined(primitive._depthFailAppearance)) {
  1735. if (twoPasses) {
  1736. ++i;
  1737. colorCommand = colorCommands[i];
  1738. if (!defined(colorCommand)) {
  1739. colorCommand = colorCommands[i] = new DrawCommand({
  1740. owner: primitive,
  1741. primitiveType: primitive._primitiveType,
  1742. });
  1743. }
  1744. colorCommand.vertexArray = primitive._va[vaIndex];
  1745. colorCommand.renderState = primitive._backFaceDepthFailRS;
  1746. colorCommand.shaderProgram = primitive._spDepthFail;
  1747. colorCommand.uniformMap = depthFailUniforms;
  1748. colorCommand.pass = pass;
  1749. }
  1750. ++i;
  1751. colorCommand = colorCommands[i];
  1752. if (!defined(colorCommand)) {
  1753. colorCommand = colorCommands[i] = new DrawCommand({
  1754. owner: primitive,
  1755. primitiveType: primitive._primitiveType,
  1756. });
  1757. }
  1758. colorCommand.vertexArray = primitive._va[vaIndex];
  1759. colorCommand.renderState = primitive._frontFaceDepthFailRS;
  1760. colorCommand.shaderProgram = primitive._spDepthFail;
  1761. colorCommand.uniformMap = depthFailUniforms;
  1762. colorCommand.pass = pass;
  1763. }
  1764. ++vaIndex;
  1765. }
  1766. }
  1767. Primitive._updateBoundingVolumes = function (
  1768. primitive,
  1769. frameState,
  1770. modelMatrix,
  1771. forceUpdate
  1772. ) {
  1773. let i;
  1774. let length;
  1775. let boundingSphere;
  1776. if (forceUpdate || !Matrix4.equals(modelMatrix, primitive._modelMatrix)) {
  1777. Matrix4.clone(modelMatrix, primitive._modelMatrix);
  1778. length = primitive._boundingSpheres.length;
  1779. for (i = 0; i < length; ++i) {
  1780. boundingSphere = primitive._boundingSpheres[i];
  1781. if (defined(boundingSphere)) {
  1782. primitive._boundingSphereWC[i] = BoundingSphere.transform(
  1783. boundingSphere,
  1784. modelMatrix,
  1785. primitive._boundingSphereWC[i]
  1786. );
  1787. if (!frameState.scene3DOnly) {
  1788. primitive._boundingSphere2D[i] = BoundingSphere.clone(
  1789. primitive._boundingSphereCV[i],
  1790. primitive._boundingSphere2D[i]
  1791. );
  1792. primitive._boundingSphere2D[i].center.x = 0.0;
  1793. primitive._boundingSphereMorph[i] = BoundingSphere.union(
  1794. primitive._boundingSphereWC[i],
  1795. primitive._boundingSphereCV[i]
  1796. );
  1797. }
  1798. }
  1799. }
  1800. }
  1801. // Update bounding volumes for primitives that are sized in pixels.
  1802. // The pixel size in meters varies based on the distance from the camera.
  1803. const pixelSize = primitive.appearance.pixelSize;
  1804. if (defined(pixelSize)) {
  1805. length = primitive._boundingSpheres.length;
  1806. for (i = 0; i < length; ++i) {
  1807. boundingSphere = primitive._boundingSpheres[i];
  1808. const boundingSphereWC = primitive._boundingSphereWC[i];
  1809. const pixelSizeInMeters = frameState.camera.getPixelSize(
  1810. boundingSphere,
  1811. frameState.context.drawingBufferWidth,
  1812. frameState.context.drawingBufferHeight
  1813. );
  1814. const sizeInMeters = pixelSizeInMeters * pixelSize;
  1815. boundingSphereWC.radius = boundingSphere.radius + sizeInMeters;
  1816. }
  1817. }
  1818. };
  1819. function updateAndQueueCommands(
  1820. primitive,
  1821. frameState,
  1822. colorCommands,
  1823. pickCommands,
  1824. modelMatrix,
  1825. cull,
  1826. debugShowBoundingVolume,
  1827. twoPasses
  1828. ) {
  1829. //>>includeStart('debug', pragmas.debug);
  1830. if (
  1831. frameState.mode !== SceneMode.SCENE3D &&
  1832. !Matrix4.equals(modelMatrix, Matrix4.IDENTITY)
  1833. ) {
  1834. throw new DeveloperError(
  1835. "Primitive.modelMatrix is only supported in 3D mode."
  1836. );
  1837. }
  1838. //>>includeEnd('debug');
  1839. Primitive._updateBoundingVolumes(primitive, frameState, modelMatrix);
  1840. let boundingSpheres;
  1841. if (frameState.mode === SceneMode.SCENE3D) {
  1842. boundingSpheres = primitive._boundingSphereWC;
  1843. } else if (frameState.mode === SceneMode.COLUMBUS_VIEW) {
  1844. boundingSpheres = primitive._boundingSphereCV;
  1845. } else if (
  1846. frameState.mode === SceneMode.SCENE2D &&
  1847. defined(primitive._boundingSphere2D)
  1848. ) {
  1849. boundingSpheres = primitive._boundingSphere2D;
  1850. } else if (defined(primitive._boundingSphereMorph)) {
  1851. boundingSpheres = primitive._boundingSphereMorph;
  1852. }
  1853. const commandList = frameState.commandList;
  1854. const passes = frameState.passes;
  1855. if (passes.render || passes.pick) {
  1856. const allowPicking = primitive.allowPicking;
  1857. const castShadows = ShadowMode.castShadows(primitive.shadows);
  1858. const receiveShadows = ShadowMode.receiveShadows(primitive.shadows);
  1859. const colorLength = colorCommands.length;
  1860. let factor = twoPasses ? 2 : 1;
  1861. factor *= defined(primitive._depthFailAppearance) ? 2 : 1;
  1862. for (let j = 0; j < colorLength; ++j) {
  1863. const sphereIndex = Math.floor(j / factor);
  1864. const colorCommand = colorCommands[j];
  1865. colorCommand.modelMatrix = modelMatrix;
  1866. colorCommand.boundingVolume = boundingSpheres[sphereIndex];
  1867. colorCommand.cull = cull;
  1868. colorCommand.debugShowBoundingVolume = debugShowBoundingVolume;
  1869. colorCommand.castShadows = castShadows;
  1870. colorCommand.receiveShadows = receiveShadows;
  1871. if (allowPicking) {
  1872. colorCommand.pickId = "v_pickColor";
  1873. } else {
  1874. colorCommand.pickId = undefined;
  1875. }
  1876. commandList.push(colorCommand);
  1877. }
  1878. }
  1879. }
  1880. /**
  1881. * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
  1882. * get the draw commands needed to render this primitive.
  1883. * <p>
  1884. * Do not call this function directly. This is documented just to
  1885. * list the exceptions that may be propagated when the scene is rendered:
  1886. * </p>
  1887. *
  1888. * @exception {DeveloperError} All instance geometries must have the same primitiveType.
  1889. * @exception {DeveloperError} Appearance and material have a uniform with the same name.
  1890. * @exception {DeveloperError} Primitive.modelMatrix is only supported in 3D mode.
  1891. * @exception {RuntimeError} Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero.
  1892. */
  1893. Primitive.prototype.update = function (frameState) {
  1894. if (
  1895. (!defined(this.geometryInstances) && this._va.length === 0) ||
  1896. (defined(this.geometryInstances) &&
  1897. Array.isArray(this.geometryInstances) &&
  1898. this.geometryInstances.length === 0) ||
  1899. !defined(this.appearance) ||
  1900. (frameState.mode !== SceneMode.SCENE3D && frameState.scene3DOnly) ||
  1901. (!frameState.passes.render && !frameState.passes.pick)
  1902. ) {
  1903. return;
  1904. }
  1905. if (defined(this._error)) {
  1906. throw this._error;
  1907. }
  1908. //>>includeStart('debug', pragmas.debug);
  1909. if (defined(this.rtcCenter) && !frameState.scene3DOnly) {
  1910. throw new DeveloperError(
  1911. "RTC rendering is only available for 3D only scenes."
  1912. );
  1913. }
  1914. //>>includeEnd('debug');
  1915. if (this._state === PrimitiveState.FAILED) {
  1916. return;
  1917. }
  1918. const context = frameState.context;
  1919. if (!defined(this._batchTable)) {
  1920. createBatchTable(this, context);
  1921. }
  1922. if (this._batchTable.attributes.length > 0) {
  1923. if (ContextLimits.maximumVertexTextureImageUnits === 0) {
  1924. throw new RuntimeError(
  1925. "Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero."
  1926. );
  1927. }
  1928. this._batchTable.update(frameState);
  1929. }
  1930. if (
  1931. this._state !== PrimitiveState.COMPLETE &&
  1932. this._state !== PrimitiveState.COMBINED
  1933. ) {
  1934. if (this.asynchronous) {
  1935. loadAsynchronous(this, frameState);
  1936. } else {
  1937. loadSynchronous(this, frameState);
  1938. }
  1939. }
  1940. if (this._state === PrimitiveState.COMBINED) {
  1941. updateBatchTableBoundingSpheres(this, frameState);
  1942. updateBatchTableOffsets(this, frameState);
  1943. createVertexArray(this, frameState);
  1944. }
  1945. if (!this.show || this._state !== PrimitiveState.COMPLETE) {
  1946. return;
  1947. }
  1948. if (!this._batchTableOffsetsUpdated) {
  1949. updateBatchTableOffsets(this, frameState);
  1950. }
  1951. if (this._recomputeBoundingSpheres) {
  1952. recomputeBoundingSpheres(this, frameState);
  1953. }
  1954. // Create or recreate render state and shader program if appearance/material changed
  1955. const appearance = this.appearance;
  1956. const material = appearance.material;
  1957. let createRS = false;
  1958. let createSP = false;
  1959. if (this._appearance !== appearance) {
  1960. this._appearance = appearance;
  1961. this._material = material;
  1962. createRS = true;
  1963. createSP = true;
  1964. } else if (this._material !== material) {
  1965. this._material = material;
  1966. createSP = true;
  1967. }
  1968. const depthFailAppearance = this.depthFailAppearance;
  1969. const depthFailMaterial = defined(depthFailAppearance)
  1970. ? depthFailAppearance.material
  1971. : undefined;
  1972. if (this._depthFailAppearance !== depthFailAppearance) {
  1973. this._depthFailAppearance = depthFailAppearance;
  1974. this._depthFailMaterial = depthFailMaterial;
  1975. createRS = true;
  1976. createSP = true;
  1977. } else if (this._depthFailMaterial !== depthFailMaterial) {
  1978. this._depthFailMaterial = depthFailMaterial;
  1979. createSP = true;
  1980. }
  1981. const translucent = this._appearance.isTranslucent();
  1982. if (this._translucent !== translucent) {
  1983. this._translucent = translucent;
  1984. createRS = true;
  1985. }
  1986. if (defined(this._material)) {
  1987. this._material.update(context);
  1988. }
  1989. const twoPasses = appearance.closed && translucent;
  1990. if (createRS) {
  1991. const rsFunc = defaultValue(
  1992. this._createRenderStatesFunction,
  1993. createRenderStates
  1994. );
  1995. rsFunc(this, context, appearance, twoPasses);
  1996. }
  1997. if (createSP) {
  1998. const spFunc = defaultValue(
  1999. this._createShaderProgramFunction,
  2000. createShaderProgram
  2001. );
  2002. spFunc(this, frameState, appearance);
  2003. }
  2004. if (createRS || createSP) {
  2005. const commandFunc = defaultValue(
  2006. this._createCommandsFunction,
  2007. createCommands
  2008. );
  2009. commandFunc(
  2010. this,
  2011. appearance,
  2012. material,
  2013. translucent,
  2014. twoPasses,
  2015. this._colorCommands,
  2016. this._pickCommands,
  2017. frameState
  2018. );
  2019. }
  2020. const updateAndQueueCommandsFunc = defaultValue(
  2021. this._updateAndQueueCommandsFunction,
  2022. updateAndQueueCommands
  2023. );
  2024. updateAndQueueCommandsFunc(
  2025. this,
  2026. frameState,
  2027. this._colorCommands,
  2028. this._pickCommands,
  2029. this.modelMatrix,
  2030. this.cull,
  2031. this.debugShowBoundingVolume,
  2032. twoPasses
  2033. );
  2034. };
  2035. const offsetBoundingSphereScratch1 = new BoundingSphere();
  2036. const offsetBoundingSphereScratch2 = new BoundingSphere();
  2037. function transformBoundingSphere(boundingSphere, offset, offsetAttribute) {
  2038. if (offsetAttribute === GeometryOffsetAttribute.TOP) {
  2039. const origBS = BoundingSphere.clone(
  2040. boundingSphere,
  2041. offsetBoundingSphereScratch1
  2042. );
  2043. const offsetBS = BoundingSphere.clone(
  2044. boundingSphere,
  2045. offsetBoundingSphereScratch2
  2046. );
  2047. offsetBS.center = Cartesian3.add(offsetBS.center, offset, offsetBS.center);
  2048. boundingSphere = BoundingSphere.union(origBS, offsetBS, boundingSphere);
  2049. } else if (offsetAttribute === GeometryOffsetAttribute.ALL) {
  2050. boundingSphere.center = Cartesian3.add(
  2051. boundingSphere.center,
  2052. offset,
  2053. boundingSphere.center
  2054. );
  2055. }
  2056. return boundingSphere;
  2057. }
  2058. function createGetFunction(batchTable, instanceIndex, attributeIndex) {
  2059. return function () {
  2060. const attributeValue = batchTable.getBatchedAttribute(
  2061. instanceIndex,
  2062. attributeIndex
  2063. );
  2064. const attribute = batchTable.attributes[attributeIndex];
  2065. const componentsPerAttribute = attribute.componentsPerAttribute;
  2066. const value = ComponentDatatype.createTypedArray(
  2067. attribute.componentDatatype,
  2068. componentsPerAttribute
  2069. );
  2070. if (defined(attributeValue.constructor.pack)) {
  2071. attributeValue.constructor.pack(attributeValue, value, 0);
  2072. } else {
  2073. value[0] = attributeValue;
  2074. }
  2075. return value;
  2076. };
  2077. }
  2078. function createSetFunction(
  2079. batchTable,
  2080. instanceIndex,
  2081. attributeIndex,
  2082. primitive,
  2083. name
  2084. ) {
  2085. return function (value) {
  2086. //>>includeStart('debug', pragmas.debug);
  2087. if (
  2088. !defined(value) ||
  2089. !defined(value.length) ||
  2090. value.length < 1 ||
  2091. value.length > 4
  2092. ) {
  2093. throw new DeveloperError(
  2094. "value must be and array with length between 1 and 4."
  2095. );
  2096. }
  2097. //>>includeEnd('debug');
  2098. const attributeValue = getAttributeValue(value);
  2099. batchTable.setBatchedAttribute(
  2100. instanceIndex,
  2101. attributeIndex,
  2102. attributeValue
  2103. );
  2104. if (name === "offset") {
  2105. primitive._recomputeBoundingSpheres = true;
  2106. primitive._batchTableOffsetsUpdated = false;
  2107. }
  2108. };
  2109. }
  2110. const offsetScratch = new Cartesian3();
  2111. function createBoundingSphereProperties(primitive, properties, index) {
  2112. properties.boundingSphere = {
  2113. get: function () {
  2114. let boundingSphere = primitive._instanceBoundingSpheres[index];
  2115. if (defined(boundingSphere)) {
  2116. boundingSphere = boundingSphere.clone();
  2117. const modelMatrix = primitive.modelMatrix;
  2118. const offset = properties.offset;
  2119. if (defined(offset)) {
  2120. transformBoundingSphere(
  2121. boundingSphere,
  2122. Cartesian3.fromArray(offset.get(), 0, offsetScratch),
  2123. primitive._offsetInstanceExtend[index]
  2124. );
  2125. }
  2126. if (defined(modelMatrix)) {
  2127. boundingSphere = BoundingSphere.transform(
  2128. boundingSphere,
  2129. modelMatrix
  2130. );
  2131. }
  2132. }
  2133. return boundingSphere;
  2134. },
  2135. };
  2136. properties.boundingSphereCV = {
  2137. get: function () {
  2138. return primitive._instanceBoundingSpheresCV[index];
  2139. },
  2140. };
  2141. }
  2142. function createPickIdProperty(primitive, properties, index) {
  2143. properties.pickId = {
  2144. get: function () {
  2145. return primitive._pickIds[index];
  2146. },
  2147. };
  2148. }
  2149. /**
  2150. * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
  2151. *
  2152. * @param {*} id The id of the {@link GeometryInstance}.
  2153. * @returns {object} The typed array in the attribute's format or undefined if the is no instance with id.
  2154. *
  2155. * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
  2156. *
  2157. * @example
  2158. * const attributes = primitive.getGeometryInstanceAttributes('an id');
  2159. * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
  2160. * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
  2161. * attributes.distanceDisplayCondition = Cesium.DistanceDisplayConditionGeometryInstanceAttribute.toValue(100.0, 10000.0);
  2162. * attributes.offset = Cesium.OffsetGeometryInstanceAttribute.toValue(Cartesian3.IDENTITY);
  2163. */
  2164. Primitive.prototype.getGeometryInstanceAttributes = function (id) {
  2165. //>>includeStart('debug', pragmas.debug);
  2166. if (!defined(id)) {
  2167. throw new DeveloperError("id is required");
  2168. }
  2169. if (!defined(this._batchTable)) {
  2170. throw new DeveloperError(
  2171. "must call update before calling getGeometryInstanceAttributes"
  2172. );
  2173. }
  2174. //>>includeEnd('debug');
  2175. let attributes = this._perInstanceAttributeCache.get(id);
  2176. if (defined(attributes)) {
  2177. return attributes;
  2178. }
  2179. let index = -1;
  2180. const lastIndex = this._lastPerInstanceAttributeIndex;
  2181. const ids = this._instanceIds;
  2182. const length = ids.length;
  2183. for (let i = 0; i < length; ++i) {
  2184. const curIndex = (lastIndex + i) % length;
  2185. if (id === ids[curIndex]) {
  2186. index = curIndex;
  2187. break;
  2188. }
  2189. }
  2190. if (index === -1) {
  2191. return undefined;
  2192. }
  2193. const batchTable = this._batchTable;
  2194. const perInstanceAttributeIndices = this._batchTableAttributeIndices;
  2195. attributes = {};
  2196. const properties = {};
  2197. for (const name in perInstanceAttributeIndices) {
  2198. if (perInstanceAttributeIndices.hasOwnProperty(name)) {
  2199. const attributeIndex = perInstanceAttributeIndices[name];
  2200. properties[name] = {
  2201. get: createGetFunction(batchTable, index, attributeIndex),
  2202. set: createSetFunction(batchTable, index, attributeIndex, this, name),
  2203. };
  2204. }
  2205. }
  2206. createBoundingSphereProperties(this, properties, index);
  2207. createPickIdProperty(this, properties, index);
  2208. Object.defineProperties(attributes, properties);
  2209. this._lastPerInstanceAttributeIndex = index;
  2210. this._perInstanceAttributeCache.set(id, attributes);
  2211. return attributes;
  2212. };
  2213. /**
  2214. * Returns true if this object was destroyed; otherwise, false.
  2215. * <p>
  2216. * If this object was destroyed, it should not be used; calling any function other than
  2217. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  2218. * </p>
  2219. *
  2220. * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  2221. *
  2222. * @see Primitive#destroy
  2223. */
  2224. Primitive.prototype.isDestroyed = function () {
  2225. return false;
  2226. };
  2227. /**
  2228. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  2229. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  2230. * <p>
  2231. * Once an object is destroyed, it should not be used; calling any function other than
  2232. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  2233. * assign the return value (<code>undefined</code>) to the object as done in the example.
  2234. * </p>
  2235. *
  2236. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  2237. *
  2238. *
  2239. * @example
  2240. * e = e && e.destroy();
  2241. *
  2242. * @see Primitive#isDestroyed
  2243. */
  2244. Primitive.prototype.destroy = function () {
  2245. let length;
  2246. let i;
  2247. this._sp = this._sp && this._sp.destroy();
  2248. this._spDepthFail = this._spDepthFail && this._spDepthFail.destroy();
  2249. const va = this._va;
  2250. length = va.length;
  2251. for (i = 0; i < length; ++i) {
  2252. va[i].destroy();
  2253. }
  2254. this._va = undefined;
  2255. const pickIds = this._pickIds;
  2256. length = pickIds.length;
  2257. for (i = 0; i < length; ++i) {
  2258. pickIds[i].destroy();
  2259. }
  2260. this._pickIds = undefined;
  2261. this._batchTable = this._batchTable && this._batchTable.destroy();
  2262. //These objects may be fairly large and reference other large objects (like Entities)
  2263. //We explicitly set them to undefined here so that the memory can be freed
  2264. //even if a reference to the destroyed Primitive has been kept around.
  2265. this._instanceIds = undefined;
  2266. this._perInstanceAttributeCache = undefined;
  2267. this._attributeLocations = undefined;
  2268. return destroyObject(this);
  2269. };
  2270. function setReady(primitive, frameState, state, error) {
  2271. primitive._completeLoad(frameState, state, error);
  2272. }
  2273. export default Primitive;