Selection.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /**
  2. * Selection.js
  3. *
  4. * @author realor
  5. */
  6. import { Application } from '../ui/Application.js'
  7. import * as THREE from '../lib/three.module.js'
  8. class Selection {
  9. constructor(application, notify = false) {
  10. this.application = application
  11. this._objects = new Set()
  12. this.notify = notify
  13. }
  14. get iterator() {
  15. return this._objects.values()
  16. }
  17. get object() {
  18. // returns the first object in selection
  19. let objects = this._objects
  20. return objects.size === 0 ? null : objects.values().next().value
  21. }
  22. get objects() {
  23. return Array.from(this._objects)
  24. }
  25. get roots() {
  26. // returns the top selected objects
  27. let roots = []
  28. let iterator = this._objects.values()
  29. let item = iterator.next()
  30. while (!item.done) {
  31. let object = item.value
  32. if (this.isRoot(object)) {
  33. roots.push(object)
  34. }
  35. item = iterator.next()
  36. }
  37. return roots
  38. }
  39. contains(object) {
  40. return this._objects.has(object)
  41. }
  42. isRoot(object) {
  43. // is root if object is selected but no ancestor is selected
  44. let root = this._objects.has(object)
  45. let parent = object.parent
  46. while (parent && root) {
  47. root = !this._objects.has(parent)
  48. parent = parent.parent
  49. }
  50. return root
  51. }
  52. isEmpty() {
  53. return this._objects.size === 0
  54. }
  55. get size() {
  56. return this._objects.size
  57. }
  58. set(...objects) {
  59. this._objects.clear()
  60. this._add(objects)
  61. if (this.notify) this._notifyListeners()
  62. }
  63. add(...objects) {
  64. this._add(objects)
  65. if (this.notify) this._notifyListeners()
  66. }
  67. remove(...objects) {
  68. let size = this._objects.size
  69. for (let object of objects) {
  70. this._objects.delete(object)
  71. }
  72. if (size !== this._objects.size) {
  73. if (this.notify) this._notifyListeners()
  74. }
  75. }
  76. clear() {
  77. if (this._objects.size > 0) {
  78. this._objects.clear()
  79. if (this.notify) this._notifyListeners()
  80. }
  81. }
  82. _add(objects) {
  83. for (let i = 0; i < objects.length; i++) {
  84. let object = objects[i]
  85. if (object instanceof THREE.Object3D) {
  86. this._objects.add(object)
  87. }
  88. }
  89. }
  90. _notifyListeners() {
  91. let selectionEvent = { type: 'changed', objects: this.objects }
  92. this.application.notifyEventListeners('selection', selectionEvent)
  93. }
  94. }
  95. export { Selection }