babylon.canvas2d.js 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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.width * 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. BABYLON.Prim2DBase._isCanvasInit = false;
  78. if (!settings) {
  79. settings = {};
  80. }
  81. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  82. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  83. this._background.zOrder = 1.0;
  84. this._background.isPickable = false;
  85. this._background.origin = BABYLON.Vector2.Zero();
  86. this._background.levelVisible = false;
  87. if (settings.backgroundRoundRadius != null) {
  88. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  89. }
  90. if (settings.backgroundBorder != null) {
  91. if (typeof (settings.backgroundBorder) === "string") {
  92. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  93. }
  94. else {
  95. this.backgroundBorder = settings.backgroundBorder;
  96. }
  97. }
  98. if (settings.backgroundBorderThickNess != null) {
  99. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  100. }
  101. if (settings.backgroundFill != null) {
  102. if (typeof (settings.backgroundFill) === "string") {
  103. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  104. }
  105. else {
  106. this.backgroundFill = settings.backgroundFill;
  107. }
  108. }
  109. this._background._patchHierarchy(this);
  110. }
  111. var engine = scene.getEngine();
  112. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  113. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  114. this._capturedPointers = new BABYLON.StringDictionary();
  115. this._pickStartingPosition = BABYLON.Vector2.Zero();
  116. this._hierarchyLevelMaxSiblingCount = 50;
  117. this._hierarchyDepthOffset = 0;
  118. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  119. this._scene = scene;
  120. this._engine = engine;
  121. this._renderingSize = new BABYLON.Size(0, 0);
  122. this._trackedGroups = new Array();
  123. this._maxAdaptiveWorldSpaceCanvasSize = null;
  124. this._groupCacheMaps = new BABYLON.StringDictionary();
  125. this._patchHierarchy(this);
  126. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  127. this._fitRenderingDevice = !settings.size;
  128. if (!settings.size) {
  129. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  130. }
  131. // Register scene dispose to also dispose the canvas when it'll happens
  132. scene.onDisposeObservable.add(function (d, s) {
  133. _this.dispose();
  134. });
  135. if (this._isScreenSpace) {
  136. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  137. _this._engine.clear(null, false, true);
  138. _this._render();
  139. });
  140. }
  141. else {
  142. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  143. _this._render();
  144. });
  145. }
  146. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  147. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  148. this._setupInteraction(enableInteraction);
  149. }
  150. Canvas2D.prototype._canvasPreInit = function (settings) {
  151. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  152. this._cachingStrategy = cachingStrategy;
  153. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  154. };
  155. Canvas2D.prototype._setupInteraction = function (enable) {
  156. var _this = this;
  157. // No change detection
  158. if (enable === this._interactionEnabled) {
  159. return;
  160. }
  161. // Set the new state
  162. this._interactionEnabled = enable;
  163. // ScreenSpace mode
  164. if (this._isScreenSpace) {
  165. // Disable interaction
  166. if (!enable) {
  167. if (this._scenePrePointerObserver) {
  168. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  169. this._scenePrePointerObserver = null;
  170. }
  171. return;
  172. }
  173. // Enable Interaction
  174. // Register the observable
  175. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  176. var hs = 1 / _this.engine.getHardwareScalingLevel();
  177. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  178. _this._handlePointerEventForInteraction(e, localPos, s);
  179. });
  180. }
  181. else {
  182. var scene = this.scene;
  183. if (enable) {
  184. scene.constantlyUpdateMeshUnderPointer = true;
  185. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  186. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  187. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  188. _this._handlePointerEventForInteraction(e, localPos, s);
  189. }
  190. });
  191. }
  192. else {
  193. if (this._scenePointerObserver) {
  194. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  195. this._scenePointerObserver = null;
  196. }
  197. }
  198. }
  199. };
  200. /**
  201. * Internal method, you should use the Prim2DBase version instead
  202. */
  203. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  204. if (this.isPointerCaptured(pointerId)) {
  205. return false;
  206. }
  207. // Try to capture the pointer on the HTML side
  208. try {
  209. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  210. }
  211. catch (e) {
  212. }
  213. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  214. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  215. this._capturedPointers.add(pointerId.toString(), primitive);
  216. return true;
  217. };
  218. /**
  219. * Internal method, you should use the Prim2DBase version instead
  220. */
  221. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  222. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  223. return false;
  224. }
  225. // Try to release the pointer on the HTML side
  226. try {
  227. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  228. }
  229. catch (e) {
  230. }
  231. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  232. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  233. this._capturedPointers.remove(pointerId.toString());
  234. return true;
  235. };
  236. /**
  237. * Determine if the given pointer is captured or not
  238. * @param pointerId the Id of the pointer
  239. * @return true if it's captured, false otherwise
  240. */
  241. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  242. return this._capturedPointers.contains(pointerId.toString());
  243. };
  244. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  245. // Avoid unnecessary lookup
  246. if (this._capturedPointers.count === 0) {
  247. return null;
  248. }
  249. return this._capturedPointers.get(pointerId.toString());
  250. };
  251. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  252. // Dispose check
  253. if (this.isDisposed) {
  254. return;
  255. }
  256. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  257. this._updatePointerInfo(eventData, localPosition);
  258. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  259. // 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.
  260. // 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.
  261. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  262. // 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
  263. this._updateOverStatus();
  264. // Check if we have nothing to raise
  265. if (!this._actualOverPrimitive && !capturedPrim) {
  266. return;
  267. }
  268. // Update the relatedTarget info with the over primitive or the captured one (if any)
  269. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  270. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  271. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  272. // Analyze the pointer event type and fire proper events on the primitive
  273. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  274. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  275. }
  276. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  277. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  278. }
  279. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  280. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  281. }
  282. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  283. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  284. }
  285. };
  286. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  287. var pii = this._primPointerInfo;
  288. if (!pii.canvasPointerPos) {
  289. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  290. }
  291. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  292. var engine = this._scene.getEngine();
  293. if (this._isScreenSpace) {
  294. var cameraViewport = camera.viewport;
  295. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  296. // Moving coordinates to local viewport world
  297. var x = localPosition.x - viewport.x;
  298. var y = localPosition.y - viewport.y;
  299. pii.canvasPointerPos.x = x - this.actualPosition.x;
  300. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  301. }
  302. else {
  303. pii.canvasPointerPos.x = localPosition.x;
  304. pii.canvasPointerPos.y = localPosition.y;
  305. }
  306. pii.mouseWheelDelta = 0;
  307. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  308. var event = eventData.event;
  309. if (event.wheelDelta) {
  310. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  311. }
  312. else if (event.detail) {
  313. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  314. }
  315. }
  316. else {
  317. var pe = eventData.event;
  318. pii.ctrlKey = pe.ctrlKey;
  319. pii.altKey = pe.altKey;
  320. pii.shiftKey = pe.shiftKey;
  321. pii.metaKey = pe.metaKey;
  322. pii.button = pe.button;
  323. pii.buttons = pe.buttons;
  324. pii.pointerId = pe.pointerId;
  325. pii.width = pe.width;
  326. pii.height = pe.height;
  327. pii.presssure = pe.pressure;
  328. pii.tilt.x = pe.tiltX;
  329. pii.tilt.y = pe.tiltY;
  330. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  331. }
  332. };
  333. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  334. if (this.scene.getRenderId() === this._intersectionRenderId) {
  335. return;
  336. }
  337. // 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
  338. if (!this._globalTransform) {
  339. this.updateCachedStates(true);
  340. }
  341. var ii = Canvas2D._interInfo;
  342. ii.pickPosition.x = mouseLocalPos.x;
  343. ii.pickPosition.y = mouseLocalPos.y;
  344. ii.findFirstOnly = false;
  345. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  346. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  347. this._previousIntersectionList = this._actualIntersectionList;
  348. this._actualIntersectionList = null;
  349. this._previousOverPrimitive = this._actualOverPrimitive;
  350. this._actualOverPrimitive = null;
  351. return;
  352. }
  353. this.intersect(ii);
  354. this._previousIntersectionList = this._actualIntersectionList;
  355. this._actualIntersectionList = ii.intersectedPrimitives;
  356. this._previousOverPrimitive = this._actualOverPrimitive;
  357. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  358. this._intersectionRenderId = this.scene.getRenderId();
  359. };
  360. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  361. Canvas2D.prototype._updateOverStatus = function () {
  362. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  363. return;
  364. }
  365. // Detect a change of over
  366. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  367. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  368. if (prevPrim !== actualPrim) {
  369. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  370. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  371. // Notify the previous "over" prim that the pointer is no longer over it
  372. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  373. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  374. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  375. }
  376. // Notify the new "over" prim that the pointer is over it
  377. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  378. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  379. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  380. }
  381. }
  382. this._hoverStatusRenderId = this.scene.getRenderId();
  383. };
  384. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  385. if (this._primPointerInfo.isCaptured) {
  386. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  387. }
  388. else {
  389. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  390. var pii = _a[_i];
  391. if (pii.prim === prim) {
  392. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  393. return;
  394. }
  395. }
  396. }
  397. };
  398. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  399. if (!this._notifDebugMode) {
  400. return;
  401. }
  402. var debug = "";
  403. for (var i = 0; i < prim.hierarchyDepth; i++) {
  404. debug += " ";
  405. }
  406. var pii = this._primPointerInfo;
  407. 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();
  408. console.log(debug);
  409. };
  410. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  411. var ppi = this._primPointerInfo;
  412. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  413. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  414. this._notifParents(prim, mask);
  415. }
  416. var bubbleCancelled = false;
  417. var cur = prim;
  418. while (cur) {
  419. // Only trigger the observers if the primitive is intersected (except for out)
  420. if (!bubbleCancelled) {
  421. this._updatePrimPointerPos(cur);
  422. // Exec the observers
  423. this._debugExecObserver(cur, mask);
  424. cur._pointerEventObservable.notifyObservers(ppi, mask);
  425. this._triggerActionManager(cur, ppi, mask, eventData);
  426. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  427. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  428. if (ppi.cancelBubble) {
  429. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  430. return;
  431. }
  432. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  433. bubbleCancelled = true;
  434. }
  435. }
  436. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  437. if (bubbleCancelled) {
  438. this._updatePrimPointerPos(cur);
  439. }
  440. // Trigger a PointerEnter corresponding to the PointerOver
  441. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  442. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  443. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  444. }
  445. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  446. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  447. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  448. }
  449. // Loop to the parent
  450. cur = cur.parent;
  451. }
  452. };
  453. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  454. var _this = this;
  455. // 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
  456. if (!this._globalTransform) {
  457. this.updateCachedStates(true);
  458. }
  459. // Process Trigger related to PointerDown
  460. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  461. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  462. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  463. this._pickStartingTime = new Date().getTime();
  464. this._pickedDownPrim = null;
  465. if (prim.actionManager) {
  466. this._pickedDownPrim = prim;
  467. if (prim.actionManager.hasPickTriggers) {
  468. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  469. switch (eventData.button) {
  470. case 0:
  471. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  472. break;
  473. case 1:
  474. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  475. break;
  476. case 2:
  477. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  478. break;
  479. }
  480. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  481. }
  482. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  483. window.setTimeout(function () {
  484. var ppi = _this._primPointerInfo;
  485. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  486. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  487. var ii = new BABYLON.IntersectInfo2D();
  488. ii.pickPosition = ppi.canvasPointerPos.clone();
  489. ii.findFirstOnly = false;
  490. _this.intersect(ii);
  491. if (ii.isPrimIntersected(prim) !== null) {
  492. if (prim.actionManager) {
  493. 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)) {
  494. _this._pickStartingTime = 0;
  495. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  496. }
  497. }
  498. }
  499. }, BABYLON.ActionManager.LongPressDelay);
  500. }
  501. }
  502. }
  503. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  504. this._pickStartingTime = 0;
  505. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  506. if (prim.actionManager) {
  507. // OnPickUpTrigger
  508. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  509. // OnPickTrigger
  510. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  511. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  512. }
  513. }
  514. // OnPickOutTrigger
  515. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  516. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  517. }
  518. }
  519. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  520. if (prim.actionManager) {
  521. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  522. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  523. }
  524. }
  525. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  526. if (prim.actionManager) {
  527. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  528. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  529. }
  530. }
  531. };
  532. Canvas2D.prototype._notifParents = function (prim, mask) {
  533. var pii = this._primPointerInfo;
  534. var curPrim = this;
  535. while (curPrim) {
  536. this._updatePrimPointerPos(curPrim);
  537. // Fire the proper notification
  538. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  539. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  540. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  541. }
  542. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  543. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  544. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  545. }
  546. curPrim = curPrim.parent;
  547. }
  548. };
  549. /**
  550. * Don't forget to call the dispose method when you're done with the Canvas instance.
  551. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  552. */
  553. Canvas2D.prototype.dispose = function () {
  554. if (!_super.prototype.dispose.call(this)) {
  555. return false;
  556. }
  557. if (this.interactionEnabled) {
  558. this._setupInteraction(false);
  559. }
  560. if (this._beforeRenderObserver) {
  561. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  562. this._beforeRenderObserver = null;
  563. }
  564. if (this._afterRenderObserver) {
  565. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  566. this._afterRenderObserver = null;
  567. }
  568. if (this._groupCacheMaps) {
  569. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  570. this._groupCacheMaps = null;
  571. }
  572. };
  573. Object.defineProperty(Canvas2D.prototype, "scene", {
  574. /**
  575. * Accessor to the Scene that owns the Canvas
  576. * @returns The instance of the Scene object
  577. */
  578. get: function () {
  579. return this._scene;
  580. },
  581. enumerable: true,
  582. configurable: true
  583. });
  584. Object.defineProperty(Canvas2D.prototype, "engine", {
  585. /**
  586. * Accessor to the Engine that drives the Scene used by this Canvas
  587. * @returns The instance of the Engine object
  588. */
  589. get: function () {
  590. return this._engine;
  591. },
  592. enumerable: true,
  593. configurable: true
  594. });
  595. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  596. /**
  597. * Accessor of the Caching Strategy used by this Canvas.
  598. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  599. * @returns the value corresponding to the used strategy.
  600. */
  601. get: function () {
  602. return this._cachingStrategy;
  603. },
  604. enumerable: true,
  605. configurable: true
  606. });
  607. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  608. /**
  609. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  610. * @returns {}
  611. */
  612. get: function () {
  613. return this._isScreenSpace;
  614. },
  615. enumerable: true,
  616. configurable: true
  617. });
  618. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  619. /**
  620. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  621. */
  622. get: function () {
  623. return this._worldSpaceNode;
  624. },
  625. set: function (val) {
  626. this._worldSpaceNode = val;
  627. },
  628. enumerable: true,
  629. configurable: true
  630. });
  631. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  632. /**
  633. * Check if the WebGL Instanced Array extension is supported or not
  634. */
  635. get: function () {
  636. return this._supprtInstancedArray;
  637. },
  638. enumerable: true,
  639. configurable: true
  640. });
  641. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  642. /**
  643. * Property that defines the fill object used to draw the background of the Canvas.
  644. * Note that Canvas with a Caching Strategy of
  645. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  646. */
  647. get: function () {
  648. if (!this._background || !this._background.isVisible) {
  649. return null;
  650. }
  651. return this._background.fill;
  652. },
  653. set: function (value) {
  654. this.checkBackgroundAvailability();
  655. if (value === this._background.fill) {
  656. return;
  657. }
  658. this._background.fill = value;
  659. this._background.levelVisible = true;
  660. },
  661. enumerable: true,
  662. configurable: true
  663. });
  664. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  665. /**
  666. * Property that defines the border object used to draw the background of the Canvas.
  667. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  668. */
  669. get: function () {
  670. if (!this._background || !this._background.isVisible) {
  671. return null;
  672. }
  673. return this._background.border;
  674. },
  675. set: function (value) {
  676. this.checkBackgroundAvailability();
  677. if (value === this._background.border) {
  678. return;
  679. }
  680. this._background.border = value;
  681. this._background.levelVisible = true;
  682. },
  683. enumerable: true,
  684. configurable: true
  685. });
  686. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  687. /**
  688. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  689. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  690. */
  691. get: function () {
  692. if (!this._background || !this._background.isVisible) {
  693. return null;
  694. }
  695. return this._background.borderThickness;
  696. },
  697. set: function (value) {
  698. this.checkBackgroundAvailability();
  699. if (value === this._background.borderThickness) {
  700. return;
  701. }
  702. this._background.borderThickness = value;
  703. },
  704. enumerable: true,
  705. configurable: true
  706. });
  707. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  708. /**
  709. * You can set the roundRadius of the background
  710. * @returns The current roundRadius
  711. */
  712. get: function () {
  713. if (!this._background || !this._background.isVisible) {
  714. return null;
  715. }
  716. return this._background.roundRadius;
  717. },
  718. set: function (value) {
  719. this.checkBackgroundAvailability();
  720. if (value === this._background.roundRadius) {
  721. return;
  722. }
  723. this._background.roundRadius = value;
  724. this._background.levelVisible = true;
  725. },
  726. enumerable: true,
  727. configurable: true
  728. });
  729. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  730. /**
  731. * Enable/Disable interaction for this Canvas
  732. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  733. */
  734. get: function () {
  735. return this._interactionEnabled;
  736. },
  737. set: function (enable) {
  738. this._setupInteraction(enable);
  739. },
  740. enumerable: true,
  741. configurable: true
  742. });
  743. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  744. /**
  745. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  746. * @returns {}
  747. */
  748. get: function () {
  749. return this.__engineData;
  750. },
  751. enumerable: true,
  752. configurable: true
  753. });
  754. Canvas2D.prototype.checkBackgroundAvailability = function () {
  755. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  756. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  757. }
  758. };
  759. Canvas2D.prototype.onPrimBecomesDirty = function () {
  760. this._addPrimToDirtyList(this);
  761. };
  762. Canvas2D.prototype._updateTrackedNodes = function () {
  763. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  764. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  765. var rh = this.engine.getRenderHeight();
  766. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  767. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  768. var group = _a[_i];
  769. if (group.isDisposed || !group.isVisible) {
  770. continue;
  771. }
  772. var node = group.trackedNode;
  773. var worldMtx = node.getWorldMatrix();
  774. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  775. group.x = Math.round(proj.x);
  776. group.y = Math.round(rh - proj.y);
  777. }
  778. };
  779. /**
  780. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  781. */
  782. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  783. this._updateCanvasState(forceRecompute);
  784. };
  785. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  786. if (this._globalTransformStep < 2) {
  787. return;
  788. }
  789. var n = this.worldSpaceCanvasNode;
  790. var bi = n.getBoundingInfo().boundingBox;
  791. var v = bi.vectorsWorld;
  792. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  793. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  794. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  795. var projPoints = new Array(4);
  796. for (var i = 0; i < 4; i++) {
  797. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  798. }
  799. var left = projPoints[3].subtract(projPoints[0]).length();
  800. var top = projPoints[3].subtract(projPoints[1]).length();
  801. var right = projPoints[1].subtract(projPoints[2]).length();
  802. var bottom = projPoints[2].subtract(projPoints[0]).length();
  803. var w = Math.round(Math.max(top, bottom));
  804. var h = Math.round(Math.max(right, left));
  805. var isW = w > h;
  806. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  807. var edge = Math.max(w, h);
  808. if (edge < 256) {
  809. edge = 256;
  810. }
  811. else {
  812. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  813. }
  814. // Clip values if needed
  815. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  816. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  817. if (newScale !== this.scale) {
  818. var scale = newScale;
  819. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  820. this._setRenderingScale(scale);
  821. }
  822. };
  823. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  824. // Check if the update has already been made for this render Frame
  825. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  826. return;
  827. }
  828. // Detect a change of rendering size
  829. var renderingSizeChanged = false;
  830. var newWidth = this.engine.getRenderWidth();
  831. if (newWidth !== this._renderingSize.width) {
  832. renderingSizeChanged = true;
  833. }
  834. this._renderingSize.width = newWidth;
  835. var newHeight = this.engine.getRenderHeight();
  836. if (newHeight !== this._renderingSize.height) {
  837. renderingSizeChanged = true;
  838. }
  839. this._renderingSize.height = newHeight;
  840. // If the canvas fit the rendering size and it changed, update
  841. if (renderingSizeChanged && this._fitRenderingDevice) {
  842. this.size = this._renderingSize;
  843. if (this._background) {
  844. this._background.size = this.size;
  845. }
  846. // Dirty the Layout at the Canvas level to recompute as the size changed
  847. this._setLayoutDirty();
  848. }
  849. var context = new BABYLON.PrepareRender2DContext();
  850. ++this._globalTransformProcessStep;
  851. this.updateCachedStates(false);
  852. this._prepareGroupRender(context);
  853. this._updateRenderId = this.scene.getRenderId();
  854. };
  855. /**
  856. * Method that renders the Canvas, you should not invoke
  857. */
  858. Canvas2D.prototype._render = function () {
  859. this._updateTrackedNodes();
  860. this._updateCanvasState(false);
  861. if (!this._isScreenSpace) {
  862. this._updateAdaptiveSizeWorldCanvas();
  863. }
  864. this._updateCanvasState(false);
  865. if (this._primPointerInfo.canvasPointerPos) {
  866. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  867. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  868. }
  869. this.engine.setState(false);
  870. this._groupRender();
  871. if (!this._isScreenSpace) {
  872. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  873. this.worldSpaceCacheChanged();
  874. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  875. }
  876. }
  877. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  878. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  879. this._cachedCanvasGroup._renderCachedCanvas();
  880. }
  881. };
  882. /**
  883. * Internal method that allocate a cache for the given group.
  884. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  885. * @param group The group to allocate the cache of.
  886. * @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.
  887. */
  888. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  889. if (useMipMap === void 0) { useMipMap = false; }
  890. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  891. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  892. // Determine size
  893. var size = group.actualSize;
  894. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  895. if (minSize) {
  896. size.width = Math.max(minSize.width, size.width);
  897. size.height = Math.max(minSize.height, size.height);
  898. }
  899. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  900. // Try to find a spot in one of the cached texture
  901. var res = null;
  902. var map;
  903. for (var _i = 0; _i < mapArray.length; _i++) {
  904. var _map = mapArray[_i];
  905. map = _map;
  906. var node = map.allocateRect(size);
  907. if (node) {
  908. res = { node: node, texture: map };
  909. break;
  910. }
  911. }
  912. // Couldn't find a map that could fit the rect, create a new map for it
  913. if (!res) {
  914. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  915. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  916. if (size.width > mapSize.width || size.height > mapSize.height) {
  917. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  918. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  919. }
  920. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  921. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  922. map.anisotropicFilteringLevel = 4;
  923. mapArray.splice(0, 0, map);
  924. var node = map.allocateRect(size);
  925. res = { node: node, texture: map };
  926. }
  927. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  928. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  929. if (group !== this || this._isScreenSpace) {
  930. var node = res.node;
  931. // 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
  932. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  933. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  934. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  935. sprite.zOrder = 1;
  936. sprite.origin = BABYLON.Vector2.Zero();
  937. }
  938. else {
  939. 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 });
  940. sprite.origin = group.origin.clone();
  941. res.sprite = sprite;
  942. }
  943. }
  944. return res;
  945. };
  946. /**
  947. * Internal method used to register a Scene Node to track position for the given group
  948. * Do not invoke this method, for internal purpose only.
  949. * @param group the group to track its associated Scene Node
  950. */
  951. Canvas2D.prototype._registerTrackedNode = function (group) {
  952. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  953. return;
  954. }
  955. this._trackedGroups.push(group);
  956. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  957. };
  958. /**
  959. * Internal method used to unregister a tracked Scene Node
  960. * Do not invoke this method, it's for internal purpose only.
  961. * @param group the group to unregister its tracked Scene Node from.
  962. */
  963. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  964. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  965. return;
  966. }
  967. var i = this._trackedGroups.indexOf(group);
  968. if (i !== -1) {
  969. this._trackedGroups.splice(i, 1);
  970. }
  971. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  972. };
  973. /**
  974. * Get a Solid Color Brush instance matching the given color.
  975. * @param color The color to retrieve
  976. * @return A shared instance of the SolidColorBrush2D class that use the given color
  977. */
  978. Canvas2D.GetSolidColorBrush = function (color) {
  979. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  980. };
  981. /**
  982. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  983. * @param color The color to retrieve
  984. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  985. */
  986. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  987. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  988. };
  989. /**
  990. * Get a Gradient Color Brush
  991. * @param color1 starting color
  992. * @param color2 engine color
  993. * @param translation translation vector to apply. default is [0;0]
  994. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  995. * @param scale scaling factor to apply. default is 1.
  996. */
  997. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  998. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  999. if (rotation === void 0) { rotation = 0; }
  1000. if (scale === void 0) { scale = 1; }
  1001. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  1002. };
  1003. /**
  1004. * Create a solid or gradient brush from a string value.
  1005. * @param brushString should be either
  1006. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  1007. * - "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.
  1008. */
  1009. Canvas2D.GetBrushFromString = function (brushString) {
  1010. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  1011. brushString = brushString.trim();
  1012. var split = brushString.split(",");
  1013. // Solid, formatted as: "[solid:]#FF808080"
  1014. if (split.length === 1) {
  1015. var value = null;
  1016. if (brushString.indexOf("solid:") === 0) {
  1017. value = brushString.substr(6).trim();
  1018. }
  1019. else if (brushString.indexOf("#") === 0) {
  1020. value = brushString;
  1021. }
  1022. else {
  1023. return null;
  1024. }
  1025. return Canvas2D.GetSolidColorBrushFromHex(value);
  1026. }
  1027. else {
  1028. if (split[0].indexOf("gradient:") === 0) {
  1029. split[0] = split[0].substr(9).trim();
  1030. }
  1031. try {
  1032. var start = BABYLON.Color4.FromHexString(split[0].trim());
  1033. var end = BABYLON.Color4.FromHexString(split[1].trim());
  1034. var t = BABYLON.Vector2.Zero();
  1035. if (split.length > 2) {
  1036. var v = split[2].trim();
  1037. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  1038. return null;
  1039. }
  1040. var sep = v.indexOf(":");
  1041. var x = parseFloat(v.substr(1, sep));
  1042. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  1043. t = new BABYLON.Vector2(x, y);
  1044. }
  1045. var r = 0;
  1046. if (split.length > 3) {
  1047. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  1048. }
  1049. var s = 1;
  1050. if (split.length > 4) {
  1051. s = parseFloat(split[4].trim());
  1052. }
  1053. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  1054. }
  1055. catch (e) {
  1056. return null;
  1057. }
  1058. }
  1059. };
  1060. /**
  1061. * 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.
  1062. * This strategy doesn't allow primitives added directly as children of the Canvas.
  1063. * 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.
  1064. */
  1065. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  1066. /**
  1067. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  1068. * 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.
  1069. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  1070. * 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.
  1071. */
  1072. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  1073. /**
  1074. * 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).
  1075. */
  1076. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  1077. /**
  1078. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  1079. * 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).
  1080. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  1081. */
  1082. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  1083. Canvas2D.hierarchyLevelMaxSiblingCount = 50;
  1084. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  1085. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  1086. Canvas2D._m = BABYLON.Matrix.Identity();
  1087. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  1088. /**
  1089. * Define the default size used for both the width and height of a MapTexture to allocate.
  1090. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  1091. */
  1092. Canvas2D._groupTextureCacheSize = 1024;
  1093. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  1094. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  1095. Canvas2D = __decorate([
  1096. BABYLON.className("Canvas2D")
  1097. ], Canvas2D);
  1098. return Canvas2D;
  1099. })(BABYLON.Group2D);
  1100. BABYLON.Canvas2D = Canvas2D;
  1101. var WorldSpaceCanvas2D = (function (_super) {
  1102. __extends(WorldSpaceCanvas2D, _super);
  1103. /**
  1104. * 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.
  1105. * 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.
  1106. * @param scene the Scene that owns the Canvas
  1107. * @param size the dimension of the Canvas in World Space
  1108. * @param settings a combination of settings, possible ones are
  1109. * - children: an array of direct children primitives
  1110. * - id: a text identifier, for information purpose only, default is null.
  1111. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  1112. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  1113. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  1114. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  1115. * - 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).
  1116. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  1117. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  1118. * - 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.
  1119. * - 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.
  1120. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  1121. * - 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.
  1122. * - 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.
  1123. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1124. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1125. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1126. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1127. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  1128. */
  1129. function WorldSpaceCanvas2D(scene, size, settings) {
  1130. BABYLON.Prim2DBase._isCanvasInit = true;
  1131. var s = settings;
  1132. s.isScreenSpace = false;
  1133. s.size = size.clone();
  1134. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  1135. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  1136. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  1137. }
  1138. _super.call(this, scene, settings);
  1139. BABYLON.Prim2DBase._isCanvasInit = false;
  1140. this._renderableData._useMipMap = true;
  1141. this._renderableData._anisotropicLevel = 8;
  1142. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  1143. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  1144. //}
  1145. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  1146. var id = settings ? settings.id || null : null;
  1147. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  1148. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  1149. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  1150. if (settings.maxAdaptiveCanvasSize == null) {
  1151. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  1152. }
  1153. else {
  1154. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  1155. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  1156. }
  1157. if (createWorldSpaceNode) {
  1158. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  1159. var vertexData = BABYLON.VertexData.CreatePlane({
  1160. width: size.width,
  1161. height: size.height,
  1162. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  1163. });
  1164. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  1165. this.applyCachedTexture(vertexData, mtl);
  1166. vertexData.applyToMesh(plane, true);
  1167. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  1168. mtl.disableLighting = true;
  1169. mtl.useAlphaFromDiffuseTexture = true;
  1170. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  1171. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  1172. plane.material = mtl;
  1173. this._worldSpaceNode = plane;
  1174. }
  1175. else {
  1176. this._worldSpaceNode = settings.customWorldSpaceNode;
  1177. this.applyCachedTexture(null, null);
  1178. }
  1179. }
  1180. WorldSpaceCanvas2D = __decorate([
  1181. BABYLON.className("WorldSpaceCanvas2D")
  1182. ], WorldSpaceCanvas2D);
  1183. return WorldSpaceCanvas2D;
  1184. })(Canvas2D);
  1185. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  1186. var ScreenSpaceCanvas2D = (function (_super) {
  1187. __extends(ScreenSpaceCanvas2D, _super);
  1188. /**
  1189. * 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.
  1190. * 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.
  1191. * All caching strategies will be available.
  1192. * 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]
  1193. * @param scene the Scene that owns the Canvas
  1194. * @param settings a combination of settings, possible ones are
  1195. * - children: an array of direct children primitives
  1196. * - id: a text identifier, for information purpose only
  1197. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  1198. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  1199. * - 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]
  1200. * - width: the width of the Canvas. you can alternatively use the size setting.
  1201. * - height: the height of the Canvas. you can alternatively use the size setting.
  1202. * - 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
  1203. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  1204. * - 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.
  1205. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  1206. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  1207. * - 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.
  1208. * - 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.
  1209. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  1210. * - 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.
  1211. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1212. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1213. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1214. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1215. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  1216. */
  1217. function ScreenSpaceCanvas2D(scene, settings) {
  1218. BABYLON.Prim2DBase._isCanvasInit = true;
  1219. _super.call(this, scene, settings);
  1220. }
  1221. ScreenSpaceCanvas2D = __decorate([
  1222. BABYLON.className("ScreenSpaceCanvas2D")
  1223. ], ScreenSpaceCanvas2D);
  1224. return ScreenSpaceCanvas2D;
  1225. })(Canvas2D);
  1226. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  1227. })(BABYLON || (BABYLON = {}));