advancedDynamicTexture.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. import { Nullable } from "babylonjs/types";
  2. import { Observable, Observer } from "babylonjs/Misc/observable";
  3. import { Vector2, Vector3, Matrix } from "babylonjs/Maths/math.vector";
  4. import { Tools } from "babylonjs/Misc/tools";
  5. import { PointerInfoPre, PointerInfo, PointerEventTypes } from 'babylonjs/Events/pointerEvents';
  6. import { ClipboardEventTypes, ClipboardInfo } from "babylonjs/Events/clipboardEvents";
  7. import { KeyboardInfoPre, KeyboardEventTypes } from "babylonjs/Events/keyboardEvents";
  8. import { Camera } from "babylonjs/Cameras/camera";
  9. import { StandardMaterial } from "babylonjs/Materials/standardMaterial";
  10. import { Texture } from "babylonjs/Materials/Textures/texture";
  11. import { DynamicTexture } from "babylonjs/Materials/Textures/dynamicTexture";
  12. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  13. import { Layer } from "babylonjs/Layers/layer";
  14. import { Engine } from "babylonjs/Engines/engine";
  15. import { Scene } from "babylonjs/scene";
  16. import { Container } from "./controls/container";
  17. import { Control } from "./controls/control";
  18. import { Style } from "./style";
  19. import { Measure } from "./measure";
  20. import { Constants } from 'babylonjs/Engines/constants';
  21. import { Viewport } from 'babylonjs/Maths/math.viewport';
  22. import { Color3 } from 'babylonjs/Maths/math.color';
  23. /**
  24. * Interface used to define a control that can receive focus
  25. */
  26. export interface IFocusableControl {
  27. /**
  28. * Function called when the control receives the focus
  29. */
  30. onFocus(): void;
  31. /**
  32. * Function called when the control loses the focus
  33. */
  34. onBlur(): void;
  35. /**
  36. * Function called to let the control handle keyboard events
  37. * @param evt defines the current keyboard event
  38. */
  39. processKeyboard(evt: KeyboardEvent): void;
  40. /**
  41. * Function called to get the list of controls that should not steal the focus from this control
  42. * @returns an array of controls
  43. */
  44. keepsFocusWith(): Nullable<Control[]>;
  45. }
  46. /**
  47. * Class used to create texture to support 2D GUI elements
  48. * @see https://doc.babylonjs.com/how_to/gui
  49. */
  50. export class AdvancedDynamicTexture extends DynamicTexture {
  51. private _isDirty = false;
  52. private _renderObserver: Nullable<Observer<Camera>>;
  53. private _resizeObserver: Nullable<Observer<Engine>>;
  54. private _preKeyboardObserver: Nullable<Observer<KeyboardInfoPre>>;
  55. private _pointerMoveObserver: Nullable<Observer<PointerInfoPre>>;
  56. private _pointerObserver: Nullable<Observer<PointerInfo>>;
  57. private _canvasPointerOutObserver: Nullable<Observer<PointerEvent>>;
  58. private _canvasBlurObserver: Nullable<Observer<Engine>>;
  59. private _background: string;
  60. /** @hidden */
  61. public _rootContainer = new Container("root");
  62. /** @hidden */
  63. public _lastPickedControl: Control;
  64. /** @hidden */
  65. public _lastControlOver: { [pointerId: number]: Control } = {};
  66. /** @hidden */
  67. public _lastControlDown: { [pointerId: number]: Control } = {};
  68. /** @hidden */
  69. public _capturingControl: { [pointerId: number]: Control } = {};
  70. /** @hidden */
  71. public _shouldBlockPointer: boolean;
  72. /** @hidden */
  73. public _layerToDispose: Nullable<Layer>;
  74. /** @hidden */
  75. public _linkedControls = new Array<Control>();
  76. private _isFullscreen = false;
  77. private _fullscreenViewport = new Viewport(0, 0, 1, 1);
  78. private _idealWidth = 0;
  79. private _idealHeight = 0;
  80. private _useSmallestIdeal: boolean = false;
  81. private _renderAtIdealSize = false;
  82. private _focusedControl: Nullable<IFocusableControl>;
  83. private _blockNextFocusCheck = false;
  84. private _renderScale = 1;
  85. private _rootElement: Nullable<HTMLElement>;
  86. private _cursorChanged = false;
  87. private _defaultMousePointerId = 0;
  88. /** @hidden */
  89. public _numLayoutCalls = 0;
  90. /** Gets the number of layout calls made the last time the ADT has been rendered */
  91. public get numLayoutCalls(): number {
  92. return this._numLayoutCalls;
  93. }
  94. /** @hidden */
  95. public _numRenderCalls = 0;
  96. /** Gets the number of render calls made the last time the ADT has been rendered */
  97. public get numRenderCalls(): number {
  98. return this._numRenderCalls;
  99. }
  100. /**
  101. * Define type to string to ensure compatibility across browsers
  102. * Safari doesn't support DataTransfer constructor
  103. */
  104. private _clipboardData: string = "";
  105. /**
  106. * Observable event triggered each time an clipboard event is received from the rendering canvas
  107. */
  108. public onClipboardObservable = new Observable<ClipboardInfo>();
  109. /**
  110. * Observable event triggered each time a pointer down is intercepted by a control
  111. */
  112. public onControlPickedObservable = new Observable<Control>();
  113. /**
  114. * Observable event triggered before layout is evaluated
  115. */
  116. public onBeginLayoutObservable = new Observable<AdvancedDynamicTexture>();
  117. /**
  118. * Observable event triggered after the layout was evaluated
  119. */
  120. public onEndLayoutObservable = new Observable<AdvancedDynamicTexture>();
  121. /**
  122. * Observable event triggered before the texture is rendered
  123. */
  124. public onBeginRenderObservable = new Observable<AdvancedDynamicTexture>();
  125. /**
  126. * Observable event triggered after the texture was rendered
  127. */
  128. public onEndRenderObservable = new Observable<AdvancedDynamicTexture>();
  129. /**
  130. * Gets or sets a boolean defining if alpha is stored as premultiplied
  131. */
  132. public premulAlpha = false;
  133. /**
  134. * Gets or sets a number used to scale rendering size (2 means that the texture will be twice bigger).
  135. * Useful when you want more antialiasing
  136. */
  137. public get renderScale(): number {
  138. return this._renderScale;
  139. }
  140. public set renderScale(value: number) {
  141. if (value === this._renderScale) {
  142. return;
  143. }
  144. this._renderScale = value;
  145. this._onResize();
  146. }
  147. /** Gets or sets the background color */
  148. public get background(): string {
  149. return this._background;
  150. }
  151. public set background(value: string) {
  152. if (this._background === value) {
  153. return;
  154. }
  155. this._background = value;
  156. this.markAsDirty();
  157. }
  158. /**
  159. * Gets or sets the ideal width used to design controls.
  160. * The GUI will then rescale everything accordingly
  161. * @see https://doc.babylonjs.com/how_to/gui#adaptive-scaling
  162. */
  163. public get idealWidth(): number {
  164. return this._idealWidth;
  165. }
  166. public set idealWidth(value: number) {
  167. if (this._idealWidth === value) {
  168. return;
  169. }
  170. this._idealWidth = value;
  171. this.markAsDirty();
  172. this._rootContainer._markAllAsDirty();
  173. }
  174. /**
  175. * Gets or sets the ideal height used to design controls.
  176. * The GUI will then rescale everything accordingly
  177. * @see https://doc.babylonjs.com/how_to/gui#adaptive-scaling
  178. */
  179. public get idealHeight(): number {
  180. return this._idealHeight;
  181. }
  182. public set idealHeight(value: number) {
  183. if (this._idealHeight === value) {
  184. return;
  185. }
  186. this._idealHeight = value;
  187. this.markAsDirty();
  188. this._rootContainer._markAllAsDirty();
  189. }
  190. /**
  191. * Gets or sets a boolean indicating if the smallest ideal value must be used if idealWidth and idealHeight are both set
  192. * @see https://doc.babylonjs.com/how_to/gui#adaptive-scaling
  193. */
  194. public get useSmallestIdeal(): boolean {
  195. return this._useSmallestIdeal;
  196. }
  197. public set useSmallestIdeal(value: boolean) {
  198. if (this._useSmallestIdeal === value) {
  199. return;
  200. }
  201. this._useSmallestIdeal = value;
  202. this.markAsDirty();
  203. this._rootContainer._markAllAsDirty();
  204. }
  205. /**
  206. * Gets or sets a boolean indicating if adaptive scaling must be used
  207. * @see https://doc.babylonjs.com/how_to/gui#adaptive-scaling
  208. */
  209. public get renderAtIdealSize(): boolean {
  210. return this._renderAtIdealSize;
  211. }
  212. public set renderAtIdealSize(value: boolean) {
  213. if (this._renderAtIdealSize === value) {
  214. return;
  215. }
  216. this._renderAtIdealSize = value;
  217. this._onResize();
  218. }
  219. /**
  220. * Gets the ratio used when in "ideal mode"
  221. * @see https://doc.babylonjs.com/how_to/gui#adaptive-scaling
  222. * */
  223. public get idealRatio(): number {
  224. var rwidth: number = 0;
  225. var rheight: number = 0;
  226. if (this._idealWidth) {
  227. rwidth = (this.getSize().width) / this._idealWidth;
  228. }
  229. if (this._idealHeight) {
  230. rheight = (this.getSize().height) / this._idealHeight;
  231. }
  232. if (this._useSmallestIdeal && this._idealWidth && this._idealHeight) {
  233. return window.innerWidth < window.innerHeight ? rwidth : rheight;
  234. }
  235. if (this._idealWidth) { // horizontal
  236. return rwidth;
  237. }
  238. if (this._idealHeight) { // vertical
  239. return rheight;
  240. }
  241. return 1;
  242. }
  243. /**
  244. * Gets the underlying layer used to render the texture when in fullscreen mode
  245. */
  246. public get layer(): Nullable<Layer> {
  247. return this._layerToDispose;
  248. }
  249. /**
  250. * Gets the root container control
  251. */
  252. public get rootContainer(): Container {
  253. return this._rootContainer;
  254. }
  255. /**
  256. * Returns an array containing the root container.
  257. * This is mostly used to let the Inspector introspects the ADT
  258. * @returns an array containing the rootContainer
  259. */
  260. public getChildren(): Array<Container> {
  261. return [this._rootContainer];
  262. }
  263. /**
  264. * Will return all controls that are inside this texture
  265. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  266. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  267. * @return all child controls
  268. */
  269. public getDescendants(directDescendantsOnly?: boolean, predicate?: (control: Control) => boolean): Control[] {
  270. return this._rootContainer.getDescendants(directDescendantsOnly, predicate);
  271. }
  272. /**
  273. * Gets or sets the current focused control
  274. */
  275. public get focusedControl(): Nullable<IFocusableControl> {
  276. return this._focusedControl;
  277. }
  278. public set focusedControl(control: Nullable<IFocusableControl>) {
  279. if (this._focusedControl == control) {
  280. return;
  281. }
  282. if (this._focusedControl) {
  283. this._focusedControl.onBlur();
  284. }
  285. if (control) {
  286. control.onFocus();
  287. }
  288. this._focusedControl = control;
  289. }
  290. /**
  291. * Gets or sets a boolean indicating if the texture must be rendered in background or foreground when in fullscreen mode
  292. */
  293. public get isForeground(): boolean {
  294. if (!this.layer) {
  295. return true;
  296. }
  297. return (!this.layer.isBackground);
  298. }
  299. public set isForeground(value: boolean) {
  300. if (!this.layer) {
  301. return;
  302. }
  303. if (this.layer.isBackground === !value) {
  304. return;
  305. }
  306. this.layer.isBackground = !value;
  307. }
  308. /**
  309. * Gets or set information about clipboardData
  310. */
  311. public get clipboardData(): string {
  312. return this._clipboardData;
  313. }
  314. public set clipboardData(value: string) {
  315. this._clipboardData = value;
  316. }
  317. /**
  318. * Creates a new AdvancedDynamicTexture
  319. * @param name defines the name of the texture
  320. * @param width defines the width of the texture
  321. * @param height defines the height of the texture
  322. * @param scene defines the hosting scene
  323. * @param generateMipMaps defines a boolean indicating if mipmaps must be generated (false by default)
  324. * @param samplingMode defines the texture sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  325. */
  326. constructor(name: string, width = 0, height = 0, scene: Nullable<Scene>, generateMipMaps = false, samplingMode = Texture.NEAREST_SAMPLINGMODE) {
  327. super(name, { width: width, height: height }, scene, generateMipMaps, samplingMode, Constants.TEXTUREFORMAT_RGBA);
  328. scene = this.getScene();
  329. if (!scene || !this._texture) {
  330. return;
  331. }
  332. this._rootElement = scene.getEngine()!.getInputElement()!;
  333. this._renderObserver = scene.onBeforeCameraRenderObservable.add((camera: Camera) => this._checkUpdate(camera));
  334. this._preKeyboardObserver = scene.onPreKeyboardObservable.add((info) => {
  335. if (!this._focusedControl) {
  336. return;
  337. }
  338. if (info.type === KeyboardEventTypes.KEYDOWN) {
  339. this._focusedControl.processKeyboard(info.event);
  340. }
  341. info.skipOnPointerObservable = true;
  342. });
  343. this._rootContainer._link(this);
  344. this.hasAlpha = true;
  345. if (!width || !height) {
  346. this._resizeObserver = scene.getEngine().onResizeObservable.add(() => this._onResize());
  347. this._onResize();
  348. }
  349. this._texture.isReady = true;
  350. }
  351. /**
  352. * Get the current class name of the texture useful for serialization or dynamic coding.
  353. * @returns "AdvancedDynamicTexture"
  354. */
  355. public getClassName(): string {
  356. return "AdvancedDynamicTexture";
  357. }
  358. /**
  359. * Function used to execute a function on all controls
  360. * @param func defines the function to execute
  361. * @param container defines the container where controls belong. If null the root container will be used
  362. */
  363. public executeOnAllControls(func: (control: Control) => void, container?: Container) {
  364. if (!container) {
  365. container = this._rootContainer;
  366. }
  367. func(container);
  368. for (var child of container.children) {
  369. if ((<any>child).children) {
  370. this.executeOnAllControls(func, (<Container>child));
  371. continue;
  372. }
  373. func(child);
  374. }
  375. }
  376. private _useInvalidateRectOptimization = true;
  377. /**
  378. * Gets or sets a boolean indicating if the InvalidateRect optimization should be turned on
  379. */
  380. public get useInvalidateRectOptimization(): boolean {
  381. return this._useInvalidateRectOptimization;
  382. }
  383. public set useInvalidateRectOptimization(value: boolean) {
  384. this._useInvalidateRectOptimization = value;
  385. }
  386. // Invalidated rectangle which is the combination of all invalidated controls after they have been rotated into absolute position
  387. private _invalidatedRectangle: Nullable<Measure> = null;
  388. /**
  389. * Invalidates a rectangle area on the gui texture
  390. * @param invalidMinX left most position of the rectangle to invalidate in the texture
  391. * @param invalidMinY top most position of the rectangle to invalidate in the texture
  392. * @param invalidMaxX right most position of the rectangle to invalidate in the texture
  393. * @param invalidMaxY bottom most position of the rectangle to invalidate in the texture
  394. */
  395. public invalidateRect(invalidMinX: number, invalidMinY: number, invalidMaxX: number, invalidMaxY: number) {
  396. if (!this._useInvalidateRectOptimization) {
  397. return;
  398. }
  399. if (!this._invalidatedRectangle) {
  400. this._invalidatedRectangle = new Measure(invalidMinX, invalidMinY, invalidMaxX - invalidMinX + 1, invalidMaxY - invalidMinY + 1);
  401. } else {
  402. // Compute intersection
  403. var maxX = Math.ceil(Math.max(this._invalidatedRectangle.left + this._invalidatedRectangle.width - 1, invalidMaxX));
  404. var maxY = Math.ceil(Math.max(this._invalidatedRectangle.top + this._invalidatedRectangle.height - 1, invalidMaxY));
  405. this._invalidatedRectangle.left = Math.floor(Math.min(this._invalidatedRectangle.left, invalidMinX));
  406. this._invalidatedRectangle.top = Math.floor(Math.min(this._invalidatedRectangle.top, invalidMinY));
  407. this._invalidatedRectangle.width = maxX - this._invalidatedRectangle.left + 1;
  408. this._invalidatedRectangle.height = maxY - this._invalidatedRectangle.top + 1;
  409. }
  410. }
  411. /**
  412. * Marks the texture as dirty forcing a complete update
  413. */
  414. public markAsDirty() {
  415. this._isDirty = true;
  416. }
  417. /**
  418. * Helper function used to create a new style
  419. * @returns a new style
  420. * @see https://doc.babylonjs.com/how_to/gui#styles
  421. */
  422. public createStyle(): Style {
  423. return new Style(this);
  424. }
  425. /**
  426. * Adds a new control to the root container
  427. * @param control defines the control to add
  428. * @returns the current texture
  429. */
  430. public addControl(control: Control): AdvancedDynamicTexture {
  431. this._rootContainer.addControl(control);
  432. return this;
  433. }
  434. /**
  435. * Removes a control from the root container
  436. * @param control defines the control to remove
  437. * @returns the current texture
  438. */
  439. public removeControl(control: Control): AdvancedDynamicTexture {
  440. this._rootContainer.removeControl(control);
  441. return this;
  442. }
  443. /**
  444. * Release all resources
  445. */
  446. public dispose(): void {
  447. let scene = this.getScene();
  448. if (!scene) {
  449. return;
  450. }
  451. this._rootElement = null;
  452. scene.onBeforeCameraRenderObservable.remove(this._renderObserver);
  453. if (this._resizeObserver) {
  454. scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  455. }
  456. if (this._pointerMoveObserver) {
  457. scene.onPrePointerObservable.remove(this._pointerMoveObserver);
  458. }
  459. if (this._pointerObserver) {
  460. scene.onPointerObservable.remove(this._pointerObserver);
  461. }
  462. if (this._preKeyboardObserver) {
  463. scene.onPreKeyboardObservable.remove(this._preKeyboardObserver);
  464. }
  465. if (this._canvasPointerOutObserver) {
  466. scene.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver);
  467. }
  468. if (this._canvasBlurObserver) {
  469. scene.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver);
  470. }
  471. if (this._layerToDispose) {
  472. this._layerToDispose.texture = null;
  473. this._layerToDispose.dispose();
  474. this._layerToDispose = null;
  475. }
  476. this._rootContainer.dispose();
  477. this.onClipboardObservable.clear();
  478. this.onControlPickedObservable.clear();
  479. this.onBeginRenderObservable.clear();
  480. this.onEndRenderObservable.clear();
  481. this.onBeginLayoutObservable.clear();
  482. this.onEndLayoutObservable.clear();
  483. super.dispose();
  484. }
  485. private _onResize(): void {
  486. let scene = this.getScene();
  487. if (!scene) {
  488. return;
  489. }
  490. // Check size
  491. var engine = scene.getEngine();
  492. var textureSize = this.getSize();
  493. var renderWidth = engine.getRenderWidth() * this._renderScale;
  494. var renderHeight = engine.getRenderHeight() * this._renderScale;
  495. if (this._renderAtIdealSize) {
  496. if (this._idealWidth) {
  497. renderHeight = (renderHeight * this._idealWidth) / renderWidth;
  498. renderWidth = this._idealWidth;
  499. } else if (this._idealHeight) {
  500. renderWidth = (renderWidth * this._idealHeight) / renderHeight;
  501. renderHeight = this._idealHeight;
  502. }
  503. }
  504. if (textureSize.width !== renderWidth || textureSize.height !== renderHeight) {
  505. this.scaleTo(renderWidth, renderHeight);
  506. this.markAsDirty();
  507. if (this._idealWidth || this._idealHeight) {
  508. this._rootContainer._markAllAsDirty();
  509. }
  510. }
  511. this.invalidateRect(0, 0, textureSize.width - 1, textureSize.height - 1);
  512. }
  513. /** @hidden */
  514. public _getGlobalViewport(scene: Scene): Viewport {
  515. var engine = scene.getEngine();
  516. return this._fullscreenViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  517. }
  518. /**
  519. * Get screen coordinates for a vector3
  520. * @param position defines the position to project
  521. * @param worldMatrix defines the world matrix to use
  522. * @returns the projected position
  523. */
  524. public getProjectedPosition(position: Vector3, worldMatrix: Matrix): Vector2 {
  525. var scene = this.getScene();
  526. if (!scene) {
  527. return Vector2.Zero();
  528. }
  529. var globalViewport = this._getGlobalViewport(scene);
  530. var projectedPosition = Vector3.Project(position, worldMatrix, scene.getTransformMatrix(), globalViewport);
  531. projectedPosition.scaleInPlace(this.renderScale);
  532. return new Vector2(projectedPosition.x, projectedPosition.y);
  533. }
  534. private _checkUpdate(camera: Camera): void {
  535. if (this._layerToDispose) {
  536. if ((camera.layerMask & this._layerToDispose.layerMask) === 0) {
  537. return;
  538. }
  539. }
  540. if (this._isFullscreen && this._linkedControls.length) {
  541. var scene = this.getScene();
  542. if (!scene) {
  543. return;
  544. }
  545. var globalViewport = this._getGlobalViewport(scene);
  546. for (let control of this._linkedControls) {
  547. if (!control.isVisible) {
  548. continue;
  549. }
  550. let mesh = control._linkedMesh;
  551. if (!mesh || mesh.isDisposed()) {
  552. Tools.SetImmediate(() => {
  553. control.linkWithMesh(null);
  554. });
  555. continue;
  556. }
  557. let position = mesh.getBoundingInfo ? mesh.getBoundingInfo().boundingSphere.center : (Vector3.ZeroReadOnly as Vector3);
  558. let projectedPosition = Vector3.Project(position, mesh.getWorldMatrix(), scene.getTransformMatrix(), globalViewport);
  559. if (projectedPosition.z < 0 || projectedPosition.z > 1) {
  560. control.notRenderable = true;
  561. continue;
  562. }
  563. control.notRenderable = false;
  564. // Account for RenderScale.
  565. projectedPosition.scaleInPlace(this.renderScale);
  566. control._moveToProjectedPosition(projectedPosition);
  567. }
  568. }
  569. if (!this._isDirty && !this._rootContainer.isDirty) {
  570. return;
  571. }
  572. this._isDirty = false;
  573. this._render();
  574. this.update(true, this.premulAlpha);
  575. }
  576. private _clearMeasure = new Measure(0, 0, 0, 0);
  577. private _render(): void {
  578. var textureSize = this.getSize();
  579. var renderWidth = textureSize.width;
  580. var renderHeight = textureSize.height;
  581. var context = this.getContext();
  582. context.font = "18px Arial";
  583. context.strokeStyle = "white";
  584. // Layout
  585. this.onBeginLayoutObservable.notifyObservers(this);
  586. var measure = new Measure(0, 0, renderWidth, renderHeight);
  587. this._numLayoutCalls = 0;
  588. this._rootContainer._layout(measure, context);
  589. this.onEndLayoutObservable.notifyObservers(this);
  590. this._isDirty = false; // Restoring the dirty state that could have been set by controls during layout processing
  591. // Clear
  592. if (this._invalidatedRectangle) {
  593. this._clearMeasure.copyFrom(this._invalidatedRectangle);
  594. } else {
  595. this._clearMeasure.copyFromFloats(0, 0, renderWidth, renderHeight);
  596. }
  597. context.clearRect(this._clearMeasure.left, this._clearMeasure.top, this._clearMeasure.width, this._clearMeasure.height);
  598. if (this._background) {
  599. context.save();
  600. context.fillStyle = this._background;
  601. context.fillRect(this._clearMeasure.left, this._clearMeasure.top, this._clearMeasure.width, this._clearMeasure.height);
  602. context.restore();
  603. }
  604. // Render
  605. this.onBeginRenderObservable.notifyObservers(this);
  606. this._numRenderCalls = 0;
  607. this._rootContainer._render(context, this._invalidatedRectangle);
  608. this.onEndRenderObservable.notifyObservers(this);
  609. this._invalidatedRectangle = null;
  610. }
  611. /** @hidden */
  612. public _changeCursor(cursor: string) {
  613. if (this._rootElement) {
  614. this._rootElement.style.cursor = cursor;
  615. this._cursorChanged = true;
  616. }
  617. }
  618. /** @hidden */
  619. public _registerLastControlDown(control: Control, pointerId: number) {
  620. this._lastControlDown[pointerId] = control;
  621. this.onControlPickedObservable.notifyObservers(control);
  622. }
  623. private _doPicking(x: number, y: number, type: number, pointerId: number, buttonIndex: number, deltaX?: number, deltaY?: number): void {
  624. var scene = this.getScene();
  625. if (!scene) {
  626. return;
  627. }
  628. var engine = scene.getEngine();
  629. var textureSize = this.getSize();
  630. if (this._isFullscreen) {
  631. let camera = scene.cameraToUseForPointers || scene.activeCamera;
  632. let viewport = camera!.viewport;
  633. x = x * (textureSize.width / (engine.getRenderWidth() * viewport.width));
  634. y = y * (textureSize.height / (engine.getRenderHeight() * viewport.height));
  635. }
  636. if (this._capturingControl[pointerId]) {
  637. this._capturingControl[pointerId]._processObservables(type, x, y, pointerId, buttonIndex);
  638. return;
  639. }
  640. this._cursorChanged = false;
  641. if (!this._rootContainer._processPicking(x, y, type, pointerId, buttonIndex, deltaX, deltaY)) {
  642. this._changeCursor("");
  643. if (type === PointerEventTypes.POINTERMOVE) {
  644. if (this._lastControlOver[pointerId]) {
  645. this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId]);
  646. delete this._lastControlOver[pointerId];
  647. }
  648. }
  649. }
  650. if (!this._cursorChanged) {
  651. this._changeCursor("");
  652. }
  653. this._manageFocus();
  654. }
  655. /** @hidden */
  656. public _cleanControlAfterRemovalFromList(list: { [pointerId: number]: Control }, control: Control) {
  657. for (var pointerId in list) {
  658. if (!list.hasOwnProperty(pointerId)) {
  659. continue;
  660. }
  661. var lastControlOver = list[pointerId];
  662. if (lastControlOver === control) {
  663. delete list[pointerId];
  664. }
  665. }
  666. }
  667. /** @hidden */
  668. public _cleanControlAfterRemoval(control: Control) {
  669. this._cleanControlAfterRemovalFromList(this._lastControlDown, control);
  670. this._cleanControlAfterRemovalFromList(this._lastControlOver, control);
  671. }
  672. /** Attach to all scene events required to support pointer events */
  673. public attach(): void {
  674. var scene = this.getScene();
  675. if (!scene) {
  676. return;
  677. }
  678. let tempViewport = new Viewport(0, 0, 0, 0);
  679. this._pointerMoveObserver = scene.onPrePointerObservable.add((pi, state) => {
  680. if (scene!.isPointerCaptured((<PointerEvent>(pi.event)).pointerId)) {
  681. return;
  682. }
  683. if (pi.type !== PointerEventTypes.POINTERMOVE
  684. && pi.type !== PointerEventTypes.POINTERUP
  685. && pi.type !== PointerEventTypes.POINTERDOWN
  686. && pi.type !== PointerEventTypes.POINTERWHEEL) {
  687. return;
  688. }
  689. if (!scene) {
  690. return;
  691. }
  692. if (pi.type === PointerEventTypes.POINTERMOVE && (pi.event as PointerEvent).pointerId) {
  693. this._defaultMousePointerId = (pi.event as PointerEvent).pointerId; // This is required to make sure we have the correct pointer ID for wheel
  694. }
  695. let camera = scene.cameraToUseForPointers || scene.activeCamera;
  696. let engine = scene.getEngine();
  697. if (!camera) {
  698. tempViewport.x = 0;
  699. tempViewport.y = 0;
  700. tempViewport.width = engine.getRenderWidth();
  701. tempViewport.height = engine.getRenderHeight();
  702. } else {
  703. camera.viewport.toGlobalToRef(engine.getRenderWidth(), engine.getRenderHeight(), tempViewport);
  704. }
  705. let x = scene.pointerX / engine.getHardwareScalingLevel() - tempViewport.x;
  706. let y = scene.pointerY / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - tempViewport.y - tempViewport.height);
  707. this._shouldBlockPointer = false;
  708. // Do picking modifies _shouldBlockPointer
  709. let pointerId = (pi.event as PointerEvent).pointerId || this._defaultMousePointerId;
  710. this._doPicking(x, y, pi.type, pointerId, pi.event.button, (<MouseWheelEvent>pi.event).deltaX, (<MouseWheelEvent>pi.event).deltaY);
  711. // Avoid overwriting a true skipOnPointerObservable to false
  712. if (this._shouldBlockPointer) {
  713. pi.skipOnPointerObservable = this._shouldBlockPointer;
  714. }
  715. });
  716. this._attachToOnPointerOut(scene);
  717. this._attachToOnBlur(scene);
  718. }
  719. /** @hidden */
  720. private onClipboardCopy = (rawEvt: Event) => {
  721. const evt = rawEvt as ClipboardEvent;
  722. let ev = new ClipboardInfo(ClipboardEventTypes.COPY, evt);
  723. this.onClipboardObservable.notifyObservers(ev);
  724. evt.preventDefault();
  725. }
  726. /** @hidden */
  727. private onClipboardCut = (rawEvt: Event) => {
  728. const evt = rawEvt as ClipboardEvent;
  729. let ev = new ClipboardInfo(ClipboardEventTypes.CUT, evt);
  730. this.onClipboardObservable.notifyObservers(ev);
  731. evt.preventDefault();
  732. }
  733. /** @hidden */
  734. private onClipboardPaste = (rawEvt: Event) => {
  735. const evt = rawEvt as ClipboardEvent;
  736. let ev = new ClipboardInfo(ClipboardEventTypes.PASTE, evt);
  737. this.onClipboardObservable.notifyObservers(ev);
  738. evt.preventDefault();
  739. }
  740. /**
  741. * Register the clipboard Events onto the canvas
  742. */
  743. public registerClipboardEvents(): void {
  744. self.addEventListener("copy", this.onClipboardCopy, false);
  745. self.addEventListener("cut", this.onClipboardCut, false);
  746. self.addEventListener("paste", this.onClipboardPaste, false);
  747. }
  748. /**
  749. * Unregister the clipboard Events from the canvas
  750. */
  751. public unRegisterClipboardEvents(): void {
  752. self.removeEventListener("copy", this.onClipboardCopy);
  753. self.removeEventListener("cut", this.onClipboardCut);
  754. self.removeEventListener("paste", this.onClipboardPaste);
  755. }
  756. /**
  757. * Connect the texture to a hosting mesh to enable interactions
  758. * @param mesh defines the mesh to attach to
  759. * @param supportPointerMove defines a boolean indicating if pointer move events must be catched as well
  760. */
  761. public attachToMesh(mesh: AbstractMesh, supportPointerMove = true): void {
  762. var scene = this.getScene();
  763. if (!scene) {
  764. return;
  765. }
  766. this._pointerObserver = scene.onPointerObservable.add((pi, state) => {
  767. if (pi.type !== PointerEventTypes.POINTERMOVE
  768. && pi.type !== PointerEventTypes.POINTERUP
  769. && pi.type !== PointerEventTypes.POINTERDOWN) {
  770. return;
  771. }
  772. var pointerId = (pi.event as PointerEvent).pointerId || this._defaultMousePointerId;
  773. if (pi.pickInfo && pi.pickInfo.hit && pi.pickInfo.pickedMesh === mesh) {
  774. var uv = pi.pickInfo.getTextureCoordinates();
  775. if (uv) {
  776. let size = this.getSize();
  777. this._doPicking(uv.x * size.width, (1.0 - uv.y) * size.height, pi.type, pointerId, pi.event.button);
  778. }
  779. } else if (pi.type === PointerEventTypes.POINTERUP) {
  780. if (this._lastControlDown[pointerId]) {
  781. this._lastControlDown[pointerId]._forcePointerUp(pointerId);
  782. }
  783. delete this._lastControlDown[pointerId];
  784. if (this.focusedControl) {
  785. const friendlyControls = this.focusedControl.keepsFocusWith();
  786. let canMoveFocus = true;
  787. if (friendlyControls) {
  788. for (var control of friendlyControls) {
  789. // Same host, no need to keep the focus
  790. if (this === control._host) {
  791. continue;
  792. }
  793. // Different hosts
  794. const otherHost = control._host;
  795. if (otherHost._lastControlOver[pointerId] && otherHost._lastControlOver[pointerId].isAscendant(control)) {
  796. canMoveFocus = false;
  797. break;
  798. }
  799. }
  800. }
  801. if (canMoveFocus) {
  802. this.focusedControl = null;
  803. }
  804. }
  805. } else if (pi.type === PointerEventTypes.POINTERMOVE) {
  806. if (this._lastControlOver[pointerId]) {
  807. this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId], true);
  808. }
  809. delete this._lastControlOver[pointerId];
  810. }
  811. });
  812. mesh.enablePointerMoveEvents = supportPointerMove;
  813. this._attachToOnPointerOut(scene);
  814. this._attachToOnBlur(scene);
  815. }
  816. /**
  817. * Move the focus to a specific control
  818. * @param control defines the control which will receive the focus
  819. */
  820. public moveFocusToControl(control: IFocusableControl): void {
  821. this.focusedControl = control;
  822. this._lastPickedControl = <any>control;
  823. this._blockNextFocusCheck = true;
  824. }
  825. private _manageFocus(): void {
  826. if (this._blockNextFocusCheck) {
  827. this._blockNextFocusCheck = false;
  828. this._lastPickedControl = <any>this._focusedControl;
  829. return;
  830. }
  831. // Focus management
  832. if (this._focusedControl) {
  833. if (this._focusedControl !== (<any>this._lastPickedControl)) {
  834. if (this._lastPickedControl.isFocusInvisible) {
  835. return;
  836. }
  837. this.focusedControl = null;
  838. }
  839. }
  840. }
  841. private _attachToOnPointerOut(scene: Scene): void {
  842. this._canvasPointerOutObserver = scene.getEngine().onCanvasPointerOutObservable.add((pointerEvent) => {
  843. if (this._lastControlOver[pointerEvent.pointerId]) {
  844. this._lastControlOver[pointerEvent.pointerId]._onPointerOut(this._lastControlOver[pointerEvent.pointerId]);
  845. }
  846. delete this._lastControlOver[pointerEvent.pointerId];
  847. if (this._lastControlDown[pointerEvent.pointerId] && this._lastControlDown[pointerEvent.pointerId] !== this._capturingControl[pointerEvent.pointerId]) {
  848. this._lastControlDown[pointerEvent.pointerId]._forcePointerUp();
  849. delete this._lastControlDown[pointerEvent.pointerId];
  850. }
  851. });
  852. }
  853. private _attachToOnBlur(scene: Scene): void {
  854. this._canvasBlurObserver = scene.getEngine().onCanvasBlurObservable.add((pointerEvent) => {
  855. Object.entries(this._lastControlDown).forEach(([key, value]) => {
  856. value._onCanvasBlur();
  857. });
  858. this._lastControlDown = {};
  859. });
  860. }
  861. // Statics
  862. /**
  863. * Creates a new AdvancedDynamicTexture in projected mode (ie. attached to a mesh)
  864. * @param mesh defines the mesh which will receive the texture
  865. * @param width defines the texture width (1024 by default)
  866. * @param height defines the texture height (1024 by default)
  867. * @param supportPointerMove defines a boolean indicating if the texture must capture move events (true by default)
  868. * @param onlyAlphaTesting defines a boolean indicating that alpha blending will not be used (only alpha testing) (false by default)
  869. * @returns a new AdvancedDynamicTexture
  870. */
  871. public static CreateForMesh(mesh: AbstractMesh, width = 1024, height = 1024, supportPointerMove = true, onlyAlphaTesting = false): AdvancedDynamicTexture {
  872. var result = new AdvancedDynamicTexture(mesh.name + " AdvancedDynamicTexture", width, height, mesh.getScene(), true, Texture.TRILINEAR_SAMPLINGMODE);
  873. var material = new StandardMaterial("AdvancedDynamicTextureMaterial", mesh.getScene());
  874. material.backFaceCulling = false;
  875. material.diffuseColor = Color3.Black();
  876. material.specularColor = Color3.Black();
  877. if (onlyAlphaTesting) {
  878. material.diffuseTexture = result;
  879. material.emissiveTexture = result;
  880. result.hasAlpha = true;
  881. } else {
  882. material.emissiveTexture = result;
  883. material.opacityTexture = result;
  884. }
  885. mesh.material = material;
  886. result.attachToMesh(mesh, supportPointerMove);
  887. return result;
  888. }
  889. /**
  890. * Creates a new AdvancedDynamicTexture in fullscreen mode.
  891. * In this mode the texture will rely on a layer for its rendering.
  892. * This allows it to be treated like any other layer.
  893. * As such, if you have a multi camera setup, you can set the layerMask on the GUI as well.
  894. * LayerMask is set through advancedTexture.layer.layerMask
  895. * @param name defines name for the texture
  896. * @param foreground defines a boolean indicating if the texture must be rendered in foreground (default is true)
  897. * @param scene defines the hsoting scene
  898. * @param sampling defines the texture sampling mode (Texture.BILINEAR_SAMPLINGMODE by default)
  899. * @returns a new AdvancedDynamicTexture
  900. */
  901. public static CreateFullscreenUI(name: string, foreground: boolean = true, scene: Nullable<Scene> = null, sampling = Texture.BILINEAR_SAMPLINGMODE): AdvancedDynamicTexture {
  902. var result = new AdvancedDynamicTexture(name, 0, 0, scene, false, sampling);
  903. // Display
  904. var layer = new Layer(name + "_layer", null, scene, !foreground);
  905. layer.texture = result;
  906. result._layerToDispose = layer;
  907. result._isFullscreen = true;
  908. // Attach
  909. result.attach();
  910. return result;
  911. }
  912. }