babylon.canvas2d.js 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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. // This class contains data that lifetime is bounding to the Babylon Engine object
  15. var Canvas2DEngineBoundData = (function () {
  16. function Canvas2DEngineBoundData() {
  17. this._modelCache = new BABYLON.StringDictionary();
  18. }
  19. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  20. return this._modelCache.getOrAddWithFactory(key, factory);
  21. };
  22. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  23. if (!modelRenderCache.isDisposed) {
  24. return false;
  25. }
  26. this._modelCache.remove(modelRenderCache.modelKey);
  27. return true;
  28. };
  29. return Canvas2DEngineBoundData;
  30. }());
  31. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  32. var Canvas2D = (function (_super) {
  33. __extends(Canvas2D, _super);
  34. function Canvas2D(scene, settings) {
  35. var _this = this;
  36. _super.call(this, settings);
  37. /**
  38. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  39. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  40. */
  41. this.worldSpaceToNodeLocal = function (worldPos) {
  42. var node = _this._worldSpaceNode;
  43. if (!node) {
  44. return;
  45. }
  46. var mtx = node.getWorldMatrix().clone();
  47. mtx.invert();
  48. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  49. var res = new BABYLON.Vector2(v.x, v.y);
  50. var size = _this.actualSize;
  51. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  52. res.y += size.height * 0.5;
  53. return res;
  54. };
  55. /**
  56. * If you use a custom WorldSpaceCanvasNode you have to override this property to update the UV of your object to reflect the changes due to a resizing of the cached bitmap
  57. */
  58. this.worldSpaceCacheChanged = function () {
  59. var plane = _this.worldSpaceCanvasNode;
  60. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  61. vd.uvs = new Float32Array(8);
  62. var material = plane.material;
  63. var tex = _this._renderableData._cacheTexture;
  64. if (material.diffuseTexture !== tex) {
  65. material.diffuseTexture = tex;
  66. tex.hasAlpha = true;
  67. }
  68. var nodeuv = _this._renderableData._cacheNodeUVs;
  69. for (var i = 0; i < 4; i++) {
  70. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  71. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  72. }
  73. vd.applyToMesh(plane);
  74. };
  75. this._notifDebugMode = false;
  76. this._mapCounter = 0;
  77. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  78. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  79. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  80. this._groupRenderCounter = new BABYLON.PerfCounter();
  81. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  82. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  83. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  84. this._updateLayoutCounter = new BABYLON.PerfCounter();
  85. this._updatePositioningCounter = new BABYLON.PerfCounter();
  86. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  87. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  88. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  89. this._profileInfoText = null;
  90. BABYLON.Prim2DBase._isCanvasInit = false;
  91. if (!settings) {
  92. settings = {};
  93. }
  94. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  95. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  96. this._background.zOrder = 1.0;
  97. this._background.isPickable = false;
  98. this._background.origin = BABYLON.Vector2.Zero();
  99. this._background.levelVisible = false;
  100. if (settings.backgroundRoundRadius != null) {
  101. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  102. }
  103. if (settings.backgroundBorder != null) {
  104. if (typeof (settings.backgroundBorder) === "string") {
  105. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  106. }
  107. else {
  108. this.backgroundBorder = settings.backgroundBorder;
  109. }
  110. }
  111. if (settings.backgroundBorderThickNess != null) {
  112. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  113. }
  114. if (settings.backgroundFill != null) {
  115. if (typeof (settings.backgroundFill) === "string") {
  116. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  117. }
  118. else {
  119. this.backgroundFill = settings.backgroundFill;
  120. }
  121. }
  122. this._background._patchHierarchy(this);
  123. }
  124. var engine = scene.getEngine();
  125. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  126. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  127. this._capturedPointers = new BABYLON.StringDictionary();
  128. this._pickStartingPosition = BABYLON.Vector2.Zero();
  129. this._hierarchyLevelMaxSiblingCount = 50;
  130. this._hierarchyDepth = 0;
  131. this._zOrder = 0;
  132. this._zMax = 1;
  133. this._scene = scene;
  134. this._engine = engine;
  135. this._renderingSize = new BABYLON.Size(0, 0);
  136. this._trackedGroups = new Array();
  137. this._maxAdaptiveWorldSpaceCanvasSize = null;
  138. this._groupCacheMaps = new BABYLON.StringDictionary();
  139. this._patchHierarchy(this);
  140. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  141. this._fitRenderingDevice = !settings.size;
  142. if (!settings.size) {
  143. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  144. }
  145. // Register scene dispose to also dispose the canvas when it'll happens
  146. scene.onDisposeObservable.add(function (d, s) {
  147. _this.dispose();
  148. });
  149. if (this._isScreenSpace) {
  150. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  151. _this._engine.clear(null, false, true, true);
  152. _this._render();
  153. });
  154. }
  155. else {
  156. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  157. _this._render();
  158. });
  159. }
  160. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  161. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  162. this._setupInteraction(enableInteraction);
  163. }
  164. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  165. get: function () {
  166. return this._drawCallsOpaqueCounter;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  172. get: function () {
  173. return this._drawCallsAlphaTestCounter;
  174. },
  175. enumerable: true,
  176. configurable: true
  177. });
  178. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  179. get: function () {
  180. return this._drawCallsTransparentCounter;
  181. },
  182. enumerable: true,
  183. configurable: true
  184. });
  185. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  186. get: function () {
  187. return this._groupRenderCounter;
  188. },
  189. enumerable: true,
  190. configurable: true
  191. });
  192. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  193. get: function () {
  194. return this._updateTransparentDataCounter;
  195. },
  196. enumerable: true,
  197. configurable: true
  198. });
  199. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  200. get: function () {
  201. return this._cachedGroupRenderCounter;
  202. },
  203. enumerable: true,
  204. configurable: true
  205. });
  206. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  207. get: function () {
  208. return this._updateCachedStateCounter;
  209. },
  210. enumerable: true,
  211. configurable: true
  212. });
  213. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  214. get: function () {
  215. return this._updateLayoutCounter;
  216. },
  217. enumerable: true,
  218. configurable: true
  219. });
  220. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  221. get: function () {
  222. return this._updatePositioningCounter;
  223. },
  224. enumerable: true,
  225. configurable: true
  226. });
  227. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  228. get: function () {
  229. return this._updateLocalTransformCounter;
  230. },
  231. enumerable: true,
  232. configurable: true
  233. });
  234. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  235. get: function () {
  236. return this._updateGlobalTransformCounter;
  237. },
  238. enumerable: true,
  239. configurable: true
  240. });
  241. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  242. get: function () {
  243. return this._boundingInfoRecomputeCounter;
  244. },
  245. enumerable: true,
  246. configurable: true
  247. });
  248. Canvas2D.prototype._canvasPreInit = function (settings) {
  249. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  250. this._cachingStrategy = cachingStrategy;
  251. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  252. };
  253. Canvas2D.prototype._setupInteraction = function (enable) {
  254. var _this = this;
  255. // No change detection
  256. if (enable === this._interactionEnabled) {
  257. return;
  258. }
  259. // Set the new state
  260. this._interactionEnabled = enable;
  261. // ScreenSpace mode
  262. if (this._isScreenSpace) {
  263. // Disable interaction
  264. if (!enable) {
  265. if (this._scenePrePointerObserver) {
  266. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  267. this._scenePrePointerObserver = null;
  268. }
  269. return;
  270. }
  271. // Enable Interaction
  272. // Register the observable
  273. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  274. if (_this.isVisible === false) {
  275. return;
  276. }
  277. var hs = 1 / _this.engine.getHardwareScalingLevel();
  278. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  279. _this._handlePointerEventForInteraction(e, localPos, s);
  280. });
  281. }
  282. else {
  283. var scene = this.scene;
  284. if (enable) {
  285. scene.constantlyUpdateMeshUnderPointer = true;
  286. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  287. if (_this.isVisible === false) {
  288. return;
  289. }
  290. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  291. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  292. _this._handlePointerEventForInteraction(e, localPos, s);
  293. }
  294. });
  295. }
  296. else {
  297. if (this._scenePointerObserver) {
  298. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  299. this._scenePointerObserver = null;
  300. }
  301. }
  302. }
  303. };
  304. /**
  305. * Internal method, you should use the Prim2DBase version instead
  306. */
  307. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  308. if (this.isPointerCaptured(pointerId)) {
  309. return false;
  310. }
  311. // Try to capture the pointer on the HTML side
  312. try {
  313. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  314. }
  315. catch (e) {
  316. }
  317. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  318. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  319. this._capturedPointers.add(pointerId.toString(), primitive);
  320. return true;
  321. };
  322. /**
  323. * Internal method, you should use the Prim2DBase version instead
  324. */
  325. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  326. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  327. return false;
  328. }
  329. // Try to release the pointer on the HTML side
  330. try {
  331. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  332. }
  333. catch (e) {
  334. }
  335. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  336. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  337. this._capturedPointers.remove(pointerId.toString());
  338. return true;
  339. };
  340. /**
  341. * Determine if the given pointer is captured or not
  342. * @param pointerId the Id of the pointer
  343. * @return true if it's captured, false otherwise
  344. */
  345. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  346. return this._capturedPointers.contains(pointerId.toString());
  347. };
  348. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  349. // Avoid unnecessary lookup
  350. if (this._capturedPointers.count === 0) {
  351. return null;
  352. }
  353. return this._capturedPointers.get(pointerId.toString());
  354. };
  355. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  356. // Dispose check
  357. if (this.isDisposed) {
  358. return;
  359. }
  360. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  361. this._updatePointerInfo(eventData, localPosition);
  362. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  363. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  364. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  365. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  366. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  367. this._updateOverStatus();
  368. // Check if we have nothing to raise
  369. if (!this._actualOverPrimitive && !capturedPrim) {
  370. return;
  371. }
  372. // Update the relatedTarget info with the over primitive or the captured one (if any)
  373. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  374. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  375. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  376. // Analyze the pointer event type and fire proper events on the primitive
  377. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  378. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  379. }
  380. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  381. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  382. }
  383. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  384. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  385. }
  386. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  387. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  388. }
  389. };
  390. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  391. var pii = this._primPointerInfo;
  392. if (!pii.canvasPointerPos) {
  393. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  394. }
  395. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  396. var engine = this._scene.getEngine();
  397. if (this._isScreenSpace) {
  398. var cameraViewport = camera.viewport;
  399. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  400. // Moving coordinates to local viewport world
  401. var x = localPosition.x - viewport.x;
  402. var y = localPosition.y - viewport.y;
  403. pii.canvasPointerPos.x = x - this.actualPosition.x;
  404. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  405. }
  406. else {
  407. pii.canvasPointerPos.x = localPosition.x;
  408. pii.canvasPointerPos.y = localPosition.y;
  409. }
  410. pii.mouseWheelDelta = 0;
  411. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  412. var event = eventData.event;
  413. if (event.wheelDelta) {
  414. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  415. }
  416. else if (event.detail) {
  417. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  418. }
  419. }
  420. else {
  421. var pe = eventData.event;
  422. pii.ctrlKey = pe.ctrlKey;
  423. pii.altKey = pe.altKey;
  424. pii.shiftKey = pe.shiftKey;
  425. pii.metaKey = pe.metaKey;
  426. pii.button = pe.button;
  427. pii.buttons = pe.buttons;
  428. pii.pointerId = pe.pointerId;
  429. pii.width = pe.width;
  430. pii.height = pe.height;
  431. pii.presssure = pe.pressure;
  432. pii.tilt.x = pe.tiltX;
  433. pii.tilt.y = pe.tiltY;
  434. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  435. }
  436. };
  437. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  438. if (this.scene.getRenderId() === this._intersectionRenderId) {
  439. return;
  440. }
  441. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  442. if (!this._globalTransform) {
  443. this.updateCachedStates(true);
  444. }
  445. var ii = Canvas2D._interInfo;
  446. ii.pickPosition.x = mouseLocalPos.x;
  447. ii.pickPosition.y = mouseLocalPos.y;
  448. ii.findFirstOnly = false;
  449. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  450. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  451. this._previousIntersectionList = this._actualIntersectionList;
  452. this._actualIntersectionList = null;
  453. this._previousOverPrimitive = this._actualOverPrimitive;
  454. this._actualOverPrimitive = null;
  455. return;
  456. }
  457. this.intersect(ii);
  458. this._previousIntersectionList = this._actualIntersectionList;
  459. this._actualIntersectionList = ii.intersectedPrimitives;
  460. this._previousOverPrimitive = this._actualOverPrimitive;
  461. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  462. this._intersectionRenderId = this.scene.getRenderId();
  463. };
  464. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  465. Canvas2D.prototype._updateOverStatus = function () {
  466. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  467. return;
  468. }
  469. // Detect a change of over
  470. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  471. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  472. if (prevPrim !== actualPrim) {
  473. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  474. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  475. // Notify the previous "over" prim that the pointer is no longer over it
  476. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  477. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  478. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  479. }
  480. // Notify the new "over" prim that the pointer is over it
  481. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  482. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  483. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  484. }
  485. }
  486. this._hoverStatusRenderId = this.scene.getRenderId();
  487. };
  488. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  489. if (this._primPointerInfo.isCaptured) {
  490. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  491. }
  492. else {
  493. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  494. var pii = _a[_i];
  495. if (pii.prim === prim) {
  496. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  497. return;
  498. }
  499. }
  500. }
  501. };
  502. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  503. if (!this._notifDebugMode) {
  504. return;
  505. }
  506. var debug = "";
  507. for (var i = 0; i < prim.hierarchyDepth; i++) {
  508. debug += " ";
  509. }
  510. var pii = this._primPointerInfo;
  511. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  512. console.log(debug);
  513. };
  514. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  515. var ppi = this._primPointerInfo;
  516. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  517. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  518. this._notifParents(prim, mask);
  519. }
  520. var bubbleCancelled = false;
  521. var cur = prim;
  522. while (cur) {
  523. // Only trigger the observers if the primitive is intersected (except for out)
  524. if (!bubbleCancelled) {
  525. this._updatePrimPointerPos(cur);
  526. // Exec the observers
  527. this._debugExecObserver(cur, mask);
  528. cur._pointerEventObservable.notifyObservers(ppi, mask);
  529. this._triggerActionManager(cur, ppi, mask, eventData);
  530. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  531. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  532. if (ppi.cancelBubble) {
  533. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  534. return;
  535. }
  536. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  537. bubbleCancelled = true;
  538. }
  539. }
  540. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  541. if (bubbleCancelled) {
  542. this._updatePrimPointerPos(cur);
  543. }
  544. // Trigger a PointerEnter corresponding to the PointerOver
  545. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  546. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  547. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  548. }
  549. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  550. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  551. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  552. }
  553. // Loop to the parent
  554. cur = cur.parent;
  555. }
  556. };
  557. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  558. var _this = this;
  559. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  560. if (!this._globalTransform) {
  561. this.updateCachedStates(true);
  562. }
  563. // Process Trigger related to PointerDown
  564. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  565. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  566. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  567. this._pickStartingTime = new Date().getTime();
  568. this._pickedDownPrim = null;
  569. if (prim.actionManager) {
  570. this._pickedDownPrim = prim;
  571. if (prim.actionManager.hasPickTriggers) {
  572. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  573. switch (eventData.button) {
  574. case 0:
  575. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  576. break;
  577. case 1:
  578. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  579. break;
  580. case 2:
  581. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  582. break;
  583. }
  584. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  585. }
  586. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  587. window.setTimeout(function () {
  588. var ppi = _this._primPointerInfo;
  589. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  590. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  591. var ii = new BABYLON.IntersectInfo2D();
  592. ii.pickPosition = ppi.canvasPointerPos.clone();
  593. ii.findFirstOnly = false;
  594. _this.intersect(ii);
  595. if (ii.isPrimIntersected(prim) !== null) {
  596. if (prim.actionManager) {
  597. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  598. _this._pickStartingTime = 0;
  599. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  600. }
  601. }
  602. }
  603. }, BABYLON.ActionManager.LongPressDelay);
  604. }
  605. }
  606. }
  607. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  608. this._pickStartingTime = 0;
  609. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  610. if (prim.actionManager) {
  611. // OnPickUpTrigger
  612. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  613. // OnPickTrigger
  614. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  615. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  616. }
  617. }
  618. // OnPickOutTrigger
  619. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  620. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  621. }
  622. }
  623. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  624. if (prim.actionManager) {
  625. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  626. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  627. }
  628. }
  629. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  630. if (prim.actionManager) {
  631. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  632. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  633. }
  634. }
  635. };
  636. Canvas2D.prototype._notifParents = function (prim, mask) {
  637. var pii = this._primPointerInfo;
  638. var curPrim = this;
  639. while (curPrim) {
  640. this._updatePrimPointerPos(curPrim);
  641. // Fire the proper notification
  642. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  643. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  644. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  645. }
  646. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  647. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  648. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  649. }
  650. curPrim = curPrim.parent;
  651. }
  652. };
  653. /**
  654. * Don't forget to call the dispose method when you're done with the Canvas instance.
  655. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  656. */
  657. Canvas2D.prototype.dispose = function () {
  658. if (!_super.prototype.dispose.call(this)) {
  659. return false;
  660. }
  661. if (this._profilingCanvas) {
  662. this._profilingCanvas.dispose();
  663. this._profilingCanvas = null;
  664. }
  665. if (this.interactionEnabled) {
  666. this._setupInteraction(false);
  667. }
  668. if (this._beforeRenderObserver) {
  669. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  670. this._beforeRenderObserver = null;
  671. }
  672. if (this._afterRenderObserver) {
  673. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  674. this._afterRenderObserver = null;
  675. }
  676. if (this._groupCacheMaps) {
  677. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  678. this._groupCacheMaps = null;
  679. }
  680. };
  681. Object.defineProperty(Canvas2D.prototype, "scene", {
  682. /**
  683. * Accessor to the Scene that owns the Canvas
  684. * @returns The instance of the Scene object
  685. */
  686. get: function () {
  687. return this._scene;
  688. },
  689. enumerable: true,
  690. configurable: true
  691. });
  692. Object.defineProperty(Canvas2D.prototype, "engine", {
  693. /**
  694. * Accessor to the Engine that drives the Scene used by this Canvas
  695. * @returns The instance of the Engine object
  696. */
  697. get: function () {
  698. return this._engine;
  699. },
  700. enumerable: true,
  701. configurable: true
  702. });
  703. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  704. /**
  705. * Accessor of the Caching Strategy used by this Canvas.
  706. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  707. * @returns the value corresponding to the used strategy.
  708. */
  709. get: function () {
  710. return this._cachingStrategy;
  711. },
  712. enumerable: true,
  713. configurable: true
  714. });
  715. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  716. /**
  717. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  718. * @returns {}
  719. */
  720. get: function () {
  721. return this._isScreenSpace;
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  727. /**
  728. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  729. */
  730. get: function () {
  731. return this._worldSpaceNode;
  732. },
  733. set: function (val) {
  734. this._worldSpaceNode = val;
  735. },
  736. enumerable: true,
  737. configurable: true
  738. });
  739. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  740. /**
  741. * Check if the WebGL Instanced Array extension is supported or not
  742. */
  743. get: function () {
  744. return this._supprtInstancedArray;
  745. },
  746. enumerable: true,
  747. configurable: true
  748. });
  749. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  750. /**
  751. * Property that defines the fill object used to draw the background of the Canvas.
  752. * Note that Canvas with a Caching Strategy of
  753. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  754. */
  755. get: function () {
  756. if (!this._background || !this._background.isVisible) {
  757. return null;
  758. }
  759. return this._background.fill;
  760. },
  761. set: function (value) {
  762. this.checkBackgroundAvailability();
  763. if (value === this._background.fill) {
  764. return;
  765. }
  766. this._background.fill = value;
  767. this._background.levelVisible = true;
  768. },
  769. enumerable: true,
  770. configurable: true
  771. });
  772. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  773. /**
  774. * Property that defines the border object used to draw the background of the Canvas.
  775. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  776. */
  777. get: function () {
  778. if (!this._background || !this._background.isVisible) {
  779. return null;
  780. }
  781. return this._background.border;
  782. },
  783. set: function (value) {
  784. this.checkBackgroundAvailability();
  785. if (value === this._background.border) {
  786. return;
  787. }
  788. this._background.border = value;
  789. this._background.levelVisible = true;
  790. },
  791. enumerable: true,
  792. configurable: true
  793. });
  794. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  795. /**
  796. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  797. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  798. */
  799. get: function () {
  800. if (!this._background || !this._background.isVisible) {
  801. return null;
  802. }
  803. return this._background.borderThickness;
  804. },
  805. set: function (value) {
  806. this.checkBackgroundAvailability();
  807. if (value === this._background.borderThickness) {
  808. return;
  809. }
  810. this._background.borderThickness = value;
  811. },
  812. enumerable: true,
  813. configurable: true
  814. });
  815. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  816. /**
  817. * You can set the roundRadius of the background
  818. * @returns The current roundRadius
  819. */
  820. get: function () {
  821. if (!this._background || !this._background.isVisible) {
  822. return null;
  823. }
  824. return this._background.roundRadius;
  825. },
  826. set: function (value) {
  827. this.checkBackgroundAvailability();
  828. if (value === this._background.roundRadius) {
  829. return;
  830. }
  831. this._background.roundRadius = value;
  832. this._background.levelVisible = true;
  833. },
  834. enumerable: true,
  835. configurable: true
  836. });
  837. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  838. /**
  839. * Enable/Disable interaction for this Canvas
  840. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  841. */
  842. get: function () {
  843. return this._interactionEnabled;
  844. },
  845. set: function (enable) {
  846. this._setupInteraction(enable);
  847. },
  848. enumerable: true,
  849. configurable: true
  850. });
  851. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  852. /**
  853. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  854. * @returns {}
  855. */
  856. get: function () {
  857. return this.__engineData;
  858. },
  859. enumerable: true,
  860. configurable: true
  861. });
  862. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  863. if (this._profilingCanvas) {
  864. return this._profilingCanvas;
  865. }
  866. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  867. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  868. new BABYLON.Rectangle2D({
  869. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  870. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  871. ]
  872. })
  873. ]
  874. });
  875. this._profileInfoText = canvas.findById("ProfileInfoText");
  876. this._profilingCanvas = canvas;
  877. return canvas;
  878. };
  879. Canvas2D.prototype.checkBackgroundAvailability = function () {
  880. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  881. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  882. }
  883. };
  884. Canvas2D.prototype._initPerfMetrics = function () {
  885. this._drawCallsOpaqueCounter.fetchNewFrame();
  886. this._drawCallsAlphaTestCounter.fetchNewFrame();
  887. this._drawCallsTransparentCounter.fetchNewFrame();
  888. this._groupRenderCounter.fetchNewFrame();
  889. this._updateTransparentDataCounter.fetchNewFrame();
  890. this._cachedGroupRenderCounter.fetchNewFrame();
  891. this._updateCachedStateCounter.fetchNewFrame();
  892. this._updateLayoutCounter.fetchNewFrame();
  893. this._updatePositioningCounter.fetchNewFrame();
  894. this._updateLocalTransformCounter.fetchNewFrame();
  895. this._updateGlobalTransformCounter.fetchNewFrame();
  896. this._boundingInfoRecomputeCounter.fetchNewFrame();
  897. };
  898. Canvas2D.prototype._fetchPerfMetrics = function () {
  899. this._drawCallsOpaqueCounter.addCount(0, true);
  900. this._drawCallsAlphaTestCounter.addCount(0, true);
  901. this._drawCallsTransparentCounter.addCount(0, true);
  902. this._groupRenderCounter.addCount(0, true);
  903. this._updateTransparentDataCounter.addCount(0, true);
  904. this._cachedGroupRenderCounter.addCount(0, true);
  905. this._updateCachedStateCounter.addCount(0, true);
  906. this._updateLayoutCounter.addCount(0, true);
  907. this._updatePositioningCounter.addCount(0, true);
  908. this._updateLocalTransformCounter.addCount(0, true);
  909. this._updateGlobalTransformCounter.addCount(0, true);
  910. this._boundingInfoRecomputeCounter.addCount(0, true);
  911. };
  912. Canvas2D.prototype._updateProfileCanvas = function () {
  913. if (this._profileInfoText == null) {
  914. return;
  915. }
  916. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  917. var p = "Draw Calls:\n" +
  918. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  919. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  920. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  921. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  922. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  923. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  924. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  925. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  926. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  927. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  928. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  929. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  930. this._profileInfoText.text = p;
  931. };
  932. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  933. switch (renderMode) {
  934. case BABYLON.Render2DContext.RenderModeOpaque:
  935. this._drawCallsOpaqueCounter.addCount(count, false);
  936. return;
  937. case BABYLON.Render2DContext.RenderModeAlphaTest:
  938. this._drawCallsAlphaTestCounter.addCount(count, false);
  939. return;
  940. case BABYLON.Render2DContext.RenderModeTransparent:
  941. this._drawCallsTransparentCounter.addCount(count, false);
  942. return;
  943. }
  944. };
  945. Canvas2D.prototype._addGroupRenderCount = function (count) {
  946. this._groupRenderCounter.addCount(count, false);
  947. };
  948. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  949. this._updateTransparentDataCounter.addCount(count, false);
  950. };
  951. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  952. this._cachedGroupRenderCounter.addCount(count, false);
  953. };
  954. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  955. this._updateCachedStateCounter.addCount(count, false);
  956. };
  957. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  958. this._updateLayoutCounter.addCount(count, false);
  959. };
  960. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  961. this._updatePositioningCounter.addCount(count, false);
  962. };
  963. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  964. this._updateLocalTransformCounter.addCount(count, false);
  965. };
  966. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  967. this._updateGlobalTransformCounter.addCount(count, false);
  968. };
  969. Canvas2D.prototype._updateTrackedNodes = function () {
  970. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  971. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  972. var rh = this.engine.getRenderHeight();
  973. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  974. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  975. var group = _a[_i];
  976. if (group.isDisposed || !group.isVisible) {
  977. continue;
  978. }
  979. var node = group.trackedNode;
  980. var worldMtx = node.getWorldMatrix();
  981. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  982. group.x = Math.round(proj.x);
  983. group.y = Math.round(rh - proj.y);
  984. }
  985. };
  986. /**
  987. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  988. */
  989. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  990. this._updateCanvasState(forceRecompute);
  991. };
  992. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  993. if (this._globalTransformStep < 2) {
  994. return;
  995. }
  996. var n = this.worldSpaceCanvasNode;
  997. var bi = n.getBoundingInfo().boundingBox;
  998. var v = bi.vectorsWorld;
  999. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  1000. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  1001. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  1002. var projPoints = new Array(4);
  1003. for (var i = 0; i < 4; i++) {
  1004. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  1005. }
  1006. var left = projPoints[3].subtract(projPoints[0]).length();
  1007. var top = projPoints[3].subtract(projPoints[1]).length();
  1008. var right = projPoints[1].subtract(projPoints[2]).length();
  1009. var bottom = projPoints[2].subtract(projPoints[0]).length();
  1010. var w = Math.round(Math.max(top, bottom));
  1011. var h = Math.round(Math.max(right, left));
  1012. var isW = w > h;
  1013. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  1014. var edge = Math.max(w, h);
  1015. if (edge < 256) {
  1016. edge = 256;
  1017. }
  1018. else {
  1019. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  1020. }
  1021. // Clip values if needed
  1022. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  1023. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  1024. if (newScale !== this.scale) {
  1025. var scale = newScale;
  1026. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  1027. this._setRenderingScale(scale);
  1028. }
  1029. };
  1030. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  1031. // Check if the update has already been made for this render Frame
  1032. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  1033. return;
  1034. }
  1035. // Detect a change of rendering size
  1036. var renderingSizeChanged = false;
  1037. var newWidth = this.engine.getRenderWidth();
  1038. if (newWidth !== this._renderingSize.width) {
  1039. renderingSizeChanged = true;
  1040. }
  1041. this._renderingSize.width = newWidth;
  1042. var newHeight = this.engine.getRenderHeight();
  1043. if (newHeight !== this._renderingSize.height) {
  1044. renderingSizeChanged = true;
  1045. }
  1046. this._renderingSize.height = newHeight;
  1047. // If the canvas fit the rendering size and it changed, update
  1048. if (renderingSizeChanged && this._fitRenderingDevice) {
  1049. this.size = this._renderingSize;
  1050. if (this._background) {
  1051. this._background.size = this.size;
  1052. }
  1053. // Dirty the Layout at the Canvas level to recompute as the size changed
  1054. this._setLayoutDirty();
  1055. }
  1056. var context = new BABYLON.PrepareRender2DContext();
  1057. ++this._globalTransformProcessStep;
  1058. this.updateCachedStates(false);
  1059. this._prepareGroupRender(context);
  1060. this._updateRenderId = this.scene.getRenderId();
  1061. };
  1062. /**
  1063. * Method that renders the Canvas, you should not invoke
  1064. */
  1065. Canvas2D.prototype._render = function () {
  1066. this._initPerfMetrics();
  1067. this._updateTrackedNodes();
  1068. this._updateCanvasState(false);
  1069. if (!this._isScreenSpace) {
  1070. this._updateAdaptiveSizeWorldCanvas();
  1071. }
  1072. this._updateCanvasState(false);
  1073. if (this._primPointerInfo.canvasPointerPos) {
  1074. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  1075. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  1076. }
  1077. this.engine.setState(false);
  1078. this._groupRender();
  1079. if (!this._isScreenSpace) {
  1080. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  1081. this.worldSpaceCacheChanged();
  1082. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  1083. }
  1084. }
  1085. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  1086. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  1087. this._cachedCanvasGroup._renderCachedCanvas();
  1088. }
  1089. this._fetchPerfMetrics();
  1090. this._updateProfileCanvas();
  1091. };
  1092. /**
  1093. * Internal method that allocate a cache for the given group.
  1094. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  1095. * @param group The group to allocate the cache of.
  1096. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  1097. */
  1098. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  1099. if (useMipMap === void 0) { useMipMap = false; }
  1100. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  1101. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  1102. // Determine size
  1103. var size = group.actualSize;
  1104. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  1105. if (minSize) {
  1106. size.width = Math.max(minSize.width, size.width);
  1107. size.height = Math.max(minSize.height, size.height);
  1108. }
  1109. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  1110. // Try to find a spot in one of the cached texture
  1111. var res = null;
  1112. var map;
  1113. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  1114. var _map = mapArray_1[_i];
  1115. map = _map;
  1116. var node = map.allocateRect(size);
  1117. if (node) {
  1118. res = { node: node, texture: map };
  1119. break;
  1120. }
  1121. }
  1122. // Couldn't find a map that could fit the rect, create a new map for it
  1123. if (!res) {
  1124. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  1125. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  1126. if (size.width > mapSize.width || size.height > mapSize.height) {
  1127. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  1128. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  1129. }
  1130. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  1131. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  1132. map.hasAlpha = true;
  1133. map.anisotropicFilteringLevel = 4;
  1134. mapArray.splice(0, 0, map);
  1135. var node = map.allocateRect(size);
  1136. res = { node: node, texture: map };
  1137. }
  1138. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  1139. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  1140. if (group !== this || this._isScreenSpace) {
  1141. var node = res.node;
  1142. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  1143. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  1144. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  1145. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  1146. sprite.zOrder = 1;
  1147. sprite.origin = BABYLON.Vector2.Zero();
  1148. }
  1149. else {
  1150. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  1151. sprite.origin = group.origin.clone();
  1152. res.sprite = sprite;
  1153. }
  1154. }
  1155. return res;
  1156. };
  1157. /**
  1158. * Internal method used to register a Scene Node to track position for the given group
  1159. * Do not invoke this method, for internal purpose only.
  1160. * @param group the group to track its associated Scene Node
  1161. */
  1162. Canvas2D.prototype._registerTrackedNode = function (group) {
  1163. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  1164. return;
  1165. }
  1166. this._trackedGroups.push(group);
  1167. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  1168. };
  1169. /**
  1170. * Internal method used to unregister a tracked Scene Node
  1171. * Do not invoke this method, it's for internal purpose only.
  1172. * @param group the group to unregister its tracked Scene Node from.
  1173. */
  1174. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  1175. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  1176. return;
  1177. }
  1178. var i = this._trackedGroups.indexOf(group);
  1179. if (i !== -1) {
  1180. this._trackedGroups.splice(i, 1);
  1181. }
  1182. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  1183. };
  1184. /**
  1185. * Get a Solid Color Brush instance matching the given color.
  1186. * @param color The color to retrieve
  1187. * @return A shared instance of the SolidColorBrush2D class that use the given color
  1188. */
  1189. Canvas2D.GetSolidColorBrush = function (color) {
  1190. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  1191. };
  1192. /**
  1193. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  1194. * @param color The color to retrieve
  1195. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  1196. */
  1197. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  1198. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  1199. };
  1200. /**
  1201. * Get a Gradient Color Brush
  1202. * @param color1 starting color
  1203. * @param color2 engine color
  1204. * @param translation translation vector to apply. default is [0;0]
  1205. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  1206. * @param scale scaling factor to apply. default is 1.
  1207. */
  1208. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  1209. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  1210. if (rotation === void 0) { rotation = 0; }
  1211. if (scale === void 0) { scale = 1; }
  1212. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  1213. };
  1214. /**
  1215. * Create a solid or gradient brush from a string value.
  1216. * @param brushString should be either
  1217. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  1218. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  1219. */
  1220. Canvas2D.GetBrushFromString = function (brushString) {
  1221. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  1222. brushString = brushString.trim();
  1223. var split = brushString.split(",");
  1224. // Solid, formatted as: "[solid:]#FF808080"
  1225. if (split.length === 1) {
  1226. var value = null;
  1227. if (brushString.indexOf("solid:") === 0) {
  1228. value = brushString.substr(6).trim();
  1229. }
  1230. else if (brushString.indexOf("#") === 0) {
  1231. value = brushString;
  1232. }
  1233. else {
  1234. return null;
  1235. }
  1236. return Canvas2D.GetSolidColorBrushFromHex(value);
  1237. }
  1238. else {
  1239. if (split[0].indexOf("gradient:") === 0) {
  1240. split[0] = split[0].substr(9).trim();
  1241. }
  1242. try {
  1243. var start = BABYLON.Color4.FromHexString(split[0].trim());
  1244. var end = BABYLON.Color4.FromHexString(split[1].trim());
  1245. var t = BABYLON.Vector2.Zero();
  1246. if (split.length > 2) {
  1247. var v = split[2].trim();
  1248. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  1249. return null;
  1250. }
  1251. var sep = v.indexOf(":");
  1252. var x = parseFloat(v.substr(1, sep));
  1253. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  1254. t = new BABYLON.Vector2(x, y);
  1255. }
  1256. var r = 0;
  1257. if (split.length > 3) {
  1258. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  1259. }
  1260. var s = 1;
  1261. if (split.length > 4) {
  1262. s = parseFloat(split[4].trim());
  1263. }
  1264. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  1265. }
  1266. catch (e) {
  1267. return null;
  1268. }
  1269. }
  1270. };
  1271. /**
  1272. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  1273. * This strategy doesn't allow primitives added directly as children of the Canvas.
  1274. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  1275. */
  1276. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  1277. /**
  1278. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  1279. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  1280. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  1281. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  1282. */
  1283. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  1284. /**
  1285. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  1286. */
  1287. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  1288. /**
  1289. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  1290. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  1291. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  1292. */
  1293. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  1294. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  1295. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  1296. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  1297. Canvas2D._m = BABYLON.Matrix.Identity();
  1298. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  1299. /**
  1300. * Define the default size used for both the width and height of a MapTexture to allocate.
  1301. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  1302. */
  1303. Canvas2D._groupTextureCacheSize = 1024;
  1304. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  1305. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  1306. Canvas2D = __decorate([
  1307. BABYLON.className("Canvas2D")
  1308. ], Canvas2D);
  1309. return Canvas2D;
  1310. }(BABYLON.Group2D));
  1311. BABYLON.Canvas2D = Canvas2D;
  1312. var WorldSpaceCanvas2D = (function (_super) {
  1313. __extends(WorldSpaceCanvas2D, _super);
  1314. /**
  1315. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  1316. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  1317. * @param scene the Scene that owns the Canvas
  1318. * @param size the dimension of the Canvas in World Space
  1319. * @param settings a combination of settings, possible ones are
  1320. * - children: an array of direct children primitives
  1321. * - id: a text identifier, for information purpose only, default is null.
  1322. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  1323. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  1324. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  1325. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  1326. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  1327. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  1328. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  1329. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1330. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1331. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  1332. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  1333. * - maxAdaptiveCanvasSize: set the max size (width and height) of the bitmap that will contain the cached version of the WorldSpace Canvas. Default is 1024 or less if it's not supported. In any case the value you give will be clipped by the maximum that WebGL supports on the running device. You can set any size, more than 1024 if you want, but testing proved it's a good max value for non "retina" like screens.
  1334. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1335. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1336. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1337. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1338. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  1339. */
  1340. function WorldSpaceCanvas2D(scene, size, settings) {
  1341. BABYLON.Prim2DBase._isCanvasInit = true;
  1342. var s = settings;
  1343. s.isScreenSpace = false;
  1344. s.size = size.clone();
  1345. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  1346. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  1347. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  1348. }
  1349. _super.call(this, scene, settings);
  1350. BABYLON.Prim2DBase._isCanvasInit = false;
  1351. this._renderableData._useMipMap = true;
  1352. this._renderableData._anisotropicLevel = 8;
  1353. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  1354. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  1355. //}
  1356. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  1357. var id = settings ? settings.id || null : null;
  1358. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  1359. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  1360. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  1361. if (settings.maxAdaptiveCanvasSize == null) {
  1362. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  1363. }
  1364. else {
  1365. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  1366. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  1367. }
  1368. if (createWorldSpaceNode) {
  1369. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  1370. var vertexData = BABYLON.VertexData.CreatePlane({
  1371. width: size.width,
  1372. height: size.height,
  1373. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  1374. });
  1375. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  1376. this.applyCachedTexture(vertexData, mtl);
  1377. vertexData.applyToMesh(plane, true);
  1378. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  1379. mtl.disableLighting = true;
  1380. mtl.useAlphaFromDiffuseTexture = true;
  1381. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  1382. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  1383. plane.material = mtl;
  1384. this._worldSpaceNode = plane;
  1385. }
  1386. else {
  1387. this._worldSpaceNode = settings.customWorldSpaceNode;
  1388. this.applyCachedTexture(null, null);
  1389. }
  1390. }
  1391. WorldSpaceCanvas2D = __decorate([
  1392. BABYLON.className("WorldSpaceCanvas2D")
  1393. ], WorldSpaceCanvas2D);
  1394. return WorldSpaceCanvas2D;
  1395. }(Canvas2D));
  1396. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  1397. var ScreenSpaceCanvas2D = (function (_super) {
  1398. __extends(ScreenSpaceCanvas2D, _super);
  1399. /**
  1400. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  1401. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  1402. * All caching strategies will be available.
  1403. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  1404. * @param scene the Scene that owns the Canvas
  1405. * @param settings a combination of settings, possible ones are
  1406. * - children: an array of direct children primitives
  1407. * - id: a text identifier, for information purpose only
  1408. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  1409. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  1410. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  1411. * - width: the width of the Canvas. you can alternatively use the size setting.
  1412. * - height: the height of the Canvas. you can alternatively use the size setting.
  1413. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  1414. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  1415. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  1416. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  1417. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  1418. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1419. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1420. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  1421. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  1422. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1423. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1424. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1425. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1426. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  1427. */
  1428. function ScreenSpaceCanvas2D(scene, settings) {
  1429. BABYLON.Prim2DBase._isCanvasInit = true;
  1430. _super.call(this, scene, settings);
  1431. }
  1432. ScreenSpaceCanvas2D = __decorate([
  1433. BABYLON.className("ScreenSpaceCanvas2D")
  1434. ], ScreenSpaceCanvas2D);
  1435. return ScreenSpaceCanvas2D;
  1436. }(Canvas2D));
  1437. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  1438. })(BABYLON || (BABYLON = {}));