physicsHelper.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. import { Nullable } from "../types";
  2. import { Logger } from "../Misc/logger";
  3. import { Vector3 } from "../Maths/math";
  4. import { AbstractMesh } from "../Meshes/abstractMesh";
  5. import { Mesh } from "../Meshes/mesh";
  6. import { SphereBuilder } from "../Meshes/Builders/sphereBuilder";
  7. import { CylinderBuilder } from "../Meshes/Builders/cylinderBuilder";
  8. import { Ray } from "../Culling/ray";
  9. import { Scene } from "../scene";
  10. import { IPhysicsEngine } from "./IPhysicsEngine";
  11. import { PhysicsEngine } from "./physicsEngine";
  12. import { PhysicsImpostor } from "./physicsImpostor";
  13. /**
  14. * A helper for physics simulations
  15. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  16. */
  17. export class PhysicsHelper {
  18. private _scene: Scene;
  19. private _physicsEngine: Nullable<IPhysicsEngine>;
  20. /**
  21. * Initializes the Physics helper
  22. * @param scene Babylon.js scene
  23. */
  24. constructor(scene: Scene) {
  25. this._scene = scene;
  26. this._physicsEngine = this._scene.getPhysicsEngine();
  27. if (!this._physicsEngine) {
  28. Logger.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  29. return;
  30. }
  31. }
  32. /**
  33. * Applies a radial explosion impulse
  34. * @param origin the origin of the explosion
  35. * @param radiusOrEventOptions the radius or the options of radial explosion
  36. * @param strength the explosion strength
  37. * @param falloff possible options: Constant & Linear. Defaults to Constant
  38. * @returns A physics radial explosion event, or null
  39. */
  40. public applyRadialExplosionImpulse(origin: Vector3, radiusOrEventOptions: number | PhysicsRadialExplosionEventOptions, strength?: number, falloff?: PhysicsRadialImpulseFalloff): Nullable<PhysicsRadialExplosionEvent> {
  41. if (!this._physicsEngine) {
  42. Logger.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  43. return null;
  44. }
  45. var impostors = this._physicsEngine.getImpostors();
  46. if (impostors.length === 0) {
  47. return null;
  48. }
  49. if (typeof radiusOrEventOptions === 'number') {
  50. radiusOrEventOptions = new PhysicsRadialExplosionEventOptions();
  51. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  52. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  53. radiusOrEventOptions.falloff = falloff || radiusOrEventOptions.falloff;
  54. }
  55. var event = new PhysicsRadialExplosionEvent(this, this._scene, radiusOrEventOptions);
  56. impostors.forEach((impostor) => {
  57. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin);
  58. if (!impostorForceAndContactPoint) {
  59. return;
  60. }
  61. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  62. });
  63. event.dispose(false);
  64. return event;
  65. }
  66. /**
  67. * Applies a radial explosion force
  68. * @param origin the origin of the explosion
  69. * @param radiusOrEventOptions the radius or the options of radial explosion
  70. * @param strength the explosion strength
  71. * @param falloff possible options: Constant & Linear. Defaults to Constant
  72. * @returns A physics radial explosion event, or null
  73. */
  74. public applyRadialExplosionForce(origin: Vector3, radiusOrEventOptions: number | PhysicsRadialExplosionEventOptions, strength?: number, falloff?: PhysicsRadialImpulseFalloff): Nullable<PhysicsRadialExplosionEvent> {
  75. if (!this._physicsEngine) {
  76. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77. return null;
  78. }
  79. var impostors = this._physicsEngine.getImpostors();
  80. if (impostors.length === 0) {
  81. return null;
  82. }
  83. if (typeof radiusOrEventOptions === 'number') {
  84. radiusOrEventOptions = new PhysicsRadialExplosionEventOptions();
  85. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  86. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  87. radiusOrEventOptions.falloff = falloff || radiusOrEventOptions.falloff;
  88. }
  89. var event = new PhysicsRadialExplosionEvent(this, this._scene, radiusOrEventOptions);
  90. impostors.forEach((impostor) => {
  91. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin);
  92. if (!impostorForceAndContactPoint) {
  93. return;
  94. }
  95. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96. });
  97. event.dispose(false);
  98. return event;
  99. }
  100. /**
  101. * Creates a gravitational field
  102. * @param origin the origin of the explosion
  103. * @param radiusOrEventOptions the radius or the options of radial explosion
  104. * @param strength the explosion strength
  105. * @param falloff possible options: Constant & Linear. Defaults to Constant
  106. * @returns A physics gravitational field event, or null
  107. */
  108. public gravitationalField(origin: Vector3, radiusOrEventOptions: number | PhysicsRadialExplosionEventOptions, strength?: number, falloff?: PhysicsRadialImpulseFalloff): Nullable<PhysicsGravitationalFieldEvent> {
  109. if (!this._physicsEngine) {
  110. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  111. return null;
  112. }
  113. var impostors = this._physicsEngine.getImpostors();
  114. if (impostors.length === 0) {
  115. return null;
  116. }
  117. if (typeof radiusOrEventOptions === 'number') {
  118. radiusOrEventOptions = new PhysicsRadialExplosionEventOptions();
  119. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  120. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  121. radiusOrEventOptions.falloff = falloff || radiusOrEventOptions.falloff;
  122. }
  123. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radiusOrEventOptions);
  124. event.dispose(false);
  125. return event;
  126. }
  127. /**
  128. * Creates a physics updraft event
  129. * @param origin the origin of the updraft
  130. * @param radiusOrEventOptions the radius or the options of the updraft
  131. * @param strength the strength of the updraft
  132. * @param height the height of the updraft
  133. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  134. * @returns A physics updraft event, or null
  135. */
  136. public updraft(origin: Vector3, radiusOrEventOptions: number | PhysicsUpdraftEventOptions, strength?: number, height?: number, updraftMode?: PhysicsUpdraftMode): Nullable<PhysicsUpdraftEvent> {
  137. if (!this._physicsEngine) {
  138. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  139. return null;
  140. }
  141. if (this._physicsEngine.getImpostors().length === 0) {
  142. return null;
  143. }
  144. if (typeof radiusOrEventOptions === 'number') {
  145. radiusOrEventOptions = new PhysicsUpdraftEventOptions();
  146. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  147. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  148. radiusOrEventOptions.height = height || radiusOrEventOptions.height;
  149. radiusOrEventOptions.updraftMode = updraftMode || radiusOrEventOptions.updraftMode;
  150. }
  151. var event = new PhysicsUpdraftEvent(this, this._scene, origin, radiusOrEventOptions);
  152. event.dispose(false);
  153. return event;
  154. }
  155. /**
  156. * Creates a physics vortex event
  157. * @param origin the of the vortex
  158. * @param radiusOrEventOptions the radius or the options of the vortex
  159. * @param strength the strength of the vortex
  160. * @param height the height of the vortex
  161. * @returns a Physics vortex event, or null
  162. * A physics vortex event or null
  163. */
  164. public vortex(origin: Vector3, radiusOrEventOptions: number | PhysicsVortexEventOptions, strength?: number, height?: number): Nullable<PhysicsVortexEvent> {
  165. if (!this._physicsEngine) {
  166. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  167. return null;
  168. }
  169. if (this._physicsEngine.getImpostors().length === 0) {
  170. return null;
  171. }
  172. if (typeof radiusOrEventOptions === 'number') {
  173. radiusOrEventOptions = new PhysicsVortexEventOptions();
  174. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  175. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  176. radiusOrEventOptions.height = height || radiusOrEventOptions.height;
  177. }
  178. var event = new PhysicsVortexEvent(this, this._scene, origin, radiusOrEventOptions);
  179. event.dispose(false);
  180. return event;
  181. }
  182. }
  183. /**
  184. * Represents a physics radial explosion event
  185. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  186. */
  187. class PhysicsRadialExplosionEvent {
  188. private _physicsEngine: PhysicsEngine;
  189. private _sphere: Mesh; // create a sphere, so we can get the intersecting meshes inside
  190. private _dataFetched: boolean = false; // check if the data has been fetched. If not, do cleanup
  191. /**
  192. * Initializes a radial explosioin event
  193. * @param _physicsHelper A physics helper
  194. * @param _scene BabylonJS scene
  195. * @param _options The options for the vortex event
  196. */
  197. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _options: PhysicsRadialExplosionEventOptions) {
  198. this._options = {...(new PhysicsRadialExplosionEventOptions()), ...this._options};
  199. this._physicsEngine = <PhysicsEngine>this._scene.getPhysicsEngine();
  200. }
  201. /**
  202. * Returns the data related to the radial explosion event (sphere).
  203. * @returns The radial explosion event data
  204. */
  205. public getData(): PhysicsRadialExplosionEventData {
  206. this._dataFetched = true;
  207. return {
  208. sphere: this._sphere,
  209. };
  210. }
  211. /**
  212. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  213. * @param impostor A physics imposter
  214. * @param origin the origin of the explosion
  215. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  216. */
  217. public getImpostorForceAndContactPoint(impostor: PhysicsImpostor, origin: Vector3): Nullable<PhysicsForceAndContactPoint> {
  218. if (impostor.mass === 0) {
  219. return null;
  220. }
  221. if (!this._intersectsWithSphere(impostor, origin, this._options.radius)) {
  222. return null;
  223. }
  224. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  225. return null;
  226. }
  227. var impostorObjectCenter = impostor.getObjectCenter();
  228. var direction = impostorObjectCenter.subtract(origin);
  229. var ray = new Ray(origin, direction, this._options.radius);
  230. var hit = ray.intersectsMesh(<AbstractMesh>impostor.object);
  231. var contactPoint = hit.pickedPoint;
  232. if (!contactPoint) {
  233. return null;
  234. }
  235. var distanceFromOrigin = Vector3.Distance(origin, contactPoint);
  236. if (distanceFromOrigin > this._options.radius) {
  237. return null;
  238. }
  239. var multiplier = this._options.falloff === PhysicsRadialImpulseFalloff.Constant
  240. ? this._options.strength
  241. : this._options.strength * (1 - (distanceFromOrigin / this._options.radius));
  242. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  243. return { force: force, contactPoint: contactPoint };
  244. }
  245. /**
  246. * Disposes the sphere.
  247. * @param force Specifies if the sphere should be disposed by force
  248. */
  249. public dispose(force: boolean = true) {
  250. if (force) {
  251. this._sphere.dispose();
  252. } else {
  253. setTimeout(() => {
  254. if (!this._dataFetched) {
  255. this._sphere.dispose();
  256. }
  257. }, 0);
  258. }
  259. }
  260. /*** Helpers ***/
  261. private _prepareSphere(): void {
  262. if (!this._sphere) {
  263. this._sphere = SphereBuilder.CreateSphere("radialExplosionEventSphere", this._options.sphere, this._scene);
  264. this._sphere.isVisible = false;
  265. }
  266. }
  267. private _intersectsWithSphere(impostor: PhysicsImpostor, origin: Vector3, radius: number): boolean {
  268. var impostorObject = <AbstractMesh>impostor.object;
  269. this._prepareSphere();
  270. this._sphere.position = origin;
  271. this._sphere.scaling = new Vector3(radius * 2, radius * 2, radius * 2);
  272. this._sphere._updateBoundingInfo();
  273. this._sphere.computeWorldMatrix(true);
  274. return this._sphere.intersectsMesh(impostorObject, true);
  275. }
  276. }
  277. /**
  278. * Represents a gravitational field event
  279. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  280. */
  281. class PhysicsGravitationalFieldEvent {
  282. private _tickCallback: any;
  283. private _sphere: Mesh;
  284. private _dataFetched: boolean = false; // check if the has been fetched the data. If not, do cleanup
  285. /**
  286. * Initializes the physics gravitational field event
  287. * @param _physicsHelper A physics helper
  288. * @param _scene BabylonJS scene
  289. * @param _origin The origin position of the gravitational field event
  290. * @param _options The options for the vortex event
  291. */
  292. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _origin: Vector3, private _options: PhysicsRadialExplosionEventOptions) {
  293. this._options = {...(new PhysicsRadialExplosionEventOptions()), ...this._options};
  294. this._tickCallback = this._tick.bind(this);
  295. this._options.strength = this._options.strength * -1;
  296. }
  297. /**
  298. * Returns the data related to the gravitational field event (sphere).
  299. * @returns A gravitational field event
  300. */
  301. public getData(): PhysicsGravitationalFieldEventData {
  302. this._dataFetched = true;
  303. return {
  304. sphere: this._sphere,
  305. };
  306. }
  307. /**
  308. * Enables the gravitational field.
  309. */
  310. public enable() {
  311. this._tickCallback.call(this);
  312. this._scene.registerBeforeRender(this._tickCallback);
  313. }
  314. /**
  315. * Disables the gravitational field.
  316. */
  317. public disable() {
  318. this._scene.unregisterBeforeRender(this._tickCallback);
  319. }
  320. /**
  321. * Disposes the sphere.
  322. * @param force The force to dispose from the gravitational field event
  323. */
  324. public dispose(force: boolean = true) {
  325. if (force) {
  326. this._sphere.dispose();
  327. } else {
  328. setTimeout(() => {
  329. if (!this._dataFetched) {
  330. this._sphere.dispose();
  331. }
  332. }, 0);
  333. }
  334. }
  335. private _tick() {
  336. // Since the params won't change, we fetch the event only once
  337. if (this._sphere) {
  338. this._physicsHelper.applyRadialExplosionForce(this._origin, this._options);
  339. } else {
  340. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._options);
  341. if (radialExplosionEvent) {
  342. this._sphere = <Mesh>radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  343. }
  344. }
  345. }
  346. }
  347. /**
  348. * Represents a physics updraft event
  349. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  350. */
  351. class PhysicsUpdraftEvent {
  352. private _physicsEngine: PhysicsEngine;
  353. private _originTop: Vector3 = Vector3.Zero(); // the most upper part of the cylinder
  354. private _originDirection: Vector3 = Vector3.Zero(); // used if the updraftMode is perpendicular
  355. private _tickCallback: any;
  356. private _cylinder: Mesh;
  357. private _cylinderPosition: Vector3 = Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  358. private _dataFetched: boolean = false; // check if the has been fetched the data. If not, do cleanup
  359. /**
  360. * Initializes the physics updraft event
  361. * @param _physicsHelper A physics helper
  362. * @param _scene BabylonJS scene
  363. * @param _origin The origin position of the updraft
  364. * @param _options The options for the updraft event
  365. */
  366. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _origin: Vector3, private _options: PhysicsUpdraftEventOptions) {
  367. this._physicsEngine = <PhysicsEngine>this._scene.getPhysicsEngine();
  368. this._options = {...(new PhysicsUpdraftEventOptions()), ...this._options};
  369. this._origin.addToRef(new Vector3(0, this._options.height / 2, 0), this._cylinderPosition);
  370. this._origin.addToRef(new Vector3(0, this._options.height, 0), this._originTop);
  371. if (this._options.updraftMode === PhysicsUpdraftMode.Perpendicular) {
  372. this._originDirection = this._origin.subtract(this._originTop).normalize();
  373. }
  374. this._tickCallback = this._tick.bind(this);
  375. this._prepareCylinder();
  376. }
  377. /**
  378. * Returns the data related to the updraft event (cylinder).
  379. * @returns A physics updraft event
  380. */
  381. public getData(): PhysicsUpdraftEventData {
  382. this._dataFetched = true;
  383. return {
  384. cylinder: this._cylinder,
  385. };
  386. }
  387. /**
  388. * Enables the updraft.
  389. */
  390. public enable() {
  391. this._tickCallback.call(this);
  392. this._scene.registerBeforeRender(this._tickCallback);
  393. }
  394. /**
  395. * Disables the updraft.
  396. */
  397. public disable() {
  398. this._scene.unregisterBeforeRender(this._tickCallback);
  399. }
  400. /**
  401. * Disposes the cylinder.
  402. * @param force Specifies if the updraft should be disposed by force
  403. */
  404. public dispose(force: boolean = true) {
  405. if (!this._cylinder) {
  406. return;
  407. }
  408. if (force) {
  409. this._cylinder.dispose();
  410. } else {
  411. setTimeout(() => {
  412. if (!this._dataFetched) {
  413. this._cylinder.dispose();
  414. }
  415. }, 0);
  416. }
  417. }
  418. private getImpostorForceAndContactPoint(impostor: PhysicsImpostor): Nullable<PhysicsForceAndContactPoint> {
  419. if (impostor.mass === 0) {
  420. return null;
  421. }
  422. if (!this._intersectsWithCylinder(impostor)) {
  423. return null;
  424. }
  425. var impostorObjectCenter = impostor.getObjectCenter();
  426. if (this._options.updraftMode === PhysicsUpdraftMode.Perpendicular) {
  427. var direction = this._originDirection;
  428. } else {
  429. var direction = impostorObjectCenter.subtract(this._originTop);
  430. }
  431. var multiplier = this._options.strength * -1;
  432. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  433. return { force: force, contactPoint: impostorObjectCenter };
  434. }
  435. private _tick() {
  436. this._physicsEngine.getImpostors().forEach((impostor) => {
  437. var impostorForceAndContactPoint = this.getImpostorForceAndContactPoint(impostor);
  438. if (!impostorForceAndContactPoint) {
  439. return;
  440. }
  441. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  442. });
  443. }
  444. /*** Helpers ***/
  445. private _prepareCylinder(): void {
  446. if (!this._cylinder) {
  447. this._cylinder = CylinderBuilder.CreateCylinder("updraftEventCylinder", {
  448. height: this._options.height,
  449. diameter: this._options.radius * 2,
  450. }, this._scene);
  451. this._cylinder.isVisible = false;
  452. }
  453. }
  454. private _intersectsWithCylinder(impostor: PhysicsImpostor): boolean {
  455. var impostorObject = <AbstractMesh>impostor.object;
  456. this._cylinder.position = this._cylinderPosition;
  457. return this._cylinder.intersectsMesh(impostorObject, true);
  458. }
  459. }
  460. /**
  461. * Represents a physics vortex event
  462. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  463. */
  464. class PhysicsVortexEvent {
  465. private _physicsEngine: PhysicsEngine;
  466. private _originTop: Vector3 = Vector3.Zero(); // the most upper part of the cylinder
  467. private _tickCallback: any;
  468. private _cylinder: Mesh;
  469. private _cylinderPosition: Vector3 = Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  470. private _dataFetched: boolean = false; // check if the has been fetched the data. If not, do cleanup
  471. /**
  472. * Initializes the physics vortex event
  473. * @param _physicsHelper A physics helper
  474. * @param _scene The BabylonJS scene
  475. * @param _origin The origin position of the vortex
  476. * @param _options The options for the vortex event
  477. */
  478. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _origin: Vector3, private _options: PhysicsVortexEventOptions) {
  479. this._physicsEngine = <PhysicsEngine>this._scene.getPhysicsEngine();
  480. this._options = {...(new PhysicsVortexEventOptions()), ...this._options};
  481. this._origin.addToRef(new Vector3(0, this._options.height / 2, 0), this._cylinderPosition);
  482. this._origin.addToRef(new Vector3(0, this._options.height, 0), this._originTop);
  483. this._tickCallback = this._tick.bind(this);
  484. this._prepareCylinder();
  485. }
  486. /**
  487. * Returns the data related to the vortex event (cylinder).
  488. * @returns The physics vortex event data
  489. */
  490. public getData(): PhysicsVortexEventData {
  491. this._dataFetched = true;
  492. return {
  493. cylinder: this._cylinder,
  494. };
  495. }
  496. /**
  497. * Enables the vortex.
  498. */
  499. public enable() {
  500. this._tickCallback.call(this);
  501. this._scene.registerBeforeRender(this._tickCallback);
  502. }
  503. /**
  504. * Disables the cortex.
  505. */
  506. public disable() {
  507. this._scene.unregisterBeforeRender(this._tickCallback);
  508. }
  509. /**
  510. * Disposes the sphere.
  511. * @param force
  512. */
  513. public dispose(force: boolean = true) {
  514. if (force) {
  515. this._cylinder.dispose();
  516. } else {
  517. setTimeout(() => {
  518. if (!this._dataFetched) {
  519. this._cylinder.dispose();
  520. }
  521. }, 0);
  522. }
  523. }
  524. private getImpostorForceAndContactPoint(impostor: PhysicsImpostor): Nullable<PhysicsForceAndContactPoint> {
  525. if (impostor.mass === 0) {
  526. return null;
  527. }
  528. if (!this._intersectsWithCylinder(impostor)) {
  529. return null;
  530. }
  531. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  532. return null;
  533. }
  534. var impostorObjectCenter = impostor.getObjectCenter();
  535. var originOnPlane = new Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  536. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  537. var ray = new Ray(originOnPlane, originToImpostorDirection, this._options.radius);
  538. var hit = ray.intersectsMesh(<AbstractMesh>impostor.object);
  539. var contactPoint = hit.pickedPoint;
  540. if (!contactPoint) {
  541. return null;
  542. }
  543. var absoluteDistanceFromOrigin = hit.distance / this._options.radius;
  544. var directionToOrigin = contactPoint.normalize();
  545. if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) {
  546. directionToOrigin = directionToOrigin.negate();
  547. }
  548. if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) {
  549. var forceX = directionToOrigin.x * this._options.centripetalForceMultiplier;
  550. var forceY = directionToOrigin.y * this._options.updraftForceMultiplier;
  551. var forceZ = directionToOrigin.z * this._options.centripetalForceMultiplier;
  552. } else {
  553. var perpendicularDirection = Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  554. var forceX = (perpendicularDirection.x + directionToOrigin.x) * this._options.centrifugalForceMultiplier;
  555. var forceY = this._originTop.y * this._options.updraftForceMultiplier;
  556. var forceZ = (perpendicularDirection.z + directionToOrigin.z) * this._options.centrifugalForceMultiplier;
  557. }
  558. var force = new Vector3(forceX, forceY, forceZ);
  559. force = force.multiplyByFloats(this._options.strength, this._options.strength, this._options.strength);
  560. return { force: force, contactPoint: impostorObjectCenter };
  561. }
  562. private _tick() {
  563. this._physicsEngine.getImpostors().forEach((impostor) => {
  564. var impostorForceAndContactPoint = this.getImpostorForceAndContactPoint(impostor);
  565. if (!impostorForceAndContactPoint) {
  566. return;
  567. }
  568. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  569. });
  570. }
  571. /*** Helpers ***/
  572. private _prepareCylinder(): void {
  573. if (!this._cylinder) {
  574. this._cylinder = CylinderBuilder.CreateCylinder("vortexEventCylinder", {
  575. height: this._options.height,
  576. diameter: this._options.radius * 2,
  577. }, this._scene);
  578. this._cylinder.isVisible = false;
  579. }
  580. }
  581. private _intersectsWithCylinder(impostor: PhysicsImpostor): boolean {
  582. var impostorObject = <AbstractMesh>impostor.object;
  583. this._cylinder.position = this._cylinderPosition;
  584. return this._cylinder.intersectsMesh(impostorObject, true);
  585. }
  586. }
  587. /**
  588. * Options fot the radial explosion event
  589. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  590. */
  591. export class PhysicsRadialExplosionEventOptions {
  592. /**
  593. * The radius of the sphere for the radial explosion.
  594. */
  595. radius: number = 5;
  596. /**
  597. * The strenth of the explosion.
  598. */
  599. strength: number = 10;
  600. /**
  601. * The strenght of the force in correspondence to the distance of the affected object
  602. */
  603. falloff: PhysicsRadialImpulseFalloff = PhysicsRadialImpulseFalloff.Constant;
  604. /**
  605. * Sphere options for the radial explosion.
  606. */
  607. sphere: { segments: number, diameter: number } = { segments: 32, diameter: 1 };
  608. }
  609. /**
  610. * Options fot the updraft event
  611. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  612. */
  613. export class PhysicsUpdraftEventOptions {
  614. /**
  615. * The radius of the cylinder for the vortex
  616. */
  617. radius: number = 5;
  618. /**
  619. * The strenth of the updraft.
  620. */
  621. strength: number = 10;
  622. /**
  623. * The height of the cylinder for the updraft.
  624. */
  625. height: number = 10;
  626. /**
  627. * The mode for the the updraft.
  628. */
  629. updraftMode: PhysicsUpdraftMode = PhysicsUpdraftMode.Center;
  630. }
  631. /**
  632. * Options fot the vortex event
  633. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  634. */
  635. export class PhysicsVortexEventOptions {
  636. /**
  637. * The radius of the cylinder for the vortex
  638. */
  639. radius: number = 5;
  640. /**
  641. * The strenth of the vortex.
  642. */
  643. strength: number = 10;
  644. /**
  645. * The height of the cylinder for the vortex.
  646. */
  647. height: number = 10;
  648. /**
  649. * At which distance, relative to the radius the centripetal forces should kick in? Range: 0-1
  650. */
  651. centripetalForceThreshold: number = 0.7;
  652. /**
  653. * This multiplier determines with how much force the objects will be pushed sideways/around the vortex, when below the treshold.
  654. */
  655. centripetalForceMultiplier: number = 5;
  656. /**
  657. * This multiplier determines with how much force the objects will be pushed sideways/around the vortex, when above the treshold.
  658. */
  659. centrifugalForceMultiplier: number = 0.5;
  660. /**
  661. * This multiplier determines with how much force the objects will be pushed upwards, when in the vortex.
  662. */
  663. updraftForceMultiplier: number = 0.02;
  664. }
  665. /**
  666. * The strenght of the force in correspondence to the distance of the affected object
  667. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  668. */
  669. export enum PhysicsRadialImpulseFalloff {
  670. /** Defines that impulse is constant in strength across it's whole radius */
  671. Constant,
  672. /** Defines that impulse gets weaker if it's further from the origin */
  673. Linear
  674. }
  675. /**
  676. * The strength of the force in correspondence to the distance of the affected object
  677. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  678. */
  679. export enum PhysicsUpdraftMode {
  680. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  681. Center,
  682. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  683. Perpendicular
  684. }
  685. /**
  686. * Interface for a physics force and contact point
  687. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  688. */
  689. export interface PhysicsForceAndContactPoint {
  690. /**
  691. * The force applied at the contact point
  692. */
  693. force: Vector3;
  694. /**
  695. * The contact point
  696. */
  697. contactPoint: Vector3;
  698. }
  699. /**
  700. * Interface for radial explosion event data
  701. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  702. */
  703. export interface PhysicsRadialExplosionEventData {
  704. /**
  705. * A sphere used for the radial explosion event
  706. */
  707. sphere: Mesh;
  708. }
  709. /**
  710. * Interface for gravitational field event data
  711. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  712. */
  713. export interface PhysicsGravitationalFieldEventData {
  714. /**
  715. * A sphere mesh used for the gravitational field event
  716. */
  717. sphere: Mesh;
  718. }
  719. /**
  720. * Interface for updraft event data
  721. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  722. */
  723. export interface PhysicsUpdraftEventData {
  724. /**
  725. * A cylinder used for the updraft event
  726. */
  727. cylinder: Mesh;
  728. }
  729. /**
  730. * Interface for vortex event data
  731. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  732. */
  733. export interface PhysicsVortexEventData {
  734. /**
  735. * A cylinder used for the vortex event
  736. */
  737. cylinder: Mesh;
  738. }