actionManager.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. import { Nullable } from "../types";
  2. import { AbstractMesh } from "../Meshes/abstractMesh";
  3. import { Scene } from "../scene";
  4. import { Vector3, Vector4, Color3, Color4 } from "../Maths/math";
  5. import { Condition, ValueCondition } from "./condition";
  6. import { Action, IAction } from "./action";
  7. import { DoNothingAction } from "./directActions";
  8. import { EngineStore } from "../Engines/engineStore";
  9. import { IActionEvent } from "../Actions/actionEvent";
  10. import { Logger } from "../Misc/logger";
  11. import { DeepCopier } from "../Misc/deepCopier";
  12. import { _TypeStore } from "../Misc/typeStore";
  13. import { AbstractActionManager } from './abstractActionManager';
  14. import { Constants } from "../Engines/constants";
  15. /**
  16. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  17. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  18. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19. */
  20. export class ActionManager extends AbstractActionManager {
  21. /**
  22. * Nothing
  23. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  24. */
  25. public static readonly NothingTrigger = Constants.ACTION_NothingTrigger;
  26. /**
  27. * On pick
  28. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  29. */
  30. public static readonly OnPickTrigger = Constants.ACTION_OnPickTrigger;
  31. /**
  32. * On left pick
  33. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  34. */
  35. public static readonly OnLeftPickTrigger = Constants.ACTION_OnLeftPickTrigger;
  36. /**
  37. * On right pick
  38. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  39. */
  40. public static readonly OnRightPickTrigger = Constants.ACTION_OnRightPickTrigger;
  41. /**
  42. * On center pick
  43. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  44. */
  45. public static readonly OnCenterPickTrigger = Constants.ACTION_OnCenterPickTrigger;
  46. /**
  47. * On pick down
  48. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  49. */
  50. public static readonly OnPickDownTrigger = Constants.ACTION_OnPickDownTrigger;
  51. /**
  52. * On double pick
  53. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54. */
  55. public static readonly OnDoublePickTrigger = Constants.ACTION_OnDoublePickTrigger;
  56. /**
  57. * On pick up
  58. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  59. */
  60. public static readonly OnPickUpTrigger = Constants.ACTION_OnPickUpTrigger;
  61. /**
  62. * On pick out.
  63. * This trigger will only be raised if you also declared a OnPickDown
  64. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  65. */
  66. public static readonly OnPickOutTrigger = Constants.ACTION_OnPickOutTrigger;
  67. /**
  68. * On long press
  69. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  70. */
  71. public static readonly OnLongPressTrigger = Constants.ACTION_OnLongPressTrigger;
  72. /**
  73. * On pointer over
  74. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  75. */
  76. public static readonly OnPointerOverTrigger = Constants.ACTION_OnPointerOverTrigger;
  77. /**
  78. * On pointer out
  79. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  80. */
  81. public static readonly OnPointerOutTrigger = Constants.ACTION_OnPointerOutTrigger;
  82. /**
  83. * On every frame
  84. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  85. */
  86. public static readonly OnEveryFrameTrigger = Constants.ACTION_OnEveryFrameTrigger;
  87. /**
  88. * On intersection enter
  89. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  90. */
  91. public static readonly OnIntersectionEnterTrigger = Constants.ACTION_OnIntersectionEnterTrigger;
  92. /**
  93. * On intersection exit
  94. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  95. */
  96. public static readonly OnIntersectionExitTrigger = Constants.ACTION_OnIntersectionExitTrigger;
  97. /**
  98. * On key down
  99. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  100. */
  101. public static readonly OnKeyDownTrigger = Constants.ACTION_OnKeyDownTrigger;
  102. /**
  103. * On key up
  104. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  105. */
  106. public static readonly OnKeyUpTrigger = 15;
  107. // Members
  108. private _scene: Scene;
  109. /**
  110. * Creates a new action manager
  111. * @param scene defines the hosting scene
  112. */
  113. constructor(scene: Scene) {
  114. super();
  115. this._scene = scene || EngineStore.LastCreatedScene;
  116. scene.actionManagers.push(this);
  117. }
  118. // Methods
  119. /**
  120. * Releases all associated resources
  121. */
  122. public dispose(): void {
  123. var index = this._scene.actionManagers.indexOf(this);
  124. for (var i = 0; i < this.actions.length; i++) {
  125. var action = this.actions[i];
  126. ActionManager.Triggers[action.trigger]--;
  127. if (ActionManager.Triggers[action.trigger] === 0) {
  128. delete ActionManager.Triggers[action.trigger];
  129. }
  130. }
  131. if (index > -1) {
  132. this._scene.actionManagers.splice(index, 1);
  133. }
  134. }
  135. /**
  136. * Gets hosting scene
  137. * @returns the hosting scene
  138. */
  139. public getScene(): Scene {
  140. return this._scene;
  141. }
  142. /**
  143. * Does this action manager handles actions of any of the given triggers
  144. * @param triggers defines the triggers to be tested
  145. * @return a boolean indicating whether one (or more) of the triggers is handled
  146. */
  147. public hasSpecificTriggers(triggers: number[]): boolean {
  148. for (var index = 0; index < this.actions.length; index++) {
  149. var action = this.actions[index];
  150. if (triggers.indexOf(action.trigger) > -1) {
  151. return true;
  152. }
  153. }
  154. return false;
  155. }
  156. /**
  157. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  158. * speed.
  159. * @param triggerA defines the trigger to be tested
  160. * @param triggerB defines the trigger to be tested
  161. * @return a boolean indicating whether one (or more) of the triggers is handled
  162. */
  163. public hasSpecificTriggers2(triggerA: number, triggerB: number): boolean {
  164. for (var index = 0; index < this.actions.length; index++) {
  165. var action = this.actions[index];
  166. if (triggerA == action.trigger || triggerB == action.trigger) {
  167. return true;
  168. }
  169. }
  170. return false;
  171. }
  172. /**
  173. * Does this action manager handles actions of a given trigger
  174. * @param trigger defines the trigger to be tested
  175. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  176. * @return whether the trigger is handled
  177. */
  178. public hasSpecificTrigger(trigger: number, parameterPredicate?: (parameter: any) => boolean): boolean {
  179. for (var index = 0; index < this.actions.length; index++) {
  180. var action = this.actions[index];
  181. if (action.trigger === trigger) {
  182. if (parameterPredicate) {
  183. if (parameterPredicate(action.getTriggerParameter())) {
  184. return true;
  185. }
  186. } else {
  187. return true;
  188. }
  189. }
  190. }
  191. return false;
  192. }
  193. /**
  194. * Does this action manager has pointer triggers
  195. */
  196. public get hasPointerTriggers(): boolean {
  197. for (var index = 0; index < this.actions.length; index++) {
  198. var action = this.actions[index];
  199. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  200. return true;
  201. }
  202. }
  203. return false;
  204. }
  205. /**
  206. * Does this action manager has pick triggers
  207. */
  208. public get hasPickTriggers(): boolean {
  209. for (var index = 0; index < this.actions.length; index++) {
  210. var action = this.actions[index];
  211. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  212. return true;
  213. }
  214. }
  215. return false;
  216. }
  217. /**
  218. * Registers an action to this action manager
  219. * @param action defines the action to be registered
  220. * @return the action amended (prepared) after registration
  221. */
  222. public registerAction(action: IAction): Nullable<IAction> {
  223. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  224. if (this.getScene().actionManager !== this) {
  225. Logger.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  226. return null;
  227. }
  228. }
  229. this.actions.push(action);
  230. if (ActionManager.Triggers[action.trigger]) {
  231. ActionManager.Triggers[action.trigger]++;
  232. }
  233. else {
  234. ActionManager.Triggers[action.trigger] = 1;
  235. }
  236. action._actionManager = this;
  237. action._prepare();
  238. return action;
  239. }
  240. /**
  241. * Unregisters an action to this action manager
  242. * @param action defines the action to be unregistered
  243. * @return a boolean indicating whether the action has been unregistered
  244. */
  245. public unregisterAction(action: IAction): Boolean {
  246. var index = this.actions.indexOf(action);
  247. if (index !== -1) {
  248. this.actions.splice(index, 1);
  249. ActionManager.Triggers[action.trigger] -= 1;
  250. if (ActionManager.Triggers[action.trigger] === 0) {
  251. delete ActionManager.Triggers[action.trigger];
  252. }
  253. delete action._actionManager;
  254. return true;
  255. }
  256. return false;
  257. }
  258. /**
  259. * Process a specific trigger
  260. * @param trigger defines the trigger to process
  261. * @param evt defines the event details to be processed
  262. */
  263. public processTrigger(trigger: number, evt?: IActionEvent): void {
  264. for (var index = 0; index < this.actions.length; index++) {
  265. var action = this.actions[index];
  266. if (action.trigger === trigger) {
  267. if (evt) {
  268. if (trigger === ActionManager.OnKeyUpTrigger
  269. || trigger === ActionManager.OnKeyDownTrigger) {
  270. var parameter = action.getTriggerParameter();
  271. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  272. if (!parameter.toLowerCase) {
  273. continue;
  274. }
  275. var lowerCase = parameter.toLowerCase();
  276. if (lowerCase !== evt.sourceEvent.key) {
  277. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  278. var actualkey = String.fromCharCode(unicode).toLowerCase();
  279. if (actualkey !== lowerCase) {
  280. continue;
  281. }
  282. }
  283. }
  284. }
  285. }
  286. action._executeCurrent(evt);
  287. }
  288. }
  289. }
  290. /** @hidden */
  291. public _getEffectiveTarget(target: any, propertyPath: string): any {
  292. var properties = propertyPath.split(".");
  293. for (var index = 0; index < properties.length - 1; index++) {
  294. target = target[properties[index]];
  295. }
  296. return target;
  297. }
  298. /** @hidden */
  299. public _getProperty(propertyPath: string): string {
  300. var properties = propertyPath.split(".");
  301. return properties[properties.length - 1];
  302. }
  303. /**
  304. * Serialize this manager to a JSON object
  305. * @param name defines the property name to store this manager
  306. * @returns a JSON representation of this manager
  307. */
  308. public serialize(name: string): any {
  309. var root = {
  310. children: new Array(),
  311. name: name,
  312. type: 3, // Root node
  313. properties: new Array() // Empty for root but required
  314. };
  315. for (var i = 0; i < this.actions.length; i++) {
  316. var triggerObject = {
  317. type: 0, // Trigger
  318. children: new Array(),
  319. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  320. properties: new Array()
  321. };
  322. var triggerOptions = this.actions[i].triggerOptions;
  323. if (triggerOptions && typeof triggerOptions !== "number") {
  324. if (triggerOptions.parameter instanceof Node) {
  325. triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter));
  326. }
  327. else {
  328. var parameter = <any>{};
  329. DeepCopier.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  330. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  331. parameter._meshId = triggerOptions.parameter.mesh.id;
  332. }
  333. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  334. }
  335. }
  336. // Serialize child action, recursively
  337. this.actions[i].serialize(triggerObject);
  338. // Add serialized trigger
  339. root.children.push(triggerObject);
  340. }
  341. return root;
  342. }
  343. /**
  344. * Creates a new ActionManager from a JSON data
  345. * @param parsedActions defines the JSON data to read from
  346. * @param object defines the hosting mesh
  347. * @param scene defines the hosting scene
  348. */
  349. public static Parse(parsedActions: any, object: Nullable<AbstractMesh>, scene: Scene): void {
  350. var actionManager = new ActionManager(scene);
  351. if (object === null) {
  352. scene.actionManager = actionManager;
  353. }
  354. else {
  355. object.actionManager = actionManager;
  356. }
  357. // instanciate a new object
  358. var instanciate = (name: string, params: Array<any>): any => {
  359. const internalClassType = _TypeStore.GetClass("BABYLON." + name);
  360. if (internalClassType) {
  361. var newInstance: Object = Object.create(internalClassType.prototype);
  362. newInstance.constructor.apply(newInstance, params);
  363. return newInstance;
  364. }
  365. };
  366. var parseParameter = (name: string, value: string, target: any, propertyPath: Nullable<string>): any => {
  367. if (propertyPath === null) {
  368. // String, boolean or float
  369. var floatValue = parseFloat(value);
  370. if (value === "true" || value === "false") {
  371. return value === "true";
  372. }
  373. else {
  374. return isNaN(floatValue) ? value : floatValue;
  375. }
  376. }
  377. var effectiveTarget = propertyPath.split(".");
  378. var values = value.split(",");
  379. // Get effective Target
  380. for (var i = 0; i < effectiveTarget.length; i++) {
  381. target = target[effectiveTarget[i]];
  382. }
  383. // Return appropriate value with its type
  384. if (typeof (target) === "boolean") {
  385. return values[0] === "true";
  386. }
  387. if (typeof (target) === "string") {
  388. return values[0];
  389. }
  390. // Parameters with multiple values such as Vector3 etc.
  391. var split = new Array<number>();
  392. for (var i = 0; i < values.length; i++) {
  393. split.push(parseFloat(values[i]));
  394. }
  395. if (target instanceof Vector3) {
  396. return Vector3.FromArray(split);
  397. }
  398. if (target instanceof Vector4) {
  399. return Vector4.FromArray(split);
  400. }
  401. if (target instanceof Color3) {
  402. return Color3.FromArray(split);
  403. }
  404. if (target instanceof Color4) {
  405. return Color4.FromArray(split);
  406. }
  407. return parseFloat(values[0]);
  408. };
  409. // traverse graph per trigger
  410. var traverse = (parsedAction: any, trigger: any, condition: Nullable<Condition>, action: Nullable<Action>, combineArray: Nullable<Array<Action>> = null) => {
  411. if (parsedAction.detached) {
  412. return;
  413. }
  414. var parameters = new Array<any>();
  415. var target: any = null;
  416. var propertyPath: Nullable<string> = null;
  417. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  418. // Parameters
  419. if (parsedAction.type === 2) {
  420. parameters.push(actionManager);
  421. }
  422. else {
  423. parameters.push(trigger);
  424. }
  425. if (combine) {
  426. var actions = new Array<Action>();
  427. for (var j = 0; j < parsedAction.combine.length; j++) {
  428. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  429. }
  430. parameters.push(actions);
  431. }
  432. else {
  433. for (var i = 0; i < parsedAction.properties.length; i++) {
  434. var value = parsedAction.properties[i].value;
  435. var name = parsedAction.properties[i].name;
  436. var targetType = parsedAction.properties[i].targetType;
  437. if (name === "target") {
  438. if (targetType !== null && targetType === "SceneProperties") {
  439. value = target = scene;
  440. }
  441. else {
  442. value = target = scene.getNodeByName(value);
  443. }
  444. }
  445. else if (name === "parent") {
  446. value = scene.getNodeByName(value);
  447. }
  448. else if (name === "sound") {
  449. // Can not externalize to component, so only checks for the presence off the API.
  450. if (scene.getSoundByName) {
  451. value = scene.getSoundByName(value);
  452. }
  453. }
  454. else if (name !== "propertyPath") {
  455. if (parsedAction.type === 2 && name === "operator") {
  456. value = (<any>ValueCondition)[value];
  457. }
  458. else {
  459. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  460. }
  461. } else {
  462. propertyPath = value;
  463. }
  464. parameters.push(value);
  465. }
  466. }
  467. if (combineArray === null) {
  468. parameters.push(condition);
  469. }
  470. else {
  471. parameters.push(null);
  472. }
  473. // If interpolate value action
  474. if (parsedAction.name === "InterpolateValueAction") {
  475. var param = parameters[parameters.length - 2];
  476. parameters[parameters.length - 1] = param;
  477. parameters[parameters.length - 2] = condition;
  478. }
  479. // Action or condition(s) and not CombineAction
  480. var newAction = instanciate(parsedAction.name, parameters);
  481. if (newAction instanceof Condition && condition !== null) {
  482. var nothing = new DoNothingAction(trigger, condition);
  483. if (action) {
  484. action.then(nothing);
  485. }
  486. else {
  487. actionManager.registerAction(nothing);
  488. }
  489. action = nothing;
  490. }
  491. if (combineArray === null) {
  492. if (newAction instanceof Condition) {
  493. condition = newAction;
  494. newAction = action;
  495. } else {
  496. condition = null;
  497. if (action) {
  498. action.then(newAction);
  499. }
  500. else {
  501. actionManager.registerAction(newAction);
  502. }
  503. }
  504. }
  505. else {
  506. combineArray.push(newAction);
  507. }
  508. for (var i = 0; i < parsedAction.children.length; i++) {
  509. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  510. }
  511. };
  512. // triggers
  513. for (var i = 0; i < parsedActions.children.length; i++) {
  514. var triggerParams: any;
  515. var trigger = parsedActions.children[i];
  516. if (trigger.properties.length > 0) {
  517. var param = trigger.properties[0].value;
  518. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  519. if (value._meshId) {
  520. value.mesh = scene.getMeshByID(value._meshId);
  521. }
  522. triggerParams = { trigger: (<any>ActionManager)[trigger.name], parameter: value };
  523. }
  524. else {
  525. triggerParams = (<any>ActionManager)[trigger.name];
  526. }
  527. for (var j = 0; j < trigger.children.length; j++) {
  528. if (!trigger.detached) {
  529. traverse(trigger.children[j], triggerParams, null, null);
  530. }
  531. }
  532. }
  533. }
  534. /**
  535. * Get a trigger name by index
  536. * @param trigger defines the trigger index
  537. * @returns a trigger name
  538. */
  539. public static GetTriggerName(trigger: number): string {
  540. switch (trigger) {
  541. case 0: return "NothingTrigger";
  542. case 1: return "OnPickTrigger";
  543. case 2: return "OnLeftPickTrigger";
  544. case 3: return "OnRightPickTrigger";
  545. case 4: return "OnCenterPickTrigger";
  546. case 5: return "OnPickDownTrigger";
  547. case 6: return "OnPickUpTrigger";
  548. case 7: return "OnLongPressTrigger";
  549. case 8: return "OnPointerOverTrigger";
  550. case 9: return "OnPointerOutTrigger";
  551. case 10: return "OnEveryFrameTrigger";
  552. case 11: return "OnIntersectionEnterTrigger";
  553. case 12: return "OnIntersectionExitTrigger";
  554. case 13: return "OnKeyDownTrigger";
  555. case 14: return "OnKeyUpTrigger";
  556. case 15: return "OnPickOutTrigger";
  557. default: return "";
  558. }
  559. }
  560. }