pointerDragBehavior.ts 22 KB

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