babylon.pointerDragBehavior.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 static _AnyMouseID = -2;
  7. private _attachedNode: Mesh;
  8. private _dragPlane: Mesh;
  9. private _scene:Scene;
  10. private _pointerObserver:Nullable<Observer<PointerInfo>>;
  11. private _beforeRenderObserver:Nullable<Observer<Scene>>;
  12. private static _planeScene:Scene;
  13. /**
  14. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  15. */
  16. public maxDragAngle = 0;
  17. /**
  18. * @hidden
  19. */
  20. public _useAlternatePickedPointAboveMaxDragAngle = false;
  21. /**
  22. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  23. */
  24. public currentDraggingPointerID = -1;
  25. /**
  26. * The last position where the pointer hit the drag plane in world space
  27. */
  28. public lastDragPosition:Vector3;
  29. /**
  30. * If the behavior is currently in a dragging state
  31. */
  32. public dragging = false;
  33. /**
  34. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  35. */
  36. public dragDeltaRatio = 0.2;
  37. /**
  38. * If the drag plane orientation should be updated during the dragging (Default: true)
  39. */
  40. public updateDragPlane = true;
  41. // Debug mode will display drag planes to help visualize behavior
  42. private _debugMode = false;
  43. private _moving = false;
  44. /**
  45. * Fires each time the attached mesh is dragged with the pointer
  46. * * delta between last drag position and current drag position in world space
  47. * * dragDistance along the drag axis
  48. * * dragPlaneNormal normal of the current drag plane used during the drag
  49. * * dragPlanePoint in world space where the drag intersects the drag plane
  50. */
  51. public onDragObservable = new Observable<{delta:Vector3, dragPlanePoint:Vector3, dragPlaneNormal:Vector3, dragDistance:number, pointerId:number}>()
  52. /**
  53. * Fires each time a drag begins (eg. mouse down on mesh)
  54. */
  55. public onDragStartObservable = new Observable<{dragPlanePoint:Vector3, pointerId:number}>()
  56. /**
  57. * Fires each time a drag ends (eg. mouse release after drag)
  58. */
  59. public onDragEndObservable = new Observable<{dragPlanePoint:Vector3, pointerId:number}>()
  60. /**
  61. * If the attached mesh should be moved when dragged
  62. */
  63. public moveAttached = true;
  64. /**
  65. * If the drag behavior will react to drag events (Default: true)
  66. */
  67. public enabled = true;
  68. /**
  69. * If camera controls should be detached during the drag
  70. */
  71. public detachCameraControls = true;
  72. /**
  73. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  74. */
  75. public useObjectOrienationForDragging = true;
  76. private _options:{dragAxis?:Vector3, dragPlaneNormal?:Vector3};
  77. /**
  78. * Creates a pointer drag behavior that can be attached to a mesh
  79. * @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)
  80. */
  81. constructor(options?:{dragAxis?:Vector3, dragPlaneNormal?:Vector3}){
  82. this._options = options ? options : {};
  83. var optionCount = 0;
  84. if(this._options.dragAxis){
  85. optionCount++;
  86. }
  87. if(this._options.dragPlaneNormal){
  88. optionCount++;
  89. }
  90. if(optionCount > 1){
  91. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  92. }
  93. }
  94. /**
  95. * The name of the behavior
  96. */
  97. public get name(): string {
  98. return "PointerDrag";
  99. }
  100. /**
  101. * Initializes the behavior
  102. */
  103. public init() {}
  104. private _tmpVector = new Vector3(0,0,0);
  105. private _alternatePickedPoint = new Vector3(0,0,0);
  106. private _worldDragAxis = new Vector3(0,0,0);
  107. private _targetPosition = new BABYLON.Vector3(0,0,0);
  108. private _attachedElement:Nullable<HTMLElement> = null;
  109. /**
  110. * Attaches the drag behavior the passed in mesh
  111. * @param ownerNode The mesh that will be dragged around once attached
  112. */
  113. public attach(ownerNode: Mesh): void {
  114. this._scene = ownerNode.getScene();
  115. this._attachedNode = ownerNode;
  116. // Initialize drag plane to not interfere with existing scene
  117. if(!PointerDragBehavior._planeScene){
  118. if(this._debugMode){
  119. PointerDragBehavior._planeScene = this._scene;
  120. }else{
  121. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  122. PointerDragBehavior._planeScene.detachControl();
  123. this._scene.getEngine().scenes.pop();
  124. this._scene.onDisposeObservable.addOnce(()=>{
  125. PointerDragBehavior._planeScene.dispose();
  126. (<any>PointerDragBehavior._planeScene) = null;
  127. })
  128. }
  129. }
  130. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  131. // State of the drag
  132. this.lastDragPosition = new BABYLON.Vector3(0,0,0);
  133. var pickPredicate = (m:AbstractMesh)=>{
  134. return this._attachedNode == m || m.isDescendantOf(this._attachedNode)
  135. }
  136. this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo, eventState)=>{
  137. if(!this.enabled){
  138. return;
  139. }
  140. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  141. if(!this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)){
  142. this._startDrag((<PointerEvent>pointerInfo.event).pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  143. }
  144. }else if(pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP){
  145. if(this.currentDraggingPointerID == (<PointerEvent>pointerInfo.event).pointerId){
  146. this.releaseDrag();
  147. }
  148. }else if(pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE){
  149. var pointerId = (<PointerEvent>pointerInfo.event).pointerId;
  150. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  151. if(this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && (<PointerEvent>pointerInfo.event).pointerType == "mouse"){
  152. if(this._lastPointerRay[this.currentDraggingPointerID]){
  153. this._lastPointerRay[pointerId] = this._lastPointerRay[this.currentDraggingPointerID];
  154. delete this._lastPointerRay[this.currentDraggingPointerID];
  155. }
  156. this.currentDraggingPointerID = pointerId;
  157. }
  158. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  159. if(!this._lastPointerRay[pointerId]){
  160. this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  161. }
  162. if(pointerInfo.pickInfo && pointerInfo.pickInfo.ray){
  163. this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  164. this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  165. if(this.currentDraggingPointerID == pointerId && this.dragging){
  166. this._moveDrag(pointerInfo.pickInfo.ray);
  167. }
  168. }
  169. }
  170. });
  171. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(()=>{
  172. if(this._moving && this.moveAttached){
  173. BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  174. // Slowly move mesh to avoid jitter
  175. this._targetPosition.subtractToRef((this._attachedNode).absolutePosition, this._tmpVector);
  176. this._tmpVector.scaleInPlace(this.dragDeltaRatio);
  177. (this._attachedNode).getAbsolutePosition().addToRef(this._tmpVector, this._tmpVector);
  178. (this._attachedNode).setAbsolutePosition(this._tmpVector);
  179. BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  180. }
  181. });
  182. }
  183. /**
  184. * Force relase the drag action by code.
  185. */
  186. public releaseDrag(){
  187. this.dragging = false;
  188. this.onDragEndObservable.notifyObservers({dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID});
  189. this.currentDraggingPointerID = -1;
  190. this._moving = false;
  191. // Reattach camera controls
  192. if(this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera){
  193. this._scene.activeCamera.attachControl(this._attachedElement, true);
  194. }
  195. }
  196. private _startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  197. private _lastPointerRay:{[key: number]: Ray} = {};
  198. /**
  199. * Simulates the start of a pointer drag event on the behavior
  200. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  201. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  202. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  203. */
  204. public startDrag(pointerId:number = PointerDragBehavior._AnyMouseID, fromRay?:Ray, startPickedPoint?:Vector3){
  205. this._startDrag(pointerId, fromRay, startPickedPoint);
  206. var lastRay = this._lastPointerRay[pointerId];
  207. if(pointerId === PointerDragBehavior._AnyMouseID){
  208. lastRay = this._lastPointerRay[<any>Object.keys(this._lastPointerRay)[0]];
  209. }
  210. if(lastRay){
  211. // if there was a last pointer ray drag the object there
  212. this._moveDrag(lastRay);
  213. }
  214. }
  215. private _startDrag(pointerId:number, fromRay?:Ray, startPickedPoint?:Vector3){
  216. if(!this._scene.activeCamera || this.dragging || !this._attachedNode){
  217. return;
  218. }
  219. BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  220. // Create start ray from the camera to the object
  221. if(fromRay){
  222. this._startDragRay.direction.copyFrom(fromRay.direction)
  223. this._startDragRay.origin.copyFrom(fromRay.origin)
  224. }else{
  225. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  226. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  227. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  228. }
  229. this._updateDragPlanePosition(this._startDragRay, startPickedPoint?startPickedPoint:this._tmpVector);
  230. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  231. if(pickedPoint){
  232. this.dragging = true;
  233. this.currentDraggingPointerID = pointerId;
  234. this.lastDragPosition.copyFrom(pickedPoint);
  235. this.onDragStartObservable.notifyObservers({dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID});
  236. this._targetPosition.copyFrom((this._attachedNode).absolutePosition)
  237. // Detatch camera controls
  238. if(this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera){
  239. if(this._scene.activeCamera.inputs.attachedElement){
  240. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  241. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  242. }else{
  243. this._attachedElement = null;
  244. }
  245. }
  246. }
  247. BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  248. }
  249. private _dragDelta = new BABYLON.Vector3();
  250. private _moveDrag(ray:Ray){
  251. this._moving = true;
  252. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  253. if (pickedPoint) {
  254. if(this.updateDragPlane){
  255. this._updateDragPlanePosition(ray, pickedPoint);
  256. }
  257. var dragLength = 0;
  258. // depending on the drag mode option drag accordingly
  259. if(this._options.dragAxis){
  260. // Convert local drag axis to world
  261. Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  262. // Project delta drag from the drag plane onto the drag axis
  263. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  264. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis)
  265. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  266. }else{
  267. dragLength = this._dragDelta.length();
  268. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  269. }
  270. this._targetPosition.addInPlace(this._dragDelta);
  271. this.onDragObservable.notifyObservers({dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID});
  272. this.lastDragPosition.copyFrom(pickedPoint);
  273. }
  274. }
  275. private _pickWithRayOnDragPlane(ray:Nullable<Ray>){
  276. if(!ray){
  277. return null;
  278. }
  279. // Calculate angle between plane normal and ray
  280. var angle = Math.acos(Vector3.Dot(this._dragPlane.forward, ray.direction));
  281. // Correct if ray is casted from oposite side
  282. if(angle > Math.PI/2){
  283. angle = Math.PI - angle;
  284. }
  285. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  286. if(this.maxDragAngle > 0 && angle > this.maxDragAngle){
  287. if(this._useAlternatePickedPointAboveMaxDragAngle){
  288. // Invert ray direction along the towards object axis
  289. this._tmpVector.copyFrom(ray.direction);
  290. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  291. this._alternatePickedPoint.normalize();
  292. this._alternatePickedPoint.scaleInPlace(-2*Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  293. this._tmpVector.addInPlace(this._alternatePickedPoint);
  294. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  295. var dot = Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  296. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  297. this._alternatePickedPoint.addInPlace(this._tmpVector);
  298. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  299. return this._alternatePickedPoint
  300. }else{
  301. return null;
  302. }
  303. }
  304. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, (m)=>{return m == this._dragPlane})
  305. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  306. return pickResult.pickedPoint;
  307. }else{
  308. return null;
  309. }
  310. }
  311. // Variables to avoid instantiation in the below method
  312. private _pointA = new Vector3(0,0,0);
  313. private _pointB = new Vector3(0,0,0);
  314. private _pointC = new Vector3(0,0,0);
  315. private _lineA = new Vector3(0,0,0);
  316. private _lineB = new Vector3(0,0,0);
  317. private _localAxis = new Vector3(0,0,0);
  318. private _lookAt = new Vector3(0,0,0);
  319. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  320. private _updateDragPlanePosition(ray:Ray, dragPlanePosition:Vector3){
  321. this._pointA.copyFrom(dragPlanePosition);
  322. if(this._options.dragAxis){
  323. this.useObjectOrienationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  324. // Calculate plane normal in direction of camera but perpendicular to drag axis
  325. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  326. ray.origin.subtractToRef(this._pointA, this._pointC)
  327. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  328. // Get perpendicular line from direction to camera and drag axis
  329. this._pointB.subtractToRef(this._pointA, this._lineA);
  330. this._pointC.subtractToRef(this._pointA, this._lineB);
  331. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  332. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  333. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  334. this._lookAt.normalize();
  335. this._dragPlane.position.copyFrom(this._pointA);
  336. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  337. this._dragPlane.lookAt(this._lookAt);
  338. }else if(this._options.dragPlaneNormal){
  339. this.useObjectOrienationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  340. this._dragPlane.position.copyFrom(this._pointA);
  341. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  342. this._dragPlane.lookAt(this._lookAt);
  343. }else{
  344. this._dragPlane.position.copyFrom(this._pointA);
  345. this._dragPlane.lookAt(ray.origin);
  346. }
  347. this._dragPlane.computeWorldMatrix(true);
  348. }
  349. /**
  350. * Detaches the behavior from the mesh
  351. */
  352. public detach(): void {
  353. if(this._pointerObserver){
  354. this._scene.onPointerObservable.remove(this._pointerObserver);
  355. }
  356. if(this._beforeRenderObserver){
  357. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  358. }
  359. }
  360. }
  361. }