babylon.prim2dBase.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. module BABYLON {
  2. export class Render2DContext {
  3. forceRefreshPrimitive: boolean;
  4. }
  5. /**
  6. * This class store information for the pointerEventObservable Observable.
  7. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  8. */
  9. export class PrimitivePointerInfo {
  10. private static _pointerOver = 0x0001;
  11. private static _pointerEnter = 0x0002;
  12. private static _pointerDown = 0x0004;
  13. private static _pointerMouseWheel = 0x0008;
  14. private static _pointerMove = 0x0010;
  15. private static _pointerUp = 0x0020;
  16. private static _pointerOut = 0x0040;
  17. private static _pointerLeave = 0x0080;
  18. private static _pointerGotCapture = 0x0100;
  19. private static _pointerLostCapture = 0x0200;
  20. private static _mouseWheelPrecision = 3.0;
  21. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  22. /**
  23. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  24. * Bubbles: yes
  25. */
  26. public static get PointerOver(): number {
  27. return PrimitivePointerInfo._pointerOver;
  28. }
  29. /**
  30. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  31. * Bubbles: no
  32. */
  33. public static get PointerEnter(): number {
  34. return PrimitivePointerInfo._pointerEnter;
  35. }
  36. /**
  37. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  38. * Bubbles: yes
  39. */
  40. public static get PointerDown(): number {
  41. return PrimitivePointerInfo._pointerDown;
  42. }
  43. /**
  44. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  45. * Bubbles: yes
  46. */
  47. public static get PointerMouseWheel(): number {
  48. return PrimitivePointerInfo._pointerMouseWheel;
  49. }
  50. /**
  51. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  52. * Bubbles: yes
  53. */
  54. public static get PointerMove(): number {
  55. return PrimitivePointerInfo._pointerMove;
  56. }
  57. /**
  58. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  59. * Bubbles: yes
  60. */
  61. public static get PointerUp(): number {
  62. return PrimitivePointerInfo._pointerUp;
  63. }
  64. /**
  65. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  66. * Bubbles: yes
  67. */
  68. public static get PointerOut(): number {
  69. return PrimitivePointerInfo._pointerOut;
  70. }
  71. /**
  72. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  73. * Bubbles: no
  74. */
  75. public static get PointerLeave(): number {
  76. return PrimitivePointerInfo._pointerLeave;
  77. }
  78. /**
  79. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  80. * Bubbles: yes
  81. */
  82. public static get PointerGotCapture(): number {
  83. return PrimitivePointerInfo._pointerGotCapture;
  84. }
  85. /**
  86. * This event type is raised after pointer capture is released for a pointer.
  87. * Bubbles: yes
  88. */
  89. public static get PointerLostCapture(): number {
  90. return PrimitivePointerInfo._pointerLostCapture;
  91. }
  92. public static get MouseWheelPrecision(): number {
  93. return PrimitivePointerInfo._mouseWheelPrecision;
  94. }
  95. /**
  96. * Event Type, one of the static PointerXXXX property defined above (PrimitivePointerInfo.PointerOver to PrimitivePointerInfo.PointerLostCapture)
  97. */
  98. eventType: number;
  99. /**
  100. * Position of the pointer relative to the bottom/left of the Canvas
  101. */
  102. canvasPointerPos: Vector2;
  103. /**
  104. * Position of the pointer relative to the bottom/left of the primitive that registered the Observer
  105. */
  106. primitivePointerPos: Vector2;
  107. /**
  108. * The primitive where the event was initiated first (in case of bubbling)
  109. */
  110. relatedTarget: Prim2DBase;
  111. /**
  112. * Position of the pointer relative to the bottom/left of the relatedTarget
  113. */
  114. relatedTargetPointerPos: Vector2;
  115. /**
  116. * An observable can set this property to true to stop bubbling on the upper levels
  117. */
  118. cancelBubble: boolean;
  119. /**
  120. * True if the Control keyboard key is down
  121. */
  122. ctrlKey: boolean;
  123. /**
  124. * true if the Shift keyboard key is down
  125. */
  126. shiftKey: boolean;
  127. /**
  128. * true if the Alt keyboard key is down
  129. */
  130. altKey: boolean;
  131. /**
  132. * true if the Meta keyboard key is down
  133. */
  134. metaKey: boolean;
  135. /**
  136. * For button, buttons, refer to https://www.w3.org/TR/pointerevents/#button-states
  137. */
  138. button: number;
  139. /**
  140. * For button, buttons, refer to https://www.w3.org/TR/pointerevents/#button-states
  141. */
  142. buttons: number;
  143. /**
  144. * The amount of mouse wheel rolled
  145. */
  146. mouseWheelDelta: number;
  147. /**
  148. * Id of the Pointer involved in the event
  149. */
  150. pointerId: number;
  151. width: number;
  152. height: number;
  153. presssure: number;
  154. tilt: Vector2;
  155. /**
  156. * true if the involved pointer is captured for a particular primitive, false otherwise.
  157. */
  158. isCaptured: boolean;
  159. constructor() {
  160. this.primitivePointerPos = Vector2.Zero();
  161. this.tilt = Vector2.Zero();
  162. this.cancelBubble = false;
  163. }
  164. updateRelatedTarget(prim: Prim2DBase, primPointerPos: Vector2) {
  165. this.relatedTarget = prim;
  166. this.relatedTargetPointerPos = primPointerPos;
  167. }
  168. public static getEventTypeName(mask: number): string {
  169. switch (mask) {
  170. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  171. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  172. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  173. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  174. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  175. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  176. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  177. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  178. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  179. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  180. }
  181. }
  182. }
  183. /**
  184. * Stores information about a Primitive that was intersected
  185. */
  186. export class PrimitiveIntersectedInfo {
  187. constructor(public prim: Prim2DBase, public intersectionLocation: Vector2) {
  188. }
  189. }
  190. /**
  191. * Main class used for the Primitive Intersection API
  192. */
  193. export class IntersectInfo2D {
  194. constructor() {
  195. this.findFirstOnly = false;
  196. this.intersectHidden = false;
  197. this.pickPosition = Vector2.Zero();
  198. }
  199. // Input settings, to setup before calling an intersection related method
  200. /**
  201. * Set the pick position, relative to the primitive where the intersection test is made
  202. */
  203. public pickPosition: Vector2;
  204. /**
  205. * If true the intersection will stop at the first hit, if false all primitives will be tested and the intersectedPrimitives array will be filled accordingly (false default)
  206. */
  207. public findFirstOnly: boolean;
  208. /**
  209. * If true the intersection test will also be made on hidden primitive (false default)
  210. */
  211. public intersectHidden: boolean;
  212. // Intermediate data, don't use!
  213. public _globalPickPosition: Vector2;
  214. public _localPickPosition: Vector2;
  215. // Output settings, up to date in return of a call to an intersection related method
  216. /**
  217. * The topmost intersected primitive
  218. */
  219. public topMostIntersectedPrimitive: PrimitiveIntersectedInfo;
  220. /**
  221. * The array containing all intersected primitive, in no particular order.
  222. */
  223. public intersectedPrimitives: Array<PrimitiveIntersectedInfo>;
  224. /**
  225. * true if at least one primitive intersected during the test
  226. */
  227. public get isIntersected(): boolean {
  228. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  229. }
  230. // Internals, don't use
  231. public _exit(firstLevel: boolean) {
  232. if (firstLevel) {
  233. this._globalPickPosition = null;
  234. }
  235. }
  236. }
  237. @className("Prim2DBase")
  238. /**
  239. * Base class for a Primitive of the Canvas2D feature
  240. */
  241. export class Prim2DBase extends SmartPropertyPrim {
  242. static PRIM2DBASE_PROPCOUNT: number = 10;
  243. protected setupPrim2DBase(owner: Canvas2D, parent: Prim2DBase, id: string, position: Vector2, isVisible: boolean = true) {
  244. if (!(this instanceof Group2D) && !(this instanceof Sprite2D && id !== null && id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  245. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  246. }
  247. this.setupSmartPropertyPrim();
  248. this._pointerEventObservable = new Observable<PrimitivePointerInfo>();
  249. this._isPickable = true;
  250. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  251. this._boundingInfoDirty = true;
  252. this._boundingInfo = new BoundingInfo2D();
  253. this._owner = owner;
  254. this._parent = parent;
  255. if (parent != null) {
  256. this._hierarchyDepth = parent._hierarchyDepth + 1;
  257. this._renderGroup = <Group2D>this.parent.traverseUp(p => p instanceof Group2D && p.isRenderableGroup);
  258. parent.addChild(this);
  259. } else {
  260. this._hierarchyDepth = 0;
  261. this._renderGroup = null;
  262. }
  263. this._id = id;
  264. this.propertyChanged = new Observable<PropertyChangedInfo>();
  265. this._children = new Array<Prim2DBase>();
  266. this._globalTransformProcessStep = 0;
  267. this._globalTransformStep = 0;
  268. if (this instanceof Group2D) {
  269. var group: any = this;
  270. group.detectGroupStates();
  271. }
  272. this.position = position;
  273. this.rotation = 0;
  274. this.scale = 1;
  275. this.levelVisible = isVisible;
  276. this.origin = new Vector2(0.5, 0.5);
  277. }
  278. /**
  279. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  280. * @param predicate the predicate to test on each parent
  281. * @return the first primitive where the predicate was successful
  282. */
  283. public traverseUp(predicate: (p: Prim2DBase) => boolean): Prim2DBase {
  284. let p: Prim2DBase = this;
  285. while (p != null) {
  286. if (predicate(p)) {
  287. return p;
  288. }
  289. p = p._parent;
  290. }
  291. return null;
  292. }
  293. /**
  294. * Retrieve the owner Canvas2D
  295. */
  296. public get owner(): Canvas2D {
  297. return this._owner;
  298. }
  299. /**
  300. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  301. */
  302. public get parent(): Prim2DBase {
  303. return this._parent;
  304. }
  305. /**
  306. * The array of direct children primitives
  307. */
  308. public get children(): Prim2DBase[] {
  309. return this._children;
  310. }
  311. /**
  312. * The identifier of this primitive, may not be unique, it's for information purpose only
  313. */
  314. public get id(): string {
  315. return this._id;
  316. }
  317. public static positionProperty: Prim2DPropInfo;
  318. public static rotationProperty: Prim2DPropInfo;
  319. public static scaleProperty: Prim2DPropInfo;
  320. public static originProperty: Prim2DPropInfo;
  321. public static levelVisibleProperty: Prim2DPropInfo;
  322. public static isVisibleProperty: Prim2DPropInfo;
  323. public static zOrderProperty: Prim2DPropInfo;
  324. @instanceLevelProperty(1, pi => Prim2DBase.positionProperty = pi, false, true)
  325. /**
  326. * Position of the primitive, relative to its parent.
  327. */
  328. public get position(): Vector2 {
  329. return this._position;
  330. }
  331. public set position(value: Vector2) {
  332. this._position = value;
  333. }
  334. @instanceLevelProperty(2, pi => Prim2DBase.rotationProperty = pi, false, true)
  335. /**
  336. * Rotation of the primitive, in radian, along the Z axis
  337. * @returns {}
  338. */
  339. public get rotation(): number {
  340. return this._rotation;
  341. }
  342. public set rotation(value: number) {
  343. this._rotation = value;
  344. }
  345. @instanceLevelProperty(3, pi => Prim2DBase.scaleProperty = pi, false, true)
  346. /**
  347. * Uniform scale applied on the primitive
  348. */
  349. public set scale(value: number) {
  350. this._scale = value;
  351. }
  352. public get scale(): number {
  353. return this._scale;
  354. }
  355. /**
  356. * this method must be implemented by the primitive type to return its size
  357. * @returns The size of the primitive
  358. */
  359. public get actualSize(): Size {
  360. return undefined;
  361. }
  362. @instanceLevelProperty(4, pi => Prim2DBase.originProperty = pi, false, true)
  363. public set origin(value: Vector2) {
  364. this._origin = value;
  365. }
  366. /**
  367. * The origin defines the normalized coordinate of the center of the primitive, from the top/left corner.
  368. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  369. * For instance:
  370. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  371. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  372. * 0,1 means the center is top/left
  373. * @returns The normalized center.
  374. */
  375. public get origin(): Vector2 {
  376. return this._origin;
  377. }
  378. @dynamicLevelProperty(5, pi => Prim2DBase.levelVisibleProperty = pi)
  379. /**
  380. * Let the user defines if the Primitive is hidden or not at its level. As Primitives inherit the hidden status from their parent, only the isVisible property give properly the real visible state.
  381. * Default is true, setting to false will hide this primitive and its children.
  382. */
  383. public get levelVisible(): boolean {
  384. return this._levelVisible;
  385. }
  386. public set levelVisible(value: boolean) {
  387. this._levelVisible = value;
  388. }
  389. @instanceLevelProperty(6, pi => Prim2DBase.isVisibleProperty = pi)
  390. /**
  391. * Use ONLY THE GETTER to determine if the primitive is visible or not.
  392. * The Setter is for internal purpose only!
  393. */
  394. public get isVisible(): boolean {
  395. return this._isVisible;
  396. }
  397. public set isVisible(value: boolean) {
  398. this._isVisible = value;
  399. }
  400. @instanceLevelProperty(7, pi => Prim2DBase.zOrderProperty = pi)
  401. /**
  402. * You can override the default Z Order through this property, but most of the time the default behavior is acceptable
  403. * @returns {}
  404. */
  405. public get zOrder(): number {
  406. return this._zOrder;
  407. }
  408. public set zOrder(value: number) {
  409. this._zOrder = value;
  410. }
  411. /**
  412. * Define if the Primitive can be subject to intersection test or not (default is true)
  413. */
  414. public get isPickable(): boolean {
  415. return this._isPickable;
  416. }
  417. public set isPickable(value: boolean) {
  418. this._isPickable = value;
  419. }
  420. /**
  421. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  422. * @returns {}
  423. */
  424. public get hierarchyDepth(): number {
  425. return this._hierarchyDepth;
  426. }
  427. /**
  428. * Retrieve the Group that is responsible to render this primitive
  429. * @returns {}
  430. */
  431. public get renderGroup(): Group2D {
  432. return this._renderGroup;
  433. }
  434. /**
  435. * Get the global transformation matrix of the primitive
  436. */
  437. public get globalTransform(): Matrix {
  438. return this._globalTransform;
  439. }
  440. /**
  441. * Get invert of the global transformation matrix of the primitive
  442. * @returns {}
  443. */
  444. public get invGlobalTransform(): Matrix {
  445. return this._invGlobalTransform;
  446. }
  447. /**
  448. * Get the local transformation of the primitive
  449. */
  450. public get localTransform(): Matrix {
  451. this._updateLocalTransform();
  452. return this._localTransform;
  453. }
  454. /**
  455. * Get the boundingInfo associated to the primitive.
  456. * The value is supposed to be always up to date
  457. */
  458. public get boundingInfo(): BoundingInfo2D {
  459. if (this._boundingInfoDirty) {
  460. this._boundingInfo = this.levelBoundingInfo.clone();
  461. let bi = this._boundingInfo;
  462. var tps = new BoundingInfo2D();
  463. for (let curChild of this._children) {
  464. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  465. bi.unionToRef(tps, bi);
  466. }
  467. this._boundingInfoDirty = false;
  468. }
  469. return this._boundingInfo;
  470. }
  471. /**
  472. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  473. */
  474. public get pointerEventObservable(): Observable<PrimitivePointerInfo> {
  475. return this._pointerEventObservable;
  476. }
  477. protected levelIntersect(intersectInfo: IntersectInfo2D): boolean {
  478. return false;
  479. }
  480. /**
  481. * Capture all the Events of the given PointerId for this primitive.
  482. * Don't forget to call releasePointerEventsCapture when done.
  483. * @param pointerId the Id of the pointer to capture the events from.
  484. */
  485. public setPointerEventCapture(pointerId: number): boolean {
  486. return this.owner._setPointerCapture(pointerId, this);
  487. }
  488. /**
  489. * Release a captured pointer made with setPointerEventCapture.
  490. * @param pointerId the Id of the pointer to release the capture from.
  491. */
  492. public releasePointerEventsCapture(pointerId: number): boolean {
  493. return this.owner._releasePointerCapture(pointerId, this);
  494. }
  495. /**
  496. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  497. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  498. */
  499. public intersect(intersectInfo: IntersectInfo2D): boolean {
  500. if (!intersectInfo) {
  501. return false;
  502. }
  503. // If this is null it means this method is call for the first level, initialize stuffs
  504. let firstLevel = !intersectInfo._globalPickPosition;
  505. if (firstLevel) {
  506. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  507. intersectInfo._globalPickPosition = Vector2.Zero();
  508. Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  509. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  510. intersectInfo.intersectedPrimitives = new Array<PrimitiveIntersectedInfo>();
  511. intersectInfo.topMostIntersectedPrimitive = null;
  512. }
  513. if (!intersectInfo.intersectHidden && !this.isVisible) {
  514. return false;
  515. }
  516. // Fast rejection test with boundingInfo
  517. if (!this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  518. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  519. intersectInfo._exit(firstLevel);
  520. return false;
  521. }
  522. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  523. let levelIntersectRes = this.levelIntersect(intersectInfo);
  524. if (levelIntersectRes) {
  525. let pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  526. intersectInfo.intersectedPrimitives.push(pii);
  527. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.getActualZOffset() > pii.prim.getActualZOffset())) {
  528. intersectInfo.topMostIntersectedPrimitive = pii;
  529. }
  530. // If we must stop at the first intersection, we're done, quit!
  531. if (intersectInfo.findFirstOnly) {
  532. intersectInfo._exit(firstLevel);
  533. return true;
  534. }
  535. }
  536. // Recurse to children if needed
  537. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  538. for (let curChild of this._children) {
  539. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  540. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  541. continue;
  542. }
  543. // Must compute the localPickLocation for the children level
  544. Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  545. // If we got an intersection with the child and we only need to find the first one, quit!
  546. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  547. intersectInfo._exit(firstLevel);
  548. return true;
  549. }
  550. }
  551. }
  552. intersectInfo._exit(firstLevel);
  553. return intersectInfo.isIntersected;
  554. }
  555. public moveChild(child: Prim2DBase, previous: Prim2DBase): boolean {
  556. if (child.parent !== this) {
  557. return false;
  558. }
  559. let prevOffset: number, nextOffset: number;
  560. let childIndex = this._children.indexOf(child);
  561. let prevIndex = previous ? this._children.indexOf(previous) : -1;
  562. // Move to first position
  563. if (!previous) {
  564. prevOffset = 1;
  565. nextOffset = this._children[1]._siblingDepthOffset;
  566. } else {
  567. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  568. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  569. }
  570. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  571. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  572. }
  573. private addChild(child: Prim2DBase) {
  574. child._siblingDepthOffset = (this._children.length + 1) * this.owner.hierarchySiblingZDelta;
  575. child._depthLevel = this._depthLevel + 1;
  576. child._hierarchyDepthOffset = child._depthLevel * this.owner.hierarchyLevelZFactor;
  577. this._children.push(child);
  578. }
  579. public dispose(): boolean {
  580. if (!super.dispose()) {
  581. return false;
  582. }
  583. // If there's a parent, remove this object from its parent list
  584. if (this._parent) {
  585. let i = this._parent._children.indexOf(this);
  586. if (i !== undefined) {
  587. this._parent._children.splice(i, 1);
  588. }
  589. this._parent = null;
  590. }
  591. // Recurse dispose to children
  592. if (this._children) {
  593. while (this._children.length > 0) {
  594. this._children[this._children.length - 1].dispose();
  595. }
  596. }
  597. return true;
  598. }
  599. public getActualZOffset(): number {
  600. return this._zOrder || 1 - (this._siblingDepthOffset + this._hierarchyDepthOffset);
  601. }
  602. protected onPrimBecomesDirty() {
  603. if (this._renderGroup) {
  604. this._renderGroup._addPrimToDirtyList(this);
  605. }
  606. }
  607. public _needPrepare(): boolean {
  608. return (this.isVisible || this._visibilityChanged) && (this._modelDirty || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep));
  609. }
  610. public _prepareRender(context: Render2DContext) {
  611. this._prepareRenderPre(context);
  612. this._prepareRenderPost(context);
  613. }
  614. public _prepareRenderPre(context: Render2DContext) {
  615. }
  616. public _prepareRenderPost(context: Render2DContext) {
  617. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  618. if (this instanceof Group2D) {
  619. var self: any = this;
  620. if (self.isRenderableGroup) {
  621. return;
  622. }
  623. }
  624. // Check if we need to recurse the prepare to children primitives
  625. // - must have children
  626. // - the global transform of this level have changed, or
  627. // - the visible state of primitive has changed
  628. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  629. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  630. this._children.forEach(c => {
  631. // As usual stop the recursion if we meet a renderable group
  632. if (!(c instanceof Group2D && c.isRenderableGroup)) {
  633. c._prepareRender(context);
  634. }
  635. });
  636. }
  637. // Finally reset the dirty flags as we've processed everything
  638. this._modelDirty = false;
  639. this._instanceDirtyFlags = 0;
  640. }
  641. protected static CheckParent(parent: Prim2DBase) {
  642. if (!parent) {
  643. throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  644. }
  645. }
  646. protected updateGlobalTransVisOf(list: Prim2DBase[], recurse: boolean) {
  647. for (let cur of list) {
  648. cur.updateGlobalTransVis(recurse);
  649. }
  650. }
  651. private _updateLocalTransform(): boolean {
  652. let tflags = Prim2DBase.positionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId;
  653. if (this.checkPropertiesDirty(tflags)) {
  654. var rot = Quaternion.RotationAxis(new Vector3(0, 0, 1), this._rotation);
  655. var local = Matrix.Compose(new Vector3(this._scale, this._scale, this._scale), rot, new Vector3(this._position.x, this._position.y, 0));
  656. this._localTransform = local;
  657. this.clearPropertiesDirty(tflags);
  658. // this is important to access actualSize AFTER fetching a first version of the local transform and reset the dirty flag, because accessing actualSize on a Group2D which actualSize is built from its content will trigger a call to this very method on this very object. We won't mind about the origin offset not being computed, as long as we return a local transform based on the position/rotation/scale
  659. var actualSize = this.actualSize;
  660. if (!actualSize) {
  661. throw new Error(`The primitive type: ${Tools.getClassName(this)} must implement the actualSize get property!`);
  662. }
  663. local.m[12] -= (actualSize.width * this.origin.x) * local.m[0] + (actualSize.height * this.origin.y) * local.m[4];
  664. local.m[13] -= (actualSize.width * this.origin.x) * local.m[1] + (actualSize.height * this.origin.y) * local.m[5];
  665. return true;
  666. }
  667. return false;
  668. }
  669. protected updateGlobalTransVis(recurse: boolean) {
  670. if (this.isDisposed) {
  671. return;
  672. }
  673. // Check if the parent is synced
  674. if (this._parent && this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  675. this._parent.updateGlobalTransVis(false);
  676. }
  677. // Check if we must update this prim
  678. if (this === <any>this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  679. let curVisibleState = this.isVisible;
  680. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  681. // Detect a change of visibility
  682. this._visibilityChanged = (curVisibleState !== undefined) && curVisibleState !== this.isVisible;
  683. // Get/compute the localTransform
  684. let localDirty = this._updateLocalTransform();
  685. // Check if we have to update the globalTransform
  686. if (!this._globalTransform || localDirty || (this._parent && this._parent._globalTransformStep !== this._parentTransformStep)) {
  687. this._globalTransform = this._parent ? this._localTransform.multiply(this._parent._globalTransform) : this._localTransform;
  688. this._invGlobalTransform = Matrix.Invert(this._globalTransform);
  689. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  690. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  691. }
  692. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  693. }
  694. if (recurse) {
  695. for (let child of this._children) {
  696. // Stop the recursion if we meet a renderable group
  697. child.updateGlobalTransVis(!(child instanceof Group2D && child.isRenderableGroup));
  698. }
  699. }
  700. }
  701. private _owner: Canvas2D;
  702. private _parent: Prim2DBase;
  703. protected _children: Array<Prim2DBase>;
  704. private _renderGroup: Group2D;
  705. private _hierarchyDepth: number;
  706. protected _depthLevel: number;
  707. private _hierarchyDepthOffset: number;
  708. private _siblingDepthOffset: number;
  709. private _zOrder: number;
  710. private _levelVisible: boolean;
  711. public _pointerEventObservable: Observable<PrimitivePointerInfo>;
  712. public _boundingInfoDirty: boolean;
  713. protected _visibilityChanged;
  714. private _isPickable;
  715. private _isVisible: boolean;
  716. private _id: string;
  717. private _position: Vector2;
  718. private _rotation: number;
  719. private _scale: number;
  720. private _origin: Vector2;
  721. // Stores the step of the parent for which the current global transform was computed
  722. // If the parent has a new step, it means this prim's global transform must be updated
  723. protected _parentTransformStep: number;
  724. // Stores the step corresponding of the global transform for this prim
  725. // If a child prim has an older _parentTransformStep it means the child's transform should be updated
  726. protected _globalTransformStep: number;
  727. // Stores the previous
  728. protected _globalTransformProcessStep: number;
  729. protected _localTransform: Matrix;
  730. protected _globalTransform: Matrix;
  731. protected _invGlobalTransform: Matrix;
  732. }
  733. }