pointerDragBehavior.ts 20 KB

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