pointerDragBehavior.ts 21 KB

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