babylon.group2d.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5. };
  6. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  10. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11. };
  12. var BABYLON;
  13. (function (BABYLON) {
  14. var Group2D = (function (_super) {
  15. __extends(Group2D, _super);
  16. /**
  17. * Create an Logical or Renderable Group.
  18. * @param settings a combination of settings, possible ones are
  19. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  20. * - children: an array of direct children
  21. * - id a text identifier, for information purpose
  22. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  23. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  24. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  25. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  26. * - zOrder: override the zOrder with the specified value
  27. * - origin: define the normalized origin point location, default [0.5;0.5]
  28. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  29. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  30. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  31. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  32. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  33. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  34. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  35. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  36. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  37. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  38. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  39. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  40. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46. */
  47. function Group2D(settings) {
  48. if (settings == null) {
  49. settings = {};
  50. }
  51. if (settings.origin == null) {
  52. settings.origin = new BABYLON.Vector2(0, 0);
  53. }
  54. _super.call(this, settings);
  55. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  56. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  57. if (this._trackedNode && this.owner) {
  58. this.owner._registerTrackedNode(this);
  59. }
  60. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  61. this.size = size;
  62. this._viewportPosition = BABYLON.Vector2.Zero();
  63. }
  64. Group2D._createCachedCanvasGroup = function (owner) {
  65. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  66. return g;
  67. };
  68. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  69. this._bindCacheTarget();
  70. if (vertexData) {
  71. var uv = vertexData.uvs;
  72. var nodeuv = this._renderableData._cacheNodeUVs;
  73. for (var i = 0; i < 4; i++) {
  74. uv[i * 2 + 0] = nodeuv[i].x;
  75. uv[i * 2 + 1] = nodeuv[i].y;
  76. }
  77. }
  78. if (material) {
  79. material.diffuseTexture = this._renderableData._cacheTexture;
  80. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  81. }
  82. this._renderableData._cacheTexture.hasAlpha = true;
  83. this._unbindCacheTarget();
  84. };
  85. Object.defineProperty(Group2D.prototype, "cachedRect", {
  86. /**
  87. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  88. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  89. */
  90. get: function () {
  91. if (!this._renderableData) {
  92. return null;
  93. }
  94. return this._renderableData._cacheNode;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  100. /**
  101. * The UVs into the MapTexture that map the cached group
  102. */
  103. get: function () {
  104. if (!this._renderableData) {
  105. return null;
  106. }
  107. return this._renderableData._cacheNodeUVs;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  113. get: function () {
  114. if (!this._renderableData) {
  115. return null;
  116. }
  117. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  118. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  119. }
  120. return this._renderableData._cacheNodeUVsChangedObservable;
  121. },
  122. enumerable: true,
  123. configurable: true
  124. });
  125. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  126. /**
  127. * Access the texture that maintains a cached version of the Group2D.
  128. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  129. */
  130. get: function () {
  131. if (!this._renderableData) {
  132. return null;
  133. }
  134. return this._renderableData._cacheTexture;
  135. },
  136. enumerable: true,
  137. configurable: true
  138. });
  139. /**
  140. * Call this method to remove this Group and its children from the Canvas
  141. */
  142. Group2D.prototype.dispose = function () {
  143. if (!_super.prototype.dispose.call(this)) {
  144. return false;
  145. }
  146. if (this._trackedNode != null) {
  147. this.owner._unregisterTrackedNode(this);
  148. this._trackedNode = null;
  149. }
  150. if (this._renderableData) {
  151. this._renderableData.dispose(this.owner.engine);
  152. this._renderableData = null;
  153. }
  154. return true;
  155. };
  156. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  157. /**
  158. * @returns Returns true if the Group render content, false if it's a logical group only
  159. */
  160. get: function () {
  161. return this._isRenderableGroup;
  162. },
  163. enumerable: true,
  164. configurable: true
  165. });
  166. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  167. /**
  168. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  169. */
  170. get: function () {
  171. return this._isCachedGroup;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. Object.defineProperty(Group2D.prototype, "size", {
  177. get: function () {
  178. return this._size;
  179. },
  180. /**
  181. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  182. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  183. */
  184. set: function (val) {
  185. this._size = val;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. Object.defineProperty(Group2D.prototype, "viewportSize", {
  191. get: function () {
  192. return this._viewportSize;
  193. },
  194. enumerable: true,
  195. configurable: true
  196. });
  197. Object.defineProperty(Group2D.prototype, "actualSize", {
  198. get: function () {
  199. // The computed size will be floor on both width and height
  200. var actualSize;
  201. // Return the size if set by the user
  202. if (this._size) {
  203. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  204. }
  205. else {
  206. var m = this.boundingInfo.max();
  207. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  208. }
  209. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  210. if (!actualSize.equals(this._actualSize)) {
  211. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  212. this._actualSize = actualSize;
  213. this.handleGroupChanged(Group2D.actualSizeProperty);
  214. }
  215. return actualSize;
  216. },
  217. enumerable: true,
  218. configurable: true
  219. });
  220. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  221. /**
  222. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  223. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  224. */
  225. get: function () {
  226. return this._cacheBehavior;
  227. },
  228. enumerable: true,
  229. configurable: true
  230. });
  231. Group2D.prototype._addPrimToDirtyList = function (prim) {
  232. this._renderableData._primDirtyList.push(prim);
  233. };
  234. Group2D.prototype._renderCachedCanvas = function () {
  235. this.owner._addGroupRenderCount(1);
  236. this.updateCachedStates(true);
  237. var context = new BABYLON.PrepareRender2DContext();
  238. this._prepareGroupRender(context);
  239. this._groupRender();
  240. };
  241. Object.defineProperty(Group2D.prototype, "trackedNode", {
  242. /**
  243. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  244. */
  245. get: function () {
  246. return this._trackedNode;
  247. },
  248. set: function (val) {
  249. if (val != null) {
  250. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  251. this.owner._registerTrackedNode(this);
  252. }
  253. this._trackedNode = val;
  254. }
  255. else {
  256. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  257. this.owner._unregisterTrackedNode(this);
  258. }
  259. this._trackedNode = null;
  260. }
  261. },
  262. enumerable: true,
  263. configurable: true
  264. });
  265. Group2D.prototype.levelIntersect = function (intersectInfo) {
  266. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  267. return true;
  268. };
  269. Group2D.prototype.updateLevelBoundingInfo = function () {
  270. var size;
  271. // If the size is set by the user, the boundingInfo is computed from this value
  272. if (this.size) {
  273. size = this.size;
  274. }
  275. else {
  276. size = new BABYLON.Size(0, 0);
  277. }
  278. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  279. };
  280. // Method called only on renderable groups to prepare the rendering
  281. Group2D.prototype._prepareGroupRender = function (context) {
  282. var sortedDirtyList = null;
  283. // Update the Global Transformation and visibility status of the changed primitives
  284. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  285. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  286. this.updateCachedStatesOf(sortedDirtyList, true);
  287. }
  288. // Setup the size of the rendering viewport
  289. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  290. if (!this._isCachedGroup) {
  291. // Compute the WebGL viewport's location/size
  292. var t = this._globalTransform.getTranslation();
  293. var s = this.actualSize.clone();
  294. var rs = this.owner._renderingSize;
  295. s.height = Math.min(s.height, rs.height - t.y);
  296. s.width = Math.min(s.width, rs.width - t.x);
  297. var x = t.x;
  298. var y = t.y;
  299. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  300. this._viewportPosition.x = x;
  301. this._viewportPosition.y = y;
  302. var vw = s.width;
  303. var vh = s.height;
  304. if (!this._viewportSize) {
  305. this._viewportSize = new BABYLON.Size(vw, vh);
  306. }
  307. else {
  308. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  309. context.forceRefreshPrimitive = true;
  310. }
  311. this._viewportSize.width = vw;
  312. this._viewportSize.height = vh;
  313. }
  314. }
  315. else {
  316. var newSize = this.actualSize.clone();
  317. if (!newSize.equals(this._viewportSize)) {
  318. context.forceRefreshPrimitive = true;
  319. }
  320. this._viewportSize = newSize;
  321. }
  322. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  323. // If the group is cached, set the dirty flag to true because of the incoming changes
  324. this._cacheGroupDirty = this._isCachedGroup;
  325. // If it's a force refresh, prepare all the children
  326. if (context.forceRefreshPrimitive) {
  327. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  328. var p = _a[_i];
  329. p._prepareRender(context);
  330. }
  331. }
  332. else {
  333. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  334. // the hierarchyDepth in order to prepare primitives from top to bottom
  335. if (!sortedDirtyList) {
  336. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  337. }
  338. sortedDirtyList.forEach(function (p) {
  339. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  340. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  341. if (!p.isDisposed && p._needPrepare()) {
  342. p._prepareRender(context);
  343. }
  344. });
  345. }
  346. // Everything is updated, clear the dirty list
  347. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  348. this._renderableData._primDirtyList.splice(0);
  349. }
  350. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  351. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  352. g._prepareGroupRender(context);
  353. });
  354. };
  355. Group2D.prototype._groupRender = function () {
  356. var _this = this;
  357. var engine = this.owner.engine;
  358. var failedCount = 0;
  359. // First recurse to children render group to render them (in their cache or on screen)
  360. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  361. var childGroup = _a[_i];
  362. childGroup._groupRender();
  363. }
  364. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  365. if (!this.isCachedGroup || this._cacheGroupDirty) {
  366. this.owner._addGroupRenderCount(1);
  367. if (this.isCachedGroup) {
  368. this._bindCacheTarget();
  369. }
  370. else {
  371. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  372. }
  373. var curAlphaTest = engine.getAlphaTesting() === true;
  374. var curDepthWrite = engine.getDepthWrite() === true;
  375. // ===================================================================
  376. // First pass, update the InstancedArray and render Opaque primitives
  377. // Disable Alpha Testing, Enable Depth Write
  378. engine.setAlphaTesting(false);
  379. engine.setDepthWrite(true);
  380. // For each different model of primitive to render
  381. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  382. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  383. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  384. var renderCount = _this._prepareContext(engine, context, v);
  385. // If null is returned, there's no opaque data to render
  386. if (renderCount === null) {
  387. return;
  388. }
  389. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  390. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  391. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  392. var renderFailed = !v.modelRenderCache.render(v, context);
  393. // Update dirty flag/related
  394. v.opaqueDirty = renderFailed;
  395. failedCount += renderFailed ? 1 : 0;
  396. }
  397. });
  398. // =======================================================================
  399. // Second pass, update the InstancedArray and render AlphaTest primitives
  400. // Enable Alpha Testing, Enable Depth Write
  401. engine.setAlphaTesting(true);
  402. engine.setDepthWrite(true);
  403. // For each different model of primitive to render
  404. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  405. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  406. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  407. var renderCount = _this._prepareContext(engine, context, v);
  408. // If null is returned, there's no opaque data to render
  409. if (renderCount === null) {
  410. return;
  411. }
  412. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  413. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  414. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  415. var renderFailed = !v.modelRenderCache.render(v, context);
  416. // Update dirty flag/related
  417. v.opaqueDirty = renderFailed;
  418. failedCount += renderFailed ? 1 : 0;
  419. }
  420. });
  421. // =======================================================================
  422. // Third pass, transparent primitive rendering
  423. // Enable Alpha Testing, Disable Depth Write
  424. engine.setAlphaTesting(true);
  425. engine.setDepthWrite(false);
  426. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  427. if (this._renderableData._transparentListChanged) {
  428. this._updateTransparentData();
  429. }
  430. // From this point on we have up to date data to render, so let's go
  431. failedCount += this._renderTransparentData();
  432. // =======================================================================
  433. // Unbind target/restore viewport setting, clear dirty flag, and quit
  434. // The group's content is no longer dirty
  435. this._cacheGroupDirty = failedCount !== 0;
  436. if (this.isCachedGroup) {
  437. this._unbindCacheTarget();
  438. }
  439. else {
  440. if (curVP) {
  441. engine.setViewport(curVP);
  442. }
  443. }
  444. // Restore saved states
  445. engine.setAlphaTesting(curAlphaTest);
  446. engine.setDepthWrite(curDepthWrite);
  447. }
  448. };
  449. Group2D.prototype._setCacheGroupDirty = function () {
  450. this._cacheGroupDirty = true;
  451. };
  452. Group2D.prototype._updateTransparentData = function () {
  453. this.owner._addUpdateTransparentDataCount(1);
  454. var rd = this._renderableData;
  455. // Sort all the primitive from their depth, max (bottom) to min (top)
  456. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  457. var checkAndAddPrimInSegment = function (seg, tpiI) {
  458. var tpi = rd._transparentPrimitives[tpiI];
  459. // Fast rejection: if gii are different
  460. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  461. return false;
  462. }
  463. //let tpiZ = tpi._primitive.actualZOffset;
  464. // We've made it so far, the tpi can be part of the segment, add it
  465. tpi._transparentSegment = seg;
  466. tpi._primitive._updateTransparentSegmentIndices(seg);
  467. return true;
  468. };
  469. // Free the existing TransparentSegments
  470. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  471. var ts = _a[_i];
  472. ts.dispose(this.owner.engine);
  473. }
  474. rd._transparentSegments.splice(0);
  475. var prevSeg = null;
  476. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  477. var tpi = rd._transparentPrimitives[tpiI];
  478. // Check if the Data in which the primitive is stored is not sorted properly
  479. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  480. tpi._groupInstanceInfo.sortTransparentData();
  481. }
  482. // Reset the segment, we have to create/rebuild it
  483. tpi._transparentSegment = null;
  484. // If there's a previous valid segment, check if this prim can be part of it
  485. if (prevSeg) {
  486. checkAndAddPrimInSegment(prevSeg, tpiI);
  487. }
  488. // If we couldn't insert in the adjacent segments, he have to create one
  489. if (!tpi._transparentSegment) {
  490. var ts = new BABYLON.TransparentSegment();
  491. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  492. var prim = tpi._primitive;
  493. ts.startZ = prim.actualZOffset;
  494. prim._updateTransparentSegmentIndices(ts);
  495. ts.endZ = ts.startZ;
  496. tpi._transparentSegment = ts;
  497. rd._transparentSegments.push(ts);
  498. }
  499. // Update prevSeg
  500. prevSeg = tpi._transparentSegment;
  501. }
  502. //rd._firstChangedPrim = null;
  503. rd._transparentListChanged = false;
  504. };
  505. Group2D.prototype._renderTransparentData = function () {
  506. var failedCount = 0;
  507. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  508. var rd = this._renderableData;
  509. var useInstanced = this.owner.supportInstancedArray;
  510. var length = rd._transparentSegments.length;
  511. for (var i = 0; i < length; i++) {
  512. context.instancedBuffers = null;
  513. var ts = rd._transparentSegments[i];
  514. var gii = ts.groupInsanceInfo;
  515. var mrc = gii.modelRenderCache;
  516. var engine = this.owner.engine;
  517. var count = ts.endDataIndex - ts.startDataIndex;
  518. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  519. // We don't want to create an Instanced Buffer for less that 5 prims
  520. if (useInstanced && count >= 5) {
  521. if (!ts.partBuffers) {
  522. var buffers = new Array();
  523. for (var j = 0; j < gii.transparentData.length; j++) {
  524. var gitd = gii.transparentData[j];
  525. var dfa = gitd._partData;
  526. var data = dfa.pack();
  527. var stride = dfa.stride;
  528. var neededSize = count * stride * 4;
  529. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  530. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  531. engine.updateArrayBuffer(segData);
  532. buffers.push(buffer);
  533. }
  534. ts.partBuffers = buffers;
  535. }
  536. else if (gii.transparentDirty) {
  537. for (var j = 0; j < gii.transparentData.length; j++) {
  538. var gitd = gii.transparentData[j];
  539. var dfa = gitd._partData;
  540. var data = dfa.pack();
  541. var stride = dfa.stride;
  542. var buffer = ts.partBuffers[j];
  543. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  544. engine.bindArrayBuffer(buffer);
  545. engine.updateArrayBuffer(segData);
  546. }
  547. }
  548. context.useInstancing = true;
  549. context.instancesCount = count;
  550. context.instancedBuffers = ts.partBuffers;
  551. context.groupInfoPartData = gii.transparentData;
  552. var renderFailed = !mrc.render(gii, context);
  553. failedCount += renderFailed ? 1 : 0;
  554. }
  555. else {
  556. context.useInstancing = false;
  557. context.partDataStartIndex = ts.startDataIndex;
  558. context.partDataEndIndex = ts.endDataIndex;
  559. context.groupInfoPartData = gii.transparentData;
  560. var renderFailed = !mrc.render(gii, context);
  561. failedCount += renderFailed ? 1 : 0;
  562. }
  563. }
  564. return failedCount;
  565. };
  566. Group2D.prototype._prepareContext = function (engine, context, gii) {
  567. var gipd = null;
  568. var setDirty;
  569. var getDirty;
  570. // Render Mode specifics
  571. switch (context.renderMode) {
  572. case BABYLON.Render2DContext.RenderModeOpaque:
  573. {
  574. if (!gii.hasOpaqueData) {
  575. return null;
  576. }
  577. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  578. getDirty = function () { return gii.opaqueDirty; };
  579. context.groupInfoPartData = gii.opaqueData;
  580. gipd = gii.opaqueData;
  581. break;
  582. }
  583. case BABYLON.Render2DContext.RenderModeAlphaTest:
  584. {
  585. if (!gii.hasAlphaTestData) {
  586. return null;
  587. }
  588. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  589. getDirty = function () { return gii.alphaTestDirty; };
  590. context.groupInfoPartData = gii.alphaTestData;
  591. gipd = gii.alphaTestData;
  592. break;
  593. }
  594. default:
  595. throw new Error("_prepareContext is only for opaque or alphaTest");
  596. }
  597. var renderCount = 0;
  598. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  599. // Skip it if instanced arrays are not supported
  600. if (this.owner.supportInstancedArray) {
  601. // Flag for instancing
  602. context.useInstancing = true;
  603. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  604. for (var i = 0; i < gipd.length; i++) {
  605. var pid = gipd[i];
  606. // If the instances of the model was changed, pack the data
  607. var array = pid._partData;
  608. var instanceData_1 = array.pack();
  609. renderCount += array.usedElementCount;
  610. // Compute the size the instance buffer should have
  611. var neededSize = array.usedElementCount * array.stride * 4;
  612. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  613. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  614. if (pid._partBuffer) {
  615. engine.deleteInstancesBuffer(pid._partBuffer);
  616. }
  617. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  618. pid._partBufferSize = neededSize;
  619. setDirty(false);
  620. // Update the WebGL buffer to match the new content of the instances data
  621. engine.updateArrayBuffer(instanceData_1);
  622. }
  623. else if (getDirty()) {
  624. // Update the WebGL buffer to match the new content of the instances data
  625. engine.bindArrayBuffer(pid._partBuffer);
  626. engine.updateArrayBuffer(instanceData_1);
  627. }
  628. }
  629. setDirty(false);
  630. }
  631. else {
  632. context.partDataStartIndex = 0;
  633. // Find the first valid object to get the count
  634. if (context.groupInfoPartData.length > 0) {
  635. var i = 0;
  636. while (!context.groupInfoPartData[i]) {
  637. i++;
  638. }
  639. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  640. }
  641. }
  642. return renderCount;
  643. };
  644. Group2D.prototype._setRenderingScale = function (scale) {
  645. if (this._renderableData._renderingScale === scale) {
  646. return;
  647. }
  648. this._renderableData._renderingScale = scale;
  649. };
  650. Group2D.prototype._bindCacheTarget = function () {
  651. var curWidth;
  652. var curHeight;
  653. var rd = this._renderableData;
  654. var rs = rd._renderingScale;
  655. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  656. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  657. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  658. if (rd._cacheNode) {
  659. var size = rd._cacheNode.contentSize;
  660. // Check if we have to deallocate because the size is too small
  661. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  662. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  663. // For World space: no over-provisioning
  664. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  665. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  666. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  667. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  668. rd._cacheTexture.freeRect(rd._cacheNode);
  669. rd._cacheNode = null;
  670. }
  671. }
  672. if (!rd._cacheNode) {
  673. // Check if we have to allocate a rendering zone in the global cache texture
  674. var res = this.owner._allocateGroupCache(this, this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  675. rd._cacheNode = res.node;
  676. rd._cacheTexture = res.texture;
  677. rd._cacheRenderSprite = res.sprite;
  678. sizeChanged = true;
  679. }
  680. if (sizeChanged) {
  681. rd._cacheSize.copyFrom(Group2D._s);
  682. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  683. this.scale = this._renderableData._renderingScale;
  684. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  685. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  686. }
  687. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  688. }
  689. var n = rd._cacheNode;
  690. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  691. };
  692. Group2D.prototype._unbindCacheTarget = function () {
  693. if (this._renderableData._cacheTexture) {
  694. this._renderableData._cacheTexture.unbindTexture();
  695. }
  696. };
  697. Group2D.prototype.handleGroupChanged = function (prop) {
  698. // This method is only for cachedGroup
  699. var rd = this._renderableData;
  700. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  701. return;
  702. }
  703. // For now we only support these property changes
  704. // TODO: add more! :)
  705. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  706. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  707. }
  708. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  709. rd._cacheRenderSprite.rotation = this.rotation;
  710. }
  711. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  712. rd._cacheRenderSprite.scale = this.scale;
  713. }
  714. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  715. rd._cacheRenderSprite.origin = this.origin.clone();
  716. }
  717. else if (prop.id === Group2D.actualSizeProperty.id) {
  718. rd._cacheRenderSprite.size = this.actualSize.clone();
  719. }
  720. };
  721. Group2D.prototype.detectGroupStates = function () {
  722. var isCanvas = this instanceof BABYLON.Canvas2D;
  723. var canvasStrat = this.owner.cachingStrategy;
  724. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  725. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  726. this._isRenderableGroup = isCanvas;
  727. this._isCachedGroup = false;
  728. }
  729. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  730. if (isCanvas) {
  731. this._isRenderableGroup = true;
  732. this._isCachedGroup = true;
  733. }
  734. else {
  735. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  736. this._isCachedGroup = false;
  737. }
  738. }
  739. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  740. if (isCanvas) {
  741. this._isRenderableGroup = true;
  742. this._isCachedGroup = false;
  743. }
  744. else {
  745. if (this.hierarchyDepth === 1) {
  746. this._isRenderableGroup = true;
  747. this._isCachedGroup = true;
  748. }
  749. else {
  750. this._isRenderableGroup = false;
  751. this._isCachedGroup = false;
  752. }
  753. }
  754. }
  755. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  756. var gcb = this.cacheBehavior;
  757. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  758. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  759. this._isCachedGroup = false;
  760. }
  761. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  762. this._isRenderableGroup = true;
  763. this._isCachedGroup = true;
  764. }
  765. }
  766. if (this._isRenderableGroup) {
  767. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  768. if (!this._renderableData) {
  769. this._renderableData = new RenderableGroupData();
  770. }
  771. }
  772. // If the group is tagged as renderable we add it to the renderable tree
  773. if (this._isCachedGroup) {
  774. var cur = this.parent;
  775. while (cur) {
  776. if (cur instanceof Group2D && cur._isRenderableGroup) {
  777. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  778. cur._renderableData._childrenRenderableGroups.push(this);
  779. }
  780. break;
  781. }
  782. cur = cur.parent;
  783. }
  784. }
  785. };
  786. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  787. /**
  788. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  789. */
  790. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  791. /**
  792. * When used, this group's content won't be cached, no matter which strategy used.
  793. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  794. */
  795. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  796. /**
  797. * When used, the group's content will be cached in the nearest cached parent group/canvas
  798. */
  799. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  800. Group2D._s = BABYLON.Size.Zero();
  801. __decorate([
  802. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  803. ], Group2D.prototype, "size", null);
  804. __decorate([
  805. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  806. ], Group2D.prototype, "actualSize", null);
  807. Group2D = __decorate([
  808. BABYLON.className("Group2D")
  809. ], Group2D);
  810. return Group2D;
  811. })(BABYLON.Prim2DBase);
  812. BABYLON.Group2D = Group2D;
  813. var RenderableGroupData = (function () {
  814. function RenderableGroupData() {
  815. this._primDirtyList = new Array();
  816. this._childrenRenderableGroups = new Array();
  817. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  818. this._transparentPrimitives = new Array();
  819. this._transparentSegments = new Array();
  820. this._transparentListChanged = false;
  821. this._cacheNode = null;
  822. this._cacheTexture = null;
  823. this._cacheRenderSprite = null;
  824. this._renderingScale = 1;
  825. this._cacheNodeUVs = null;
  826. this._cacheNodeUVsChangedObservable = null;
  827. this._cacheSize = BABYLON.Size.Zero();
  828. this._useMipMap = false;
  829. this._anisotropicLevel = 1;
  830. }
  831. RenderableGroupData.prototype.dispose = function (engine) {
  832. if (this._cacheRenderSprite) {
  833. this._cacheRenderSprite.dispose();
  834. this._cacheRenderSprite = null;
  835. }
  836. if (this._cacheTexture && this._cacheNode) {
  837. this._cacheTexture.freeRect(this._cacheNode);
  838. this._cacheTexture = null;
  839. this._cacheNode = null;
  840. }
  841. if (this._primDirtyList) {
  842. this._primDirtyList.splice(0);
  843. this._primDirtyList = null;
  844. }
  845. if (this._renderGroupInstancesInfo) {
  846. this._renderGroupInstancesInfo.forEach(function (k, v) {
  847. v.dispose();
  848. });
  849. this._renderGroupInstancesInfo = null;
  850. }
  851. if (this._cacheNodeUVsChangedObservable) {
  852. this._cacheNodeUVsChangedObservable.clear();
  853. this._cacheNodeUVsChangedObservable = null;
  854. }
  855. if (this._transparentSegments) {
  856. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  857. var ts = _a[_i];
  858. ts.dispose(engine);
  859. }
  860. this._transparentSegments.splice(0);
  861. this._transparentSegments = null;
  862. }
  863. };
  864. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  865. var tpi = new TransparentPrimitiveInfo();
  866. tpi._primitive = prim;
  867. tpi._groupInstanceInfo = gii;
  868. tpi._transparentSegment = null;
  869. this._transparentPrimitives.push(tpi);
  870. this._transparentListChanged = true;
  871. return tpi;
  872. };
  873. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  874. var index = this._transparentPrimitives.indexOf(tpi);
  875. if (index !== -1) {
  876. this._transparentPrimitives.splice(index, 1);
  877. this._transparentListChanged = true;
  878. }
  879. };
  880. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  881. this._transparentListChanged = true;
  882. //this.updateSmallestZChangedPrim(tpi);
  883. };
  884. return RenderableGroupData;
  885. })();
  886. BABYLON.RenderableGroupData = RenderableGroupData;
  887. var TransparentPrimitiveInfo = (function () {
  888. function TransparentPrimitiveInfo() {
  889. }
  890. return TransparentPrimitiveInfo;
  891. })();
  892. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  893. })(BABYLON || (BABYLON = {}));