BatchTexture.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. import Cartesian2 from "../Core/Cartesian2.js";
  2. import Cartesian4 from "../Core/Cartesian4.js";
  3. import Check from "../Core/Check.js";
  4. import Color from "../Core/Color.js";
  5. import createGuid from "../Core/createGuid.js";
  6. import defined from "../Core/defined.js";
  7. import destroyObject from "../Core/destroyObject.js";
  8. import DeveloperError from "../Core/DeveloperError.js";
  9. import PixelFormat from "../Core/PixelFormat.js";
  10. import ContextLimits from "../Renderer/ContextLimits.js";
  11. import PixelDatatype from "../Renderer/PixelDatatype.js";
  12. import Sampler from "../Renderer/Sampler.js";
  13. import Texture from "../Renderer/Texture.js";
  14. /**
  15. * An object that manages color, show/hide and picking textures for a batch
  16. * table or feature table.
  17. *
  18. * @param {object} options Object with the following properties:
  19. * @param {number} featuresLength The number of features in the batch table or feature table
  20. * @param {Cesium3DTileContent|ModelFeatureTable} owner The owner of this batch texture. For 3D Tiles, this will be a {@link Cesium3DTileContent}. For glTF models, this will be a {@link ModelFeatureTable}.
  21. * @param {object} [statistics] The statistics object to update with information about the batch texture.
  22. * @param {Function} [colorChangedCallback] A callback function that is called whenever the color of a feature changes.
  23. *
  24. * @alias BatchTexture
  25. * @constructor
  26. *
  27. * @private
  28. */
  29. function BatchTexture(options) {
  30. //>>includeStart('debug', pragmas.debug);
  31. Check.typeOf.number("options.featuresLength", options.featuresLength);
  32. Check.typeOf.object("options.owner", options.owner);
  33. //>>includeEnd('debug');
  34. this._id = createGuid();
  35. const featuresLength = options.featuresLength;
  36. // PERFORMANCE_IDEA: These parallel arrays probably generate cache misses in get/set color/show
  37. // and use A LOT of memory. How can we use less memory?
  38. this._showAlphaProperties = undefined; // [Show (0 or 255), Alpha (0 to 255)] property for each feature
  39. this._batchValues = undefined; // Per-feature RGBA (A is based on the color's alpha and feature's show property)
  40. this._batchValuesDirty = false;
  41. this._batchTexture = undefined;
  42. this._defaultTexture = undefined;
  43. this._pickTexture = undefined;
  44. this._pickIds = [];
  45. // Dimensions for batch and pick textures
  46. let textureDimensions;
  47. let textureStep;
  48. if (featuresLength > 0) {
  49. // PERFORMANCE_IDEA: this can waste memory in the last row in the uncommon case
  50. // when more than one row is needed (e.g., > 16K features in one tile)
  51. const width = Math.min(featuresLength, ContextLimits.maximumTextureSize);
  52. const height = Math.ceil(featuresLength / ContextLimits.maximumTextureSize);
  53. const stepX = 1.0 / width;
  54. const centerX = stepX * 0.5;
  55. const stepY = 1.0 / height;
  56. const centerY = stepY * 0.5;
  57. textureDimensions = new Cartesian2(width, height);
  58. textureStep = new Cartesian4(stepX, centerX, stepY, centerY);
  59. }
  60. this._translucentFeaturesLength = 0;
  61. this._featuresLength = featuresLength;
  62. this._textureDimensions = textureDimensions;
  63. this._textureStep = textureStep;
  64. this._owner = options.owner;
  65. this._statistics = options.statistics;
  66. this._colorChangedCallback = options.colorChangedCallback;
  67. }
  68. Object.defineProperties(BatchTexture.prototype, {
  69. /**
  70. * Number of features that are translucent
  71. *
  72. * @memberof BatchTexture.prototype
  73. * @type {number}
  74. * @readonly
  75. * @private
  76. */
  77. translucentFeaturesLength: {
  78. get: function () {
  79. return this._translucentFeaturesLength;
  80. },
  81. },
  82. /**
  83. * Total size of all GPU resources used by this batch texture.
  84. *
  85. * @memberof BatchTexture.prototype
  86. * @type {number}
  87. * @readonly
  88. * @private
  89. */
  90. byteLength: {
  91. get: function () {
  92. let memory = 0;
  93. if (defined(this._pickTexture)) {
  94. memory += this._pickTexture.sizeInBytes;
  95. }
  96. if (defined(this._batchTexture)) {
  97. memory += this._batchTexture.sizeInBytes;
  98. }
  99. return memory;
  100. },
  101. },
  102. /**
  103. * Dimensions of the underlying batch texture.
  104. *
  105. * @memberof BatchTexture.prototype
  106. * @type {Cartesian2}
  107. * @readonly
  108. * @private
  109. */
  110. textureDimensions: {
  111. get: function () {
  112. return this._textureDimensions;
  113. },
  114. },
  115. /**
  116. * Size of each texture and distance from side to center of a texel in
  117. * each direction. Stored as (stepX, centerX, stepY, centerY)
  118. *
  119. * @memberof BatchTexture.prototype
  120. * @type {Cartesian4}
  121. * @readonly
  122. * @private
  123. */
  124. textureStep: {
  125. get: function () {
  126. return this._textureStep;
  127. },
  128. },
  129. /**
  130. * The underlying texture used for styling. The texels are accessed
  131. * by batch ID, and the value is the color of this feature after accounting
  132. * for show/hide settings.
  133. *
  134. * @memberof BatchTexture.prototype
  135. * @type {Texture}
  136. * @readonly
  137. * @private
  138. */
  139. batchTexture: {
  140. get: function () {
  141. return this._batchTexture;
  142. },
  143. },
  144. /**
  145. * The default texture to use when there are no batch values
  146. *
  147. * @memberof BatchTexture.prototype
  148. * @type {Texture}
  149. * @readonly
  150. * @private
  151. */
  152. defaultTexture: {
  153. get: function () {
  154. return this._defaultTexture;
  155. },
  156. },
  157. /**
  158. * The underlying texture used for picking. The texels are accessed by
  159. * batch ID, and the value is the pick color.
  160. *
  161. * @memberof BatchTexture.prototype
  162. * @type {Texture}
  163. * @readonly
  164. * @private
  165. */
  166. pickTexture: {
  167. get: function () {
  168. return this._pickTexture;
  169. },
  170. },
  171. });
  172. BatchTexture.DEFAULT_COLOR_VALUE = Color.WHITE;
  173. BatchTexture.DEFAULT_SHOW_VALUE = true;
  174. function getByteLength(batchTexture) {
  175. const dimensions = batchTexture._textureDimensions;
  176. return dimensions.x * dimensions.y * 4;
  177. }
  178. function getBatchValues(batchTexture) {
  179. if (!defined(batchTexture._batchValues)) {
  180. // Default batch texture to RGBA = 255: white highlight (RGB) and show/alpha = true/255 (A).
  181. const byteLength = getByteLength(batchTexture);
  182. const bytes = new Uint8Array(byteLength).fill(255);
  183. batchTexture._batchValues = bytes;
  184. }
  185. return batchTexture._batchValues;
  186. }
  187. function getShowAlphaProperties(batchTexture) {
  188. if (!defined(batchTexture._showAlphaProperties)) {
  189. const byteLength = 2 * batchTexture._featuresLength;
  190. const bytes = new Uint8Array(byteLength).fill(255);
  191. // [Show = true, Alpha = 255]
  192. batchTexture._showAlphaProperties = bytes;
  193. }
  194. return batchTexture._showAlphaProperties;
  195. }
  196. function checkBatchId(batchId, featuresLength) {
  197. if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
  198. throw new DeveloperError(
  199. `batchId is required and between zero and featuresLength - 1 (${featuresLength}` -
  200. +")."
  201. );
  202. }
  203. }
  204. /**
  205. * Set whether a feature is visible.
  206. *
  207. * @param {number} batchId the ID of the feature
  208. * @param {boolean} show <code>true</code> if the feature should be shown, <code>false</code> otherwise
  209. * @private
  210. */
  211. BatchTexture.prototype.setShow = function (batchId, show) {
  212. //>>includeStart('debug', pragmas.debug);
  213. checkBatchId(batchId, this._featuresLength);
  214. Check.typeOf.bool("show", show);
  215. //>>includeEnd('debug');
  216. if (show && !defined(this._showAlphaProperties)) {
  217. // Avoid allocating since the default is show = true
  218. return;
  219. }
  220. const showAlphaProperties = getShowAlphaProperties(this);
  221. const propertyOffset = batchId * 2;
  222. const newShow = show ? 255 : 0;
  223. if (showAlphaProperties[propertyOffset] !== newShow) {
  224. showAlphaProperties[propertyOffset] = newShow;
  225. const batchValues = getBatchValues(this);
  226. // Compute alpha used in the shader based on show and color.alpha properties
  227. const offset = batchId * 4 + 3;
  228. batchValues[offset] = show ? showAlphaProperties[propertyOffset + 1] : 0;
  229. this._batchValuesDirty = true;
  230. }
  231. };
  232. /**
  233. * Set the show for all features at once.
  234. *
  235. * @param {boolean} show <code>true</code> if the feature should be shown, <code>false</code> otherwise
  236. * @private
  237. */
  238. BatchTexture.prototype.setAllShow = function (show) {
  239. //>>includeStart('debug', pragmas.debug);
  240. Check.typeOf.bool("show", show);
  241. //>>includeEnd('debug');
  242. const featuresLength = this._featuresLength;
  243. for (let i = 0; i < featuresLength; ++i) {
  244. this.setShow(i, show);
  245. }
  246. };
  247. /**
  248. * Check the current show value for a feature
  249. *
  250. * @param {number} batchId the ID of the feature
  251. * @return {boolean} <code>true</code> if the feature is shown, or <code>false</code> otherwise
  252. * @private
  253. */
  254. BatchTexture.prototype.getShow = function (batchId) {
  255. //>>includeStart('debug', pragmas.debug);
  256. checkBatchId(batchId, this._featuresLength);
  257. //>>includeEnd('debug');
  258. if (!defined(this._showAlphaProperties)) {
  259. // Avoid allocating since the default is show = true
  260. return true;
  261. }
  262. const offset = batchId * 2;
  263. return this._showAlphaProperties[offset] === 255;
  264. };
  265. const scratchColorBytes = new Array(4);
  266. /**
  267. * Set the styling color of a feature
  268. *
  269. * @param {number} batchId the ID of the feature
  270. * @param {Color} color the color to assign to this feature.
  271. *
  272. * @private
  273. */
  274. BatchTexture.prototype.setColor = function (batchId, color) {
  275. //>>includeStart('debug', pragmas.debug);
  276. checkBatchId(batchId, this._featuresLength);
  277. Check.typeOf.object("color", color);
  278. //>>includeEnd('debug');
  279. if (
  280. Color.equals(color, BatchTexture.DEFAULT_COLOR_VALUE) &&
  281. !defined(this._batchValues)
  282. ) {
  283. // Avoid allocating since the default is white
  284. return;
  285. }
  286. const newColor = color.toBytes(scratchColorBytes);
  287. const newAlpha = newColor[3];
  288. const batchValues = getBatchValues(this);
  289. const offset = batchId * 4;
  290. const showAlphaProperties = getShowAlphaProperties(this);
  291. const propertyOffset = batchId * 2;
  292. if (
  293. batchValues[offset] !== newColor[0] ||
  294. batchValues[offset + 1] !== newColor[1] ||
  295. batchValues[offset + 2] !== newColor[2] ||
  296. showAlphaProperties[propertyOffset + 1] !== newAlpha
  297. ) {
  298. batchValues[offset] = newColor[0];
  299. batchValues[offset + 1] = newColor[1];
  300. batchValues[offset + 2] = newColor[2];
  301. const wasTranslucent = showAlphaProperties[propertyOffset + 1] !== 255;
  302. // Compute alpha used in the shader based on show and color.alpha properties
  303. const show = showAlphaProperties[propertyOffset] !== 0;
  304. batchValues[offset + 3] = show ? newAlpha : 0;
  305. showAlphaProperties[propertyOffset + 1] = newAlpha;
  306. // Track number of translucent features so we know if this tile needs
  307. // opaque commands, translucent commands, or both for rendering.
  308. const isTranslucent = newAlpha !== 255;
  309. if (isTranslucent && !wasTranslucent) {
  310. ++this._translucentFeaturesLength;
  311. } else if (!isTranslucent && wasTranslucent) {
  312. --this._translucentFeaturesLength;
  313. }
  314. this._batchValuesDirty = true;
  315. if (defined(this._colorChangedCallback)) {
  316. this._colorChangedCallback(batchId, color);
  317. }
  318. }
  319. };
  320. /**
  321. * Set the styling color for all features at once
  322. *
  323. * @param {Color} color the color to assign to all features.
  324. *
  325. * @private
  326. */
  327. BatchTexture.prototype.setAllColor = function (color) {
  328. //>>includeStart('debug', pragmas.debug);
  329. Check.typeOf.object("color", color);
  330. //>>includeEnd('debug');
  331. const featuresLength = this._featuresLength;
  332. for (let i = 0; i < featuresLength; ++i) {
  333. this.setColor(i, color);
  334. }
  335. };
  336. /**
  337. * Get the current color of a feature
  338. *
  339. * @param {number} batchId The ID of the feature
  340. * @param {Color} result A color object where the result will be stored.
  341. * @return {Color} The color assigned to the selected feature
  342. *
  343. * @private
  344. */
  345. BatchTexture.prototype.getColor = function (batchId, result) {
  346. //>>includeStart('debug', pragmas.debug);
  347. checkBatchId(batchId, this._featuresLength);
  348. Check.typeOf.object("result", result);
  349. //>>includeEnd('debug');
  350. if (!defined(this._batchValues)) {
  351. return Color.clone(BatchTexture.DEFAULT_COLOR_VALUE, result);
  352. }
  353. const batchValues = this._batchValues;
  354. const offset = batchId * 4;
  355. const showAlphaProperties = this._showAlphaProperties;
  356. const propertyOffset = batchId * 2;
  357. return Color.fromBytes(
  358. batchValues[offset],
  359. batchValues[offset + 1],
  360. batchValues[offset + 2],
  361. showAlphaProperties[propertyOffset + 1],
  362. result
  363. );
  364. };
  365. /**
  366. * Get the pick color of a feature. This feature is an RGBA encoding of the
  367. * pick ID.
  368. *
  369. * @param {number} batchId The ID of the feature
  370. * @return {PickId} The picking color assigned to this feature
  371. *
  372. * @private
  373. */
  374. BatchTexture.prototype.getPickColor = function (batchId) {
  375. //>>includeStart('debug', pragmas.debug);
  376. checkBatchId(batchId, this._featuresLength);
  377. //>>includeEnd('debug');
  378. return this._pickIds[batchId];
  379. };
  380. function createTexture(batchTexture, context, bytes) {
  381. const dimensions = batchTexture._textureDimensions;
  382. return new Texture({
  383. context: context,
  384. pixelFormat: PixelFormat.RGBA,
  385. pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
  386. source: {
  387. width: dimensions.x,
  388. height: dimensions.y,
  389. arrayBufferView: bytes,
  390. },
  391. flipY: false,
  392. sampler: Sampler.NEAREST,
  393. });
  394. }
  395. function createPickTexture(batchTexture, context) {
  396. const featuresLength = batchTexture._featuresLength;
  397. if (!defined(batchTexture._pickTexture) && featuresLength > 0) {
  398. const pickIds = batchTexture._pickIds;
  399. const byteLength = getByteLength(batchTexture);
  400. const bytes = new Uint8Array(byteLength);
  401. const owner = batchTexture._owner;
  402. const statistics = batchTexture._statistics;
  403. // PERFORMANCE_IDEA: we could skip the pick texture completely by allocating
  404. // a continuous range of pickIds and then converting the base pickId + batchId
  405. // to RGBA in the shader. The only consider is precision issues, which might
  406. // not be an issue in WebGL 2.
  407. for (let i = 0; i < featuresLength; ++i) {
  408. const pickId = context.createPickId(owner.getFeature(i));
  409. pickIds.push(pickId);
  410. const pickColor = pickId.color;
  411. const offset = i * 4;
  412. bytes[offset] = Color.floatToByte(pickColor.red);
  413. bytes[offset + 1] = Color.floatToByte(pickColor.green);
  414. bytes[offset + 2] = Color.floatToByte(pickColor.blue);
  415. bytes[offset + 3] = Color.floatToByte(pickColor.alpha);
  416. }
  417. batchTexture._pickTexture = createTexture(batchTexture, context, bytes);
  418. // Make sure the tileset statistics are updated the frame when the pick
  419. // texture is created.
  420. if (defined(statistics)) {
  421. statistics.batchTableByteLength += batchTexture._pickTexture.sizeInBytes;
  422. }
  423. }
  424. }
  425. function updateBatchTexture(batchTexture) {
  426. const dimensions = batchTexture._textureDimensions;
  427. // PERFORMANCE_IDEA: Instead of rewriting the entire texture, use fine-grained
  428. // texture updates when less than, for example, 10%, of the values changed. Or
  429. // even just optimize the common case when one feature show/color changed.
  430. batchTexture._batchTexture.copyFrom({
  431. source: {
  432. width: dimensions.x,
  433. height: dimensions.y,
  434. arrayBufferView: batchTexture._batchValues,
  435. },
  436. });
  437. }
  438. BatchTexture.prototype.update = function (tileset, frameState) {
  439. const context = frameState.context;
  440. this._defaultTexture = context.defaultTexture;
  441. const passes = frameState.passes;
  442. if (passes.pick || passes.postProcess) {
  443. createPickTexture(this, context);
  444. }
  445. if (this._batchValuesDirty) {
  446. this._batchValuesDirty = false;
  447. // Create batch texture on-demand
  448. if (!defined(this._batchTexture)) {
  449. this._batchTexture = createTexture(this, context, this._batchValues);
  450. // Make sure the tileset statistics are updated the frame when the
  451. // batch texture is created.
  452. if (defined(this._statistics)) {
  453. this._statistics.batchTableByteLength += this._batchTexture.sizeInBytes;
  454. }
  455. }
  456. updateBatchTexture(this); // Apply per-feature show/color updates
  457. }
  458. };
  459. /**
  460. * Returns true if this object was destroyed; otherwise, false.
  461. * <p>
  462. * If this object was destroyed, it should not be used; calling any function other than
  463. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  464. * </p>
  465. *
  466. * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  467. *
  468. * @see BatchTexture#destroy
  469. * @private
  470. */
  471. BatchTexture.prototype.isDestroyed = function () {
  472. return false;
  473. };
  474. /**
  475. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  476. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  477. * <p>
  478. * Once an object is destroyed, it should not be used; calling any function other than
  479. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  480. * assign the return value (<code>undefined</code>) to the object as done in the example.
  481. * </p>
  482. *
  483. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  484. *
  485. * @example
  486. * e = e && e.destroy();
  487. *
  488. * @see BatchTexture#isDestroyed
  489. * @private
  490. */
  491. BatchTexture.prototype.destroy = function () {
  492. this._batchTexture = this._batchTexture && this._batchTexture.destroy();
  493. this._pickTexture = this._pickTexture && this._pickTexture.destroy();
  494. const pickIds = this._pickIds;
  495. const length = pickIds.length;
  496. for (let i = 0; i < length; ++i) {
  497. pickIds[i].destroy();
  498. }
  499. return destroyObject(this);
  500. };
  501. export default BatchTexture;