Object2D.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. import {Vector2} from "./math/Vector2.js";
  2. import {Matrix} from "./math/Matrix.js";
  3. import {UUID} from "./math/UUID.js";
  4. /**
  5. * Base object class, implements all the object positioning and scaling features.
  6. *
  7. * Stores all the base properties shared between all objects as the position, transformation properties, children etc.
  8. *
  9. * Object2D object can be used as a group to the other objects drawn.
  10. *
  11. * @class
  12. */
  13. function Object2D()
  14. {
  15. /**
  16. * UUID of the object.
  17. *
  18. * @type {string}
  19. */
  20. this.uuid = UUID.generate();
  21. /**
  22. * List of children objects attached to the object.
  23. *
  24. * @type {Object2D[]}
  25. */
  26. this.children = [];
  27. /**
  28. * Parent object, the object position is affected by its parent position.
  29. *
  30. * @type {Object2D}
  31. */
  32. this.parent = null;
  33. /**
  34. * Depth level in the object tree, objects with higher depth are drawn on top.
  35. *
  36. * The layer value is considered first.
  37. *
  38. * @type {number}
  39. */
  40. this.level = 0;
  41. /**
  42. * Position of the object.
  43. *
  44. * The world position of the object is affected by its parent transform.
  45. *
  46. * @type {Vector2}
  47. */
  48. this.position = new Vector2(0, 0);
  49. /**
  50. * Origin of the object used as point of rotation.
  51. *
  52. * @type {Vector2}
  53. */
  54. this.origin = new Vector2(0, 0);
  55. /**
  56. * Scale of the object.
  57. *
  58. * The world scale of the object is affected by the parent transform.
  59. *
  60. * @type {Vector2}
  61. */
  62. this.scale = new Vector2(1, 1);
  63. /**
  64. * Rotation of the object relative to its center.
  65. *
  66. * The world rotation of the object is affected by the parent transform.
  67. *
  68. * @type {number}
  69. */
  70. this.rotation = 0.0;
  71. /**
  72. * Indicates if the object is visible.
  73. *
  74. * @type {boolean}
  75. */
  76. this.visible = true;
  77. /**
  78. * Layer of this object, objects are sorted by layer value.
  79. *
  80. * Lower layer value is draw first, higher layer value is drawn on top.
  81. *
  82. * @type {number}
  83. */
  84. this.layer = 0;
  85. /**
  86. * Local transformation matrix applied to the object.
  87. *
  88. * @type {Matrix}
  89. */
  90. this.matrix = new Matrix();
  91. /**
  92. * Global transformation matrix multiplied by the parent matrix.
  93. *
  94. * Used to transform the object before projecting into screen coordinates.
  95. *
  96. * @type {Matrix}
  97. */
  98. this.globalMatrix = new Matrix();
  99. /**
  100. * Inverse of the global (world) transform matrix.
  101. *
  102. * Used to convert pointer input points (viewport space) into object coordinates.
  103. *
  104. * @type {Matrix}
  105. */
  106. this.inverseGlobalMatrix = new Matrix();
  107. /**
  108. * Mask objects being applied to this object. Used to mask/subtract portions of this object when rendering.
  109. *
  110. * Multiple masks can be used simultaneously. Same mask might be reused for multiple objects.
  111. *
  112. * @type {Mask[]}
  113. */
  114. this.masks = [];
  115. /**
  116. * Indicates if the transform matrix should be automatically updated every frame.
  117. *
  118. * Set this false for better performance. But if you do so dont forget to set matrixNeedsUpdate every time that a transform attribute is changed.
  119. *
  120. * @type {boolean}
  121. */
  122. this.matrixAutoUpdate = true;
  123. /**
  124. * Indicates if the matrix needs to be updated, should be set true after changes to the object position, scale or rotation.
  125. *
  126. * The matrix is updated before rendering the object, after the matrix is updated this attribute is automatically reset to false.
  127. *
  128. * @type {boolean}
  129. */
  130. this.matrixNeedsUpdate = true;
  131. /**
  132. * Draggable controls if its possible to drag the object around. Set this true to enable dragging events on this object.
  133. *
  134. * The onPointerDrag callback is used to update the state of the object while being dragged, by default it just updates the object position.
  135. *
  136. * @type {boolean}
  137. */
  138. this.draggable = false;
  139. /**
  140. * Indicates if this object uses pointer events.
  141. *
  142. * Can be set false to skip the pointer interaction events, better performance if pointer events are not required.
  143. *
  144. * @type {boolean}
  145. */
  146. this.pointerEvents = true;
  147. /**
  148. * Flag to indicate whether this object ignores the viewport transformation.
  149. *
  150. * @type {boolean}
  151. */
  152. this.ignoreViewport = false;
  153. /**
  154. * Flag to indicate if the context of canvas should be saved before render.
  155. *
  156. * @type {boolean}
  157. */
  158. this.saveContextState = true;
  159. /**
  160. * Flag to indicate if the context of canvas should be restored after render.
  161. *
  162. * @type {boolean}
  163. */
  164. this.restoreContextState = true;
  165. /**
  166. * Flag indicating if the pointer is inside of the element.
  167. *
  168. * Used to control object event.
  169. *
  170. * @type {boolean}
  171. */
  172. this.pointerInside = false;
  173. /**
  174. * Flag to indicate if the object is currently being dragged.
  175. *
  176. * @type {boolean}
  177. */
  178. this.beingDragged = false;
  179. /**
  180. * Indicates if the object should be serialized or not as a child of another object.
  181. *
  182. * Used to prevent duplicate serialization data on custom objects. Should be set false for objects added on constructor.
  183. *
  184. * @type {boolean}
  185. */
  186. this.serializable = true;
  187. }
  188. Object2D.prototype.constructor = Object2D;
  189. /**
  190. * Type of the object, used for data serialization and/or checking the object type.
  191. *
  192. * The name used should match the object constructor name. But it is not required.
  193. *
  194. * If this type is from an external library you can add the library name to the object type name to prevent collisions.
  195. *
  196. * @type {string}
  197. */
  198. Object2D.prototype.type = "Object2D";
  199. /**
  200. * List of available object types known by the application. Stores the object constructor by object type.
  201. *
  202. * Newly created types should be introduced in this map for data serialization support.
  203. *
  204. * New object types should be added using the Object2D.register() method.
  205. *
  206. * @static
  207. * @type {Map<string, Function>}
  208. */
  209. Object2D.types = new Map([[Object2D.prototype.type, Object2D]]);
  210. /**
  211. * Register a object type into the application. Associates the type string to the object constructor.
  212. *
  213. * Should be called for every new object class implemented if you want to be able to serialize and parse data.
  214. *
  215. * @static
  216. * @param {Function} constructor Object constructor.
  217. * @param {string} type Object type name.
  218. */
  219. Object2D.register = function(constructor, type)
  220. {
  221. Object2D.types.set(type, constructor);
  222. };
  223. /**
  224. * Check if a point in world coordinates intersects this object or its children and get a list of the objects intersected.
  225. *
  226. * @param {Vector2} point Point in world coordinates.
  227. * @param {Object2D[]} list List of objects intersected passed to children objects recursively.
  228. * @return {Object2D[]} List of object intersected by this point.
  229. */
  230. Object2D.prototype.getWorldPointIntersections = function(point, list)
  231. {
  232. if(list === undefined)
  233. {
  234. list = [];
  235. }
  236. // Calculate the pointer position in the object coordinates
  237. var localPoint = this.inverseGlobalMatrix.transformPoint(point);
  238. if(this.isInside(localPoint))
  239. {
  240. list.push(this);
  241. }
  242. // Iterate trough the children
  243. for(var i = 0; i < this.children.length; i++)
  244. {
  245. this.children[i].getWorldPointIntersections(point, list);
  246. }
  247. return list;
  248. };
  249. /**
  250. * Check if a point in world coordinates intersects this object or some of its children.
  251. *
  252. * @param {Vector2} point Point in world coordinates.
  253. * @param {boolean} recursive If set to true it will also check intersections with the object children.
  254. * @return {boolean} Returns true if the point in inside of the object.
  255. */
  256. Object2D.prototype.isWorldPointInside = function(point, recursive)
  257. {
  258. // Calculate the pointer position in the object coordinates
  259. var localPoint = this.inverseGlobalMatrix.transformPoint(point);
  260. if(this.isInside(localPoint))
  261. {
  262. return true;
  263. }
  264. // Iterate trough the children
  265. if(recursive)
  266. {
  267. for(var i = 0; i < this.children.length; i++)
  268. {
  269. if(this.children[i].isWorldPointInside(point, true))
  270. {
  271. return true;
  272. }
  273. }
  274. }
  275. return false;
  276. };
  277. /**
  278. * Destroy the object, removes it from the parent object.
  279. */
  280. Object2D.prototype.destroy = function()
  281. {
  282. if(this.parent !== null)
  283. {
  284. this.parent.remove(this);
  285. }
  286. };
  287. /**
  288. * Traverse the object tree and run a function for all objects.
  289. *
  290. * @param {Function} callback Callback function that receives the object as parameter.
  291. */
  292. Object2D.prototype.traverse = function(callback)
  293. {
  294. callback(this);
  295. for(var i = 0; i < this.children.length; i++)
  296. {
  297. this.children[i].traverse(callback);
  298. }
  299. };
  300. /**
  301. * Get a object from its children list by its UUID.
  302. *
  303. * @param {string} uuid UUID of the object to get.
  304. * @return {Object2D} The object that has the UUID specified, null if the object was not found.
  305. */
  306. Object2D.prototype.getChildByUUID = function(uuid)
  307. {
  308. var object = null;
  309. this.traverse(function(child)
  310. {
  311. if(child.uuid === uuid)
  312. {
  313. object = child;
  314. }
  315. });
  316. return object;
  317. };
  318. /**
  319. * Attach a children to this object.
  320. *
  321. * The object is set as children of this object and the transformations applied to this object are traversed to its children.
  322. *
  323. * @param {Object2D} object Object to attach to this object.
  324. */
  325. Object2D.prototype.add = function(object)
  326. {
  327. object.parent = this;
  328. object.level = this.level + 1;
  329. object.traverse(function(child)
  330. {
  331. if(child.onAdd !== null)
  332. {
  333. child.onAdd(this);
  334. }
  335. });
  336. this.children.push(object);
  337. };
  338. /**
  339. * Remove object from the children list.
  340. *
  341. * Resets the parent of the object to null and resets its level.
  342. *
  343. * @param {Object2D} children Object to be removed.
  344. */
  345. Object2D.prototype.remove = function(children)
  346. {
  347. var index = this.children.indexOf(children);
  348. if(index !== -1)
  349. {
  350. var object = this.children[index];
  351. object.parent = null;
  352. object.level = 0;
  353. object.traverse(function(child)
  354. {
  355. if(child.onRemove !== null)
  356. {
  357. child.onRemove(this);
  358. }
  359. });
  360. this.children.splice(index, 1)
  361. }
  362. };
  363. /**
  364. * Check if a point is inside of the object. Used by the renderer check for pointer collision (required for the object to properly process pointer events).
  365. *
  366. * Point should be in local object coordinates.
  367. *
  368. * To check if a point in world coordinates intersects the object the inverseGlobalMatrix should be applied to that point before calling this method.
  369. *
  370. * @param {Vector2} point Point in local object coordinates.
  371. * @return {boolean} True if the point is inside of the object.
  372. */
  373. Object2D.prototype.isInside = function(point)
  374. {
  375. return false;
  376. };
  377. /**
  378. * Update the transformation matrix of the object.
  379. *
  380. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  381. */
  382. Object2D.prototype.updateMatrix = function(context)
  383. {
  384. if(this.matrixAutoUpdate || this.matrixNeedsUpdate)
  385. {
  386. this.matrix.compose(this.position.x, this.position.y, this.scale.x, this.scale.y, this.origin.x, this.origin.y, this.rotation);
  387. this.globalMatrix.copy(this.matrix);
  388. if(this.parent !== null)
  389. {
  390. this.globalMatrix.premultiply(this.parent.globalMatrix);
  391. }
  392. this.inverseGlobalMatrix = this.globalMatrix.getInverse()
  393. this.matrixNeedsUpdate = false;
  394. }
  395. };
  396. /**
  397. * Apply the transform to the rendering context, it is assumed that the viewport transform is pre-applied to the context.
  398. *
  399. * This is called before style() and draw(). It can also be used for some pre-rendering logic.
  400. *
  401. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  402. * @param {Viewport} viewport Viewport applied to the canvas.
  403. * @param {Element} canvas DOM canvas element where the content is being drawn.
  404. * @param {Renderer} renderer Renderer object being used to draw the object into the canvas.
  405. */
  406. Object2D.prototype.transform = function(context, viewport, canvas, renderer)
  407. {
  408. this.globalMatrix.tranformContext(context);
  409. };
  410. /**
  411. * Style is called right before draw() it should not draw any content into the canvas, all context styling should be applied here (colors, fonts, etc).
  412. *
  413. * The draw() and style() methods can be useful for objects that share the same styling attributes but are drawing differently.
  414. *
  415. * Should be implemented by underlying classes.
  416. *
  417. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  418. * @param {Viewport} viewport Viewport used to view the canvas content.
  419. * @param {Element} canvas DOM canvas element where the content is being drawn.
  420. */
  421. Object2D.prototype.style = null; // function(context, viewport, canvas){};
  422. /**
  423. * Draw the object into the canvas, this is called transform() and style(), should be where the content is actually drawn into the canvas.
  424. *
  425. * Should be implemented by underlying classes.
  426. *
  427. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  428. * @param {Viewport} viewport Viewport used to view the canvas content.
  429. * @param {Element} canvas DOM canvas element where the content is being drawn.
  430. */
  431. Object2D.prototype.draw = null; // function(context, viewport, canvas){};
  432. /**
  433. * Callback method while the object is being dragged across the screen.
  434. *
  435. * By default is adds the delta value to the object position (making it follow the mouse movement).
  436. *
  437. * Delta is the movement of the pointer already translated into local object coordinates.
  438. *
  439. * To detect when the object drag stops the onPointerDragEnd() method can be used.
  440. *
  441. * @param {Pointer} pointer Pointer object that receives the user input.
  442. * @param {Viewport} viewport Viewport where the object is drawn.
  443. * @param {Vector2} delta Pointer movement diff in world space since the last frame.
  444. * @param {Vector2} positionWorld Position of the dragging pointer in world coordinates.
  445. */
  446. Object2D.prototype.onPointerDrag = function(pointer, viewport, delta, positionWorld)
  447. {
  448. this.position.add(delta);
  449. };
  450. /**
  451. * Callback method called when the pointer drag start after the button was pressed
  452. *
  453. * @param {Pointer} pointer Pointer object that receives the user input.
  454. * @param {Viewport} viewport Viewport where the object is drawn.
  455. */
  456. Object2D.prototype.onPointerDragStart = null;
  457. /**
  458. * Callback method called when the pointer drag ends after the button has been released.
  459. *
  460. * @param {Pointer} pointer Pointer object that receives the user input.
  461. * @param {Viewport} viewport Viewport where the object is drawn.
  462. */
  463. Object2D.prototype.onPointerDragEnd = null;
  464. /**
  465. * Method called when the object its added to a parent.
  466. *
  467. * @param {Object2D} parent Parent object were it was added.
  468. */
  469. Object2D.prototype.onAdd = null;
  470. /**
  471. * Method called when the object gets removed from its parent
  472. *
  473. * @param {Object2D} parent Parent object from were the object is being removed.
  474. */
  475. Object2D.prototype.onRemove = null;
  476. /**
  477. * Callback method called every time before the object is draw into the canvas.
  478. *
  479. * Should be used to run object logic, any preparation code, move the object, etc.
  480. *
  481. * This method is called for every object before rendering.
  482. */
  483. Object2D.prototype.onUpdate = null;
  484. /**
  485. * Callback method called when the pointer enters the object.
  486. *
  487. * It is not called while the pointer is inside of the object, just on the first time that the pointer enters the object for that use onPointerOver()
  488. *
  489. * @param {Pointer} pointer Pointer object that receives the user input.
  490. * @param {Viewport} viewport Viewport where the object is drawn.
  491. */
  492. Object2D.prototype.onPointerEnter = null;
  493. /**
  494. * Method called when the was inside of the object and leaves the object.
  495. *
  496. * @param {Pointer} pointer Pointer object that receives the user input.
  497. * @param {Viewport} viewport Viewport where the object is drawn.
  498. */
  499. Object2D.prototype.onPointerLeave = null;
  500. /**
  501. * Method while the pointer is over (inside) of the object.
  502. *
  503. * @param {Pointer} pointer Pointer object that receives the user input.
  504. * @param {Viewport} viewport Viewport where the object is drawn.
  505. */
  506. Object2D.prototype.onPointerOver = null;
  507. /**
  508. * Method called while the pointer button is pressed.
  509. *
  510. * @param {Pointer} pointer Pointer object that receives the user input.
  511. * @param {Viewport} viewport Viewport where the object is drawn.
  512. */
  513. Object2D.prototype.onButtonPressed = null;
  514. /**
  515. * Method called while the pointer button is double clicked.
  516. *
  517. * @param {Pointer} pointer Pointer object that receives the user input.
  518. * @param {Viewport} viewport Viewport where the object is drawn.
  519. */
  520. Object2D.prototype.onDoubleClick = null;
  521. /**
  522. * Callback method called when the pointer button is pressed down (single time).
  523. *
  524. * @param {Pointer} pointer Pointer object that receives the user input.
  525. * @param {Viewport} viewport Viewport where the object is drawn.
  526. */
  527. Object2D.prototype.onButtonDown = null;
  528. /**
  529. * Method called when the pointer button is released (single time).
  530. *
  531. * @param {Pointer} pointer Pointer object that receives the user input.
  532. * @param {Viewport} viewport Viewport where the object is drawn.
  533. */
  534. Object2D.prototype.onButtonUp = null;
  535. /**
  536. * Serialize the object data into a JSON object. That can be written into a file, sent using HTTP request etc.
  537. *
  538. * All required attributes to recreate the object in its current state should be stored. Relations between children should be stored by their UUID only.
  539. *
  540. * Data has to be parsed back into a usable object.
  541. *
  542. * @param {boolean} recursive If set false the children list is not serialized, otherwise all children are serialized.
  543. * @return {Object} Serialized object data.
  544. */
  545. Object2D.prototype.serialize = function(recursive)
  546. {
  547. var data = {
  548. uuid: this.uuid,
  549. type: this.type,
  550. position: this.position.toArray(),
  551. origin: this.origin.toArray(),
  552. scale: this.scale.toArray(),
  553. rotation: this.rotation,
  554. visible: this.visible,
  555. layer: this.layer,
  556. matrix: this.matrix.m,
  557. globalMatrix: this.globalMatrix.m,
  558. inverseGlobalMatrix: this.inverseGlobalMatrix.m,
  559. matrixAutoUpdate: this.matrixAutoUpdate,
  560. draggable: this.draggable,
  561. pointerEvents: this.pointerEvents,
  562. ignoreViewport: this.ignoreViewport,
  563. saveContextState: this.saveContextState,
  564. restoreContextState: this.restoreContextState,
  565. children: [],
  566. masks: []
  567. };
  568. if(recursive !== false)
  569. {
  570. for(var i = 0; i < this.children.length; i++)
  571. {
  572. if(this.children[i].serializable)
  573. {
  574. data.children.push(this.children[i].serialize());
  575. }
  576. }
  577. }
  578. for(var i = 0; i < this.masks.length; i++)
  579. {
  580. data.masks.push(this.masks[i].uuid);
  581. }
  582. return data;
  583. };
  584. /**
  585. * Parse serialized object data and fill the object attributes.
  586. *
  587. * Implementations of this method should only load the attributes added to the structure, the based method already loads common attributes.
  588. *
  589. * Dont forget to register object types using the Object2D.register() method.
  590. *
  591. * @param {Object} data Object data loaded from JSON.
  592. * @param {Object2D} root Root object being loaded can be used to get references to other objects.
  593. */
  594. Object2D.prototype.parse = function(data, root)
  595. {
  596. this.uuid = data.uuid;
  597. this.position.fromArray(data.position);
  598. this.origin.fromArray(data.origin);
  599. this.scale.fromArray(data.scale);
  600. this.rotation = data.rotation;
  601. this.visible = data.visible;
  602. this.layer = data.layer;
  603. this.matrix = new Matrix(data.matrix);
  604. this.globalMatrix = new Matrix(data.globalMatrix);
  605. this.inverseGlobalMatrix = new Matrix(data.inverseGlobalMatrix);
  606. this.matrixAutoUpdate = data.matrixAutoUpdate;
  607. this.draggable = data.draggable;
  608. this.pointerEvents = data.pointerEvents;
  609. this.ignoreViewport = data.ignoreViewport;
  610. this.saveContextState = data.saveContextState;
  611. this.restoreContextState = data.restoreContextState;
  612. for(var i = 0; i < this.masks.length; i++)
  613. {
  614. data.masks.push(root.getChildByUUID(data.masks[i]));
  615. }
  616. };
  617. /**
  618. * Create objects from serialized object data into the proper data structures.
  619. *
  620. * All objects should implement serialization methods to serialize and load data properly.
  621. *
  622. * First all objects instances are created to ensure that object trying to get references to other object can have the data accessible, only then the parse method is called.
  623. *
  624. * @static
  625. * @param {Object} data Object data loaded from JSON.
  626. * @return {Object2D} Parsed object data.
  627. */
  628. Object2D.parse = function(data)
  629. {
  630. // List of objects created stored as pairs of object, data to be later parsed.
  631. var objects = [];
  632. // Parse all objects from the data object recursively and create the correct instances.
  633. function createObjectInstances(data)
  634. {
  635. if(!Object2D.types.has(data.type))
  636. {
  637. throw new Error("Object type " + data.type + " unknown. Cannot parse data.");
  638. }
  639. var Constructor = Object2D.types.get(data.type);
  640. var object = new Constructor();
  641. object.uuid = data.uuid;
  642. objects.push({object: object, data: data});
  643. for(var i = 0; i < data.children.length; i++)
  644. {
  645. object.add(createObjectInstances(data.children[i]));
  646. }
  647. return object;
  648. }
  649. var root = createObjectInstances(data);
  650. // Parse objects data
  651. for(var i = 0; i < objects.length; i++)
  652. {
  653. objects[i].object.parse(objects[i].data, root);
  654. }
  655. return root;
  656. };
  657. export {Object2D};