Batched3DModel3DTileContent.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import Cartesian3 from '../Core/Cartesian3.js';
  2. import Color from '../Core/Color.js';
  3. import ComponentDatatype from '../Core/ComponentDatatype.js';
  4. import defaultValue from '../Core/defaultValue.js';
  5. import defined from '../Core/defined.js';
  6. import defineProperties from '../Core/defineProperties.js';
  7. import deprecationWarning from '../Core/deprecationWarning.js';
  8. import destroyObject from '../Core/destroyObject.js';
  9. import DeveloperError from '../Core/DeveloperError.js';
  10. import getStringFromTypedArray from '../Core/getStringFromTypedArray.js';
  11. import Matrix4 from '../Core/Matrix4.js';
  12. import RequestType from '../Core/RequestType.js';
  13. import RuntimeError from '../Core/RuntimeError.js';
  14. import Pass from '../Renderer/Pass.js';
  15. import Axis from './Axis.js';
  16. import Cesium3DTileBatchTable from './Cesium3DTileBatchTable.js';
  17. import Cesium3DTileFeature from './Cesium3DTileFeature.js';
  18. import Cesium3DTileFeatureTable from './Cesium3DTileFeatureTable.js';
  19. import ClassificationModel from './ClassificationModel.js';
  20. import Model from './Model.js';
  21. import ModelUtility from './ModelUtility.js';
  22. /**
  23. * Represents the contents of a
  24. * {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/TileFormats/Batched3DModel|Batched 3D Model}
  25. * tile in a {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification|3D Tiles} tileset.
  26. * <p>
  27. * Implements the {@link Cesium3DTileContent} interface.
  28. * </p>
  29. *
  30. * @alias Batched3DModel3DTileContent
  31. * @constructor
  32. *
  33. * @private
  34. */
  35. function Batched3DModel3DTileContent(tileset, tile, resource, arrayBuffer, byteOffset) {
  36. this._tileset = tileset;
  37. this._tile = tile;
  38. this._resource = resource;
  39. this._model = undefined;
  40. this._batchTable = undefined;
  41. this._features = undefined;
  42. // Populate from gltf when available
  43. this._batchIdAttributeName = undefined;
  44. this._diffuseAttributeOrUniformName = {};
  45. this._rtcCenterTransform = undefined;
  46. this._contentModelMatrix = undefined;
  47. this.featurePropertiesDirty = false;
  48. initialize(this, arrayBuffer, byteOffset);
  49. }
  50. // This can be overridden for testing purposes
  51. Batched3DModel3DTileContent._deprecationWarning = deprecationWarning;
  52. defineProperties(Batched3DModel3DTileContent.prototype, {
  53. featuresLength : {
  54. get : function() {
  55. return this._batchTable.featuresLength;
  56. }
  57. },
  58. pointsLength : {
  59. get : function() {
  60. return 0;
  61. }
  62. },
  63. trianglesLength : {
  64. get : function() {
  65. return this._model.trianglesLength;
  66. }
  67. },
  68. geometryByteLength : {
  69. get : function() {
  70. return this._model.geometryByteLength;
  71. }
  72. },
  73. texturesByteLength : {
  74. get : function() {
  75. return this._model.texturesByteLength;
  76. }
  77. },
  78. batchTableByteLength : {
  79. get : function() {
  80. return this._batchTable.memorySizeInBytes;
  81. }
  82. },
  83. innerContents : {
  84. get : function() {
  85. return undefined;
  86. }
  87. },
  88. readyPromise : {
  89. get : function() {
  90. return this._model.readyPromise;
  91. }
  92. },
  93. tileset : {
  94. get : function() {
  95. return this._tileset;
  96. }
  97. },
  98. tile : {
  99. get : function() {
  100. return this._tile;
  101. }
  102. },
  103. url: {
  104. get: function() {
  105. return this._resource.getUrlComponent(true);
  106. }
  107. },
  108. batchTable : {
  109. get : function() {
  110. return this._batchTable;
  111. }
  112. }
  113. });
  114. var sizeOfUint32 = Uint32Array.BYTES_PER_ELEMENT;
  115. function getBatchIdAttributeName(gltf) {
  116. var batchIdAttributeName = ModelUtility.getAttributeOrUniformBySemantic(gltf, '_BATCHID');
  117. if (!defined(batchIdAttributeName)) {
  118. batchIdAttributeName = ModelUtility.getAttributeOrUniformBySemantic(gltf, 'BATCHID');
  119. if (defined(batchIdAttributeName)) {
  120. Batched3DModel3DTileContent._deprecationWarning('b3dm-legacy-batchid', 'The glTF in this b3dm uses the semantic `BATCHID`. Application-specific semantics should be prefixed with an underscore: `_BATCHID`.');
  121. }
  122. }
  123. return batchIdAttributeName;
  124. }
  125. function getVertexShaderCallback(content) {
  126. return function(vs, programId) {
  127. var batchTable = content._batchTable;
  128. var handleTranslucent = !defined(content._tileset.classificationType);
  129. var gltf = content._model.gltf;
  130. if (defined(gltf)) {
  131. content._batchIdAttributeName = getBatchIdAttributeName(gltf);
  132. content._diffuseAttributeOrUniformName[programId] = ModelUtility.getDiffuseAttributeOrUniform(gltf, programId);
  133. }
  134. var callback = batchTable.getVertexShaderCallback(handleTranslucent, content._batchIdAttributeName, content._diffuseAttributeOrUniformName[programId]);
  135. return defined(callback) ? callback(vs) : vs;
  136. };
  137. }
  138. function getFragmentShaderCallback(content) {
  139. return function(fs, programId) {
  140. var batchTable = content._batchTable;
  141. var handleTranslucent = !defined(content._tileset.classificationType);
  142. var gltf = content._model.gltf;
  143. if (defined(gltf)) {
  144. content._diffuseAttributeOrUniformName[programId] = ModelUtility.getDiffuseAttributeOrUniform(gltf, programId);
  145. }
  146. var callback = batchTable.getFragmentShaderCallback(handleTranslucent, content._diffuseAttributeOrUniformName[programId]);
  147. return defined(callback) ? callback(fs) : fs;
  148. };
  149. }
  150. function getPickIdCallback(content) {
  151. return function() {
  152. return content._batchTable.getPickId();
  153. };
  154. }
  155. function getClassificationFragmentShaderCallback(content) {
  156. return function(fs) {
  157. var batchTable = content._batchTable;
  158. var callback = batchTable.getClassificationFragmentShaderCallback();
  159. return defined(callback) ? callback(fs) : fs;
  160. };
  161. }
  162. function createColorChangedCallback(content) {
  163. return function(batchId, color) {
  164. content._model.updateCommands(batchId, color);
  165. };
  166. }
  167. function initialize(content, arrayBuffer, byteOffset) {
  168. var tileset = content._tileset;
  169. var tile = content._tile;
  170. var resource = content._resource;
  171. var byteStart = defaultValue(byteOffset, 0);
  172. byteOffset = byteStart;
  173. var uint8Array = new Uint8Array(arrayBuffer);
  174. var view = new DataView(arrayBuffer);
  175. byteOffset += sizeOfUint32; // Skip magic
  176. var version = view.getUint32(byteOffset, true);
  177. if (version !== 1) {
  178. throw new RuntimeError('Only Batched 3D Model version 1 is supported. Version ' + version + ' is not.');
  179. }
  180. byteOffset += sizeOfUint32;
  181. var byteLength = view.getUint32(byteOffset, true);
  182. byteOffset += sizeOfUint32;
  183. var featureTableJsonByteLength = view.getUint32(byteOffset, true);
  184. byteOffset += sizeOfUint32;
  185. var featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  186. byteOffset += sizeOfUint32;
  187. var batchTableJsonByteLength = view.getUint32(byteOffset, true);
  188. byteOffset += sizeOfUint32;
  189. var batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  190. byteOffset += sizeOfUint32;
  191. var batchLength;
  192. // Legacy header #1: [batchLength] [batchTableByteLength]
  193. // Legacy header #2: [batchTableJsonByteLength] [batchTableBinaryByteLength] [batchLength]
  194. // Current header: [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength]
  195. // If the header is in the first legacy format 'batchTableJsonByteLength' will be the start of the JSON string (a quotation mark) or the glTF magic.
  196. // Accordingly its first byte will be either 0x22 or 0x67, and so the minimum uint32 expected is 0x22000000 = 570425344 = 570MB. It is unlikely that the feature table JSON will exceed this length.
  197. // The check for the second legacy format is similar, except it checks 'batchTableBinaryByteLength' instead
  198. if (batchTableJsonByteLength >= 570425344) {
  199. // First legacy check
  200. byteOffset -= sizeOfUint32 * 2;
  201. batchLength = featureTableJsonByteLength;
  202. batchTableJsonByteLength = featureTableBinaryByteLength;
  203. batchTableBinaryByteLength = 0;
  204. featureTableJsonByteLength = 0;
  205. featureTableBinaryByteLength = 0;
  206. Batched3DModel3DTileContent._deprecationWarning('b3dm-legacy-header', 'This b3dm header is using the legacy format [batchLength] [batchTableByteLength]. The new format is [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength] from https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/TileFormats/Batched3DModel.');
  207. } else if (batchTableBinaryByteLength >= 570425344) {
  208. // Second legacy check
  209. byteOffset -= sizeOfUint32;
  210. batchLength = batchTableJsonByteLength;
  211. batchTableJsonByteLength = featureTableJsonByteLength;
  212. batchTableBinaryByteLength = featureTableBinaryByteLength;
  213. featureTableJsonByteLength = 0;
  214. featureTableBinaryByteLength = 0;
  215. Batched3DModel3DTileContent._deprecationWarning('b3dm-legacy-header', 'This b3dm header is using the legacy format [batchTableJsonByteLength] [batchTableBinaryByteLength] [batchLength]. The new format is [featureTableJsonByteLength] [featureTableBinaryByteLength] [batchTableJsonByteLength] [batchTableBinaryByteLength] from https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/TileFormats/Batched3DModel.');
  216. }
  217. var featureTableJson;
  218. if (featureTableJsonByteLength === 0) {
  219. featureTableJson = {
  220. BATCH_LENGTH : defaultValue(batchLength, 0)
  221. };
  222. } else {
  223. var featureTableString = getStringFromTypedArray(uint8Array, byteOffset, featureTableJsonByteLength);
  224. featureTableJson = JSON.parse(featureTableString);
  225. byteOffset += featureTableJsonByteLength;
  226. }
  227. var featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  228. byteOffset += featureTableBinaryByteLength;
  229. var featureTable = new Cesium3DTileFeatureTable(featureTableJson, featureTableBinary);
  230. batchLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  231. featureTable.featuresLength = batchLength;
  232. var batchTableJson;
  233. var batchTableBinary;
  234. if (batchTableJsonByteLength > 0) {
  235. // PERFORMANCE_IDEA: is it possible to allocate this on-demand? Perhaps keep the
  236. // arraybuffer/string compressed in memory and then decompress it when it is first accessed.
  237. //
  238. // We could also make another request for it, but that would make the property set/get
  239. // API async, and would double the number of numbers in some cases.
  240. var batchTableString = getStringFromTypedArray(uint8Array, byteOffset, batchTableJsonByteLength);
  241. batchTableJson = JSON.parse(batchTableString);
  242. byteOffset += batchTableJsonByteLength;
  243. if (batchTableBinaryByteLength > 0) {
  244. // Has a batch table binary
  245. batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  246. // Copy the batchTableBinary section and let the underlying ArrayBuffer be freed
  247. batchTableBinary = new Uint8Array(batchTableBinary);
  248. byteOffset += batchTableBinaryByteLength;
  249. }
  250. }
  251. var colorChangedCallback;
  252. if (defined(tileset.classificationType)) {
  253. colorChangedCallback = createColorChangedCallback(content);
  254. }
  255. var batchTable = new Cesium3DTileBatchTable(content, batchLength, batchTableJson, batchTableBinary, colorChangedCallback);
  256. content._batchTable = batchTable;
  257. var gltfByteLength = byteStart + byteLength - byteOffset;
  258. if (gltfByteLength === 0) {
  259. throw new RuntimeError('glTF byte length must be greater than 0.');
  260. }
  261. var gltfView;
  262. if (byteOffset % 4 === 0) {
  263. gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength);
  264. } else {
  265. // Create a copy of the glb so that it is 4-byte aligned
  266. Batched3DModel3DTileContent._deprecationWarning('b3dm-glb-unaligned', 'The embedded glb is not aligned to a 4-byte boundary.');
  267. gltfView = new Uint8Array(uint8Array.subarray(byteOffset, byteOffset + gltfByteLength));
  268. }
  269. var pickObject = {
  270. content : content,
  271. primitive : tileset
  272. };
  273. content._rtcCenterTransform = Matrix4.IDENTITY;
  274. var rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', ComponentDatatype.FLOAT, 3);
  275. if (defined(rtcCenter)) {
  276. content._rtcCenterTransform = Matrix4.fromTranslation(Cartesian3.fromArray(rtcCenter));
  277. }
  278. content._contentModelMatrix = Matrix4.multiply(tile.computedTransform, content._rtcCenterTransform, new Matrix4());
  279. if (!defined(tileset.classificationType)) {
  280. // PERFORMANCE_IDEA: patch the shader on demand, e.g., the first time show/color changes.
  281. // The pick shader still needs to be patched.
  282. content._model = new Model({
  283. gltf : gltfView,
  284. cull : false, // The model is already culled by 3D Tiles
  285. releaseGltfJson : true, // Models are unique and will not benefit from caching so save memory
  286. opaquePass : Pass.CESIUM_3D_TILE, // Draw opaque portions of the model during the 3D Tiles pass
  287. basePath : resource,
  288. requestType : RequestType.TILES3D,
  289. modelMatrix: content._contentModelMatrix,
  290. upAxis : tileset._gltfUpAxis,
  291. forwardAxis : Axis.X,
  292. shadows: tileset.shadows,
  293. debugWireframe: tileset.debugWireframe,
  294. incrementallyLoadTextures : false,
  295. vertexShaderLoaded : getVertexShaderCallback(content),
  296. fragmentShaderLoaded : getFragmentShaderCallback(content),
  297. uniformMapLoaded : batchTable.getUniformMapCallback(),
  298. pickIdLoaded : getPickIdCallback(content),
  299. addBatchIdToGeneratedShaders : (batchLength > 0), // If the batch table has values in it, generated shaders will need a batchId attribute
  300. pickObject : pickObject,
  301. imageBasedLightingFactor : tileset.imageBasedLightingFactor,
  302. lightColor : tileset.lightColor,
  303. luminanceAtZenith : tileset.luminanceAtZenith,
  304. sphericalHarmonicCoefficients : tileset.sphericalHarmonicCoefficients,
  305. specularEnvironmentMaps : tileset.specularEnvironmentMaps
  306. });
  307. } else {
  308. // This transcodes glTF to an internal representation for geometry so we can take advantage of the re-batching of vector data.
  309. // For a list of limitations on the input glTF, see the documentation for classificationType of Cesium3DTileset.
  310. content._model = new ClassificationModel({
  311. gltf : gltfView,
  312. cull : false, // The model is already culled by 3D Tiles
  313. basePath : resource,
  314. requestType : RequestType.TILES3D,
  315. modelMatrix: content._contentModelMatrix,
  316. upAxis : tileset._gltfUpAxis,
  317. forwardAxis : Axis.X,
  318. debugWireframe : tileset.debugWireframe,
  319. vertexShaderLoaded : getVertexShaderCallback(content),
  320. classificationShaderLoaded : getClassificationFragmentShaderCallback(content),
  321. uniformMapLoaded : batchTable.getUniformMapCallback(),
  322. pickIdLoaded : getPickIdCallback(content),
  323. classificationType : tileset._classificationType,
  324. batchTable : batchTable
  325. });
  326. }
  327. }
  328. function createFeatures(content) {
  329. var featuresLength = content.featuresLength;
  330. if (!defined(content._features) && (featuresLength > 0)) {
  331. var features = new Array(featuresLength);
  332. for (var i = 0; i < featuresLength; ++i) {
  333. features[i] = new Cesium3DTileFeature(content, i);
  334. }
  335. content._features = features;
  336. }
  337. }
  338. Batched3DModel3DTileContent.prototype.hasProperty = function(batchId, name) {
  339. return this._batchTable.hasProperty(batchId, name);
  340. };
  341. Batched3DModel3DTileContent.prototype.getFeature = function(batchId) {
  342. //>>includeStart('debug', pragmas.debug);
  343. var featuresLength = this.featuresLength;
  344. if (!defined(batchId) || (batchId < 0) || (batchId >= featuresLength)) {
  345. throw new DeveloperError('batchId is required and between zero and featuresLength - 1 (' + (featuresLength - 1) + ').');
  346. }
  347. //>>includeEnd('debug');
  348. createFeatures(this);
  349. return this._features[batchId];
  350. };
  351. Batched3DModel3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
  352. color = enabled ? color : Color.WHITE;
  353. if (this.featuresLength === 0) {
  354. this._model.color = color;
  355. } else {
  356. this._batchTable.setAllColor(color);
  357. }
  358. };
  359. Batched3DModel3DTileContent.prototype.applyStyle = function(style) {
  360. if (this.featuresLength === 0) {
  361. var hasColorStyle = defined(style) && defined(style.color);
  362. var hasShowStyle = defined(style) && defined(style.show);
  363. this._model.color = hasColorStyle ? style.color.evaluateColor(undefined, this._model.color) : Color.clone(Color.WHITE, this._model.color);
  364. this._model.show = hasShowStyle ? style.show.evaluate(undefined) : true;
  365. } else {
  366. this._batchTable.applyStyle(style);
  367. }
  368. };
  369. Batched3DModel3DTileContent.prototype.update = function(tileset, frameState) {
  370. var commandStart = frameState.commandList.length;
  371. // In the PROCESSING state we may be calling update() to move forward
  372. // the content's resource loading. In the READY state, it will
  373. // actually generate commands.
  374. this._batchTable.update(tileset, frameState);
  375. this._contentModelMatrix = Matrix4.multiply(this._tile.computedTransform, this._rtcCenterTransform, this._contentModelMatrix);
  376. this._model.modelMatrix = this._contentModelMatrix;
  377. this._model.shadows = this._tileset.shadows;
  378. this._model.imageBasedLightingFactor = this._tileset.imageBasedLightingFactor;
  379. this._model.lightColor = this._tileset.lightColor;
  380. this._model.luminanceAtZenith = this._tileset.luminanceAtZenith;
  381. this._model.sphericalHarmonicCoefficients = this._tileset.sphericalHarmonicCoefficients;
  382. this._model.specularEnvironmentMaps = this._tileset.specularEnvironmentMaps;
  383. this._model.debugWireframe = this._tileset.debugWireframe;
  384. // Update clipping planes
  385. var tilesetClippingPlanes = this._tileset.clippingPlanes;
  386. this._model.clippingPlanesOriginMatrix = this._tileset.clippingPlanesOriginMatrix;
  387. if (defined(tilesetClippingPlanes) && this._tile.clippingPlanesDirty) {
  388. // Dereference the clipping planes from the model if they are irrelevant.
  389. // Link/Dereference directly to avoid ownership checks.
  390. // This will also trigger synchronous shader regeneration to remove or add the clipping plane and color blending code.
  391. this._model._clippingPlanes = (tilesetClippingPlanes.enabled && this._tile._isClipped) ? tilesetClippingPlanes : undefined;
  392. }
  393. // If the model references a different ClippingPlaneCollection due to the tileset's collection being replaced with a
  394. // ClippingPlaneCollection that gives this tile the same clipping status, update the model to use the new ClippingPlaneCollection.
  395. if (defined(tilesetClippingPlanes) && defined(this._model._clippingPlanes) && this._model._clippingPlanes !== tilesetClippingPlanes) {
  396. this._model._clippingPlanes = tilesetClippingPlanes;
  397. }
  398. this._model.update(frameState);
  399. // If any commands were pushed, add derived commands
  400. var commandEnd = frameState.commandList.length;
  401. if ((commandStart < commandEnd) && (frameState.passes.render || frameState.passes.pick) && !defined(tileset.classificationType)) {
  402. this._batchTable.addDerivedCommands(frameState, commandStart);
  403. }
  404. };
  405. Batched3DModel3DTileContent.prototype.isDestroyed = function() {
  406. return false;
  407. };
  408. Batched3DModel3DTileContent.prototype.destroy = function() {
  409. this._model = this._model && this._model.destroy();
  410. this._batchTable = this._batchTable && this._batchTable.destroy();
  411. return destroyObject(this);
  412. };
  413. export default Batched3DModel3DTileContent;