babylon.pointerDragBehavior.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. module BABYLON {
  2. /**
  3. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  4. */
  5. export class PointerDragBehavior implements Behavior<Mesh> {
  6. private _attachedNode: Node;
  7. private _dragPlane: Mesh;
  8. private _scene:Scene;
  9. private _pointerObserver:Nullable<Observer<PointerInfo>>;
  10. private static _planeScene:Scene;
  11. private _draggingID = -1;
  12. // Debug mode will display drag planes to help visualize behavior
  13. private _debugMode = false;
  14. private _maxDragAngle = Math.PI/5;
  15. /**
  16. * Fires each time the attached mesh is dragged with the pointer
  17. * delta between last drag position and current drag position in world space
  18. * dragDistance along the drag axis
  19. * dragPlaneNormal normal of the current drag plane used during the drag
  20. * dragPlanePoint in world space where the drag intersects the drag plane
  21. */
  22. public onDragObservable = new Observable<{delta:Vector3, dragPlanePoint:Vector3, dragPlaneNormal:Vector3, dragDistance:number}>()
  23. /**
  24. * Fires each time a drag begins (eg. mouse down on mesh)
  25. */
  26. public onDragStartObservable = new Observable<{dragPlanePoint:Vector3}>()
  27. /**
  28. * Fires each time a drag ends (eg. mouse release after drag)
  29. */
  30. public onDragEndObservable = new Observable<{dragPlanePoint:Vector3}>()
  31. /**
  32. * If the attached mesh should be moved when dragged
  33. */
  34. public moveAttached = true;
  35. /**
  36. * Mesh with the position where the drag plane should be placed
  37. */
  38. public _dragPlaneParent:Nullable<Mesh>=null;
  39. /**
  40. * If the drag behavior will react to drag events
  41. */
  42. public enabled = true;
  43. /**
  44. * Creates a pointer drag behavior that can be attached to a mesh
  45. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  46. */
  47. constructor(private options:{dragAxis?:Vector3, dragPlaneNormal?:Vector3}){
  48. var optionCount = 0;
  49. if(options === undefined){
  50. options = {}
  51. }
  52. if(options.dragAxis){
  53. optionCount++;
  54. }
  55. if(options.dragPlaneNormal){
  56. optionCount++;
  57. }
  58. if(optionCount > 1){
  59. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  60. }
  61. }
  62. /**
  63. * The name of the behavior
  64. */
  65. public get name(): string {
  66. return "PointerDrag";
  67. }
  68. /**
  69. * Initializes the behavior
  70. */
  71. public init() {}
  72. /**
  73. * Attaches the drag behavior the passed in mesh
  74. * @param ownerNode The mesh that will be dragged around once attached
  75. */
  76. public attach(ownerNode: Mesh): void {
  77. this._scene = ownerNode.getScene();
  78. this._attachedNode = ownerNode;
  79. // Initialize drag plane to not interfere with existing scene
  80. if(!PointerDragBehavior._planeScene){
  81. if(this._debugMode){
  82. PointerDragBehavior._planeScene = this._scene;
  83. }else{
  84. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  85. this._scene.getEngine().scenes.pop();
  86. }
  87. }
  88. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89. // State of the drag
  90. var dragging = false;
  91. var lastPosition = new BABYLON.Vector3(0,0,0);
  92. var delta = new BABYLON.Vector3(0,0,0);
  93. var dragLength = 0;
  94. var pickPredicate = (m:AbstractMesh)=>{
  95. return this._attachedNode == m || m.isDescendantOf(this._attachedNode)
  96. }
  97. this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo, eventState)=>{
  98. if(!this.enabled){
  99. return;
  100. }
  101. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  102. if(!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)){
  103. this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  104. var pickedPoint = this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  105. if(pickedPoint){
  106. dragging = true;
  107. this._draggingID = (<PointerEvent>pointerInfo.event).pointerId;
  108. lastPosition.copyFrom(pickedPoint);
  109. this.onDragStartObservable.notifyObservers({dragPlanePoint: pickedPoint});
  110. }
  111. }
  112. }else if(pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP){
  113. if(this._draggingID == (<PointerEvent>pointerInfo.event).pointerId){
  114. dragging = false;
  115. this._draggingID = -1;
  116. this.onDragEndObservable.notifyObservers({dragPlanePoint: lastPosition});
  117. }
  118. }else if(pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE){
  119. if(this._draggingID == (<PointerEvent>pointerInfo.event).pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray){
  120. var pickedPoint = this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  121. // Get angle between drag plane and ray. Only update the drag plane at non steep angles to avoid jumps in delta position
  122. var angle = Math.acos(Vector3.Dot(this._dragPlane.forward, pointerInfo.pickInfo.ray.direction));
  123. if(angle < this._maxDragAngle){
  124. this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  125. }
  126. if (pickedPoint) {
  127. // depending on the drag mode option drag accordingly
  128. if(this.options.dragAxis){
  129. // Convert local drag axis to world
  130. var worldDragAxis = Vector3.TransformCoordinates(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix());
  131. // Project delta drag from the drag plane onto the drag axis
  132. dragLength = BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), worldDragAxis)
  133. worldDragAxis.scaleToRef(dragLength, delta);
  134. }else{
  135. dragLength = delta.length();
  136. pickedPoint.subtractToRef(lastPosition, delta);
  137. }
  138. if(this.moveAttached){
  139. (<Mesh>this._attachedNode).position.addInPlace(delta);
  140. }
  141. this.onDragObservable.notifyObservers({dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward});
  142. lastPosition.copyFrom(pickedPoint);
  143. }
  144. }
  145. }
  146. });
  147. }
  148. private _pickWithRayOnDragPlane(ray:Nullable<Ray>){
  149. if(!ray){
  150. return null;
  151. }
  152. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, (m)=>{return m == this._dragPlane})
  153. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  154. return pickResult.pickedPoint;
  155. }else{
  156. return null;
  157. }
  158. }
  159. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  160. private _updateDragPlanePosition(ray:Ray){
  161. var pointA = this._dragPlaneParent ? this._dragPlaneParent.absolutePosition : (<Mesh>this._attachedNode).absolutePosition;
  162. if(this.options.dragAxis){
  163. var localAxis = Vector3.TransformCoordinates(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix());
  164. // Calculate plane normal in direction of camera but perpendicular to drag axis
  165. var pointB = pointA.add(localAxis); // towards drag axis
  166. var pointC = pointA.add(ray.origin.subtract(pointA).normalize()); // towards camera
  167. // Get perpendicular line from direction to camera and drag axis
  168. var lineA = pointB.subtract(pointA);
  169. var lineB = pointC.subtract(pointA);
  170. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  171. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  172. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  173. this._dragPlane.position.copyFrom(pointA);
  174. this._dragPlane.lookAt(pointA.subtract(norm));
  175. }else if(this.options.dragPlaneNormal){
  176. this._dragPlane.position.copyFrom(pointA);
  177. this._dragPlane.lookAt(pointA.subtract(this.options.dragPlaneNormal));
  178. }else{
  179. this._dragPlane.position.copyFrom(pointA);
  180. this._dragPlane.lookAt(ray.origin);
  181. }
  182. this._dragPlane.computeWorldMatrix(true);
  183. }
  184. /**
  185. * Detaches the behavior from the mesh
  186. */
  187. public detach(): void {
  188. if(this._pointerObserver){
  189. this._scene.onPointerObservable.remove(this._pointerObserver);
  190. }
  191. }
  192. }
  193. }