babylon.pointerDragBehavior.ts 13 KB

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