babylon.actionManager.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. module BABYLON {
  2. /**
  3. * ActionEvent is the event beint sent when an action is triggered.
  4. */
  5. export class ActionEvent {
  6. /**
  7. * @param source The mesh or sprite that triggered the action.
  8. * @param pointerX The X mouse cursor position at the time of the event
  9. * @param pointerY The Y mouse cursor position at the time of the event
  10. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  11. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  12. */
  13. constructor(public source: any, public pointerX: number, public pointerY: number, public meshUnderPointer: Nullable<AbstractMesh>, public sourceEvent?: any, public additionalData?: any) {
  14. }
  15. /**
  16. * Helper function to auto-create an ActionEvent from a source mesh.
  17. * @param source The source mesh that triggered the event
  18. * @param evt {Event} The original (browser) event
  19. */
  20. public static CreateNew(source: AbstractMesh, evt?: Event, additionalData?: any): ActionEvent {
  21. var scene = source.getScene();
  22. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  23. }
  24. /**
  25. * Helper function to auto-create an ActionEvent from a source mesh.
  26. * @param source The source sprite that triggered the event
  27. * @param scene Scene associated with the sprite
  28. * @param evt {Event} The original (browser) event
  29. */
  30. public static CreateNewFromSprite(source: Sprite, scene: Scene, evt?: Event, additionalData?: any): ActionEvent {
  31. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32. }
  33. /**
  34. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35. * @param scene the scene where the event occurred
  36. * @param evt {Event} The original (browser) event
  37. */
  38. public static CreateNewFromScene(scene: Scene, evt: Event): ActionEvent {
  39. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  40. }
  41. public static CreateNewFromPrimitive(prim: any, pointerPos: Vector2, evt?: Event, additionalData?: any): ActionEvent {
  42. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43. }
  44. }
  45. /**
  46. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48. */
  49. export class ActionManager {
  50. // Statics
  51. private static _NothingTrigger = 0;
  52. private static _OnPickTrigger = 1;
  53. private static _OnLeftPickTrigger = 2;
  54. private static _OnRightPickTrigger = 3;
  55. private static _OnCenterPickTrigger = 4;
  56. private static _OnPickDownTrigger = 5;
  57. private static _OnDoublePickTrigger = 6;
  58. private static _OnPickUpTrigger = 7;
  59. private static _OnLongPressTrigger = 8;
  60. private static _OnPointerOverTrigger = 9;
  61. private static _OnPointerOutTrigger = 10;
  62. private static _OnEveryFrameTrigger = 11;
  63. private static _OnIntersectionEnterTrigger = 12;
  64. private static _OnIntersectionExitTrigger = 13;
  65. private static _OnKeyDownTrigger = 14;
  66. private static _OnKeyUpTrigger = 15;
  67. private static _OnPickOutTrigger = 16;
  68. public static get NothingTrigger(): number {
  69. return ActionManager._NothingTrigger;
  70. }
  71. public static get OnPickTrigger(): number {
  72. return ActionManager._OnPickTrigger;
  73. }
  74. public static get OnLeftPickTrigger(): number {
  75. return ActionManager._OnLeftPickTrigger;
  76. }
  77. public static get OnRightPickTrigger(): number {
  78. return ActionManager._OnRightPickTrigger;
  79. }
  80. public static get OnCenterPickTrigger(): number {
  81. return ActionManager._OnCenterPickTrigger;
  82. }
  83. public static get OnPickDownTrigger(): number {
  84. return ActionManager._OnPickDownTrigger;
  85. }
  86. public static get OnDoublePickTrigger(): number {
  87. return ActionManager._OnDoublePickTrigger;
  88. }
  89. public static get OnPickUpTrigger(): number {
  90. return ActionManager._OnPickUpTrigger;
  91. }
  92. /// This trigger will only be raised if you also declared a OnPickDown
  93. public static get OnPickOutTrigger(): number {
  94. return ActionManager._OnPickOutTrigger;
  95. }
  96. public static get OnLongPressTrigger(): number {
  97. return ActionManager._OnLongPressTrigger;
  98. }
  99. public static get OnPointerOverTrigger(): number {
  100. return ActionManager._OnPointerOverTrigger;
  101. }
  102. public static get OnPointerOutTrigger(): number {
  103. return ActionManager._OnPointerOutTrigger;
  104. }
  105. public static get OnEveryFrameTrigger(): number {
  106. return ActionManager._OnEveryFrameTrigger;
  107. }
  108. public static get OnIntersectionEnterTrigger(): number {
  109. return ActionManager._OnIntersectionEnterTrigger;
  110. }
  111. public static get OnIntersectionExitTrigger(): number {
  112. return ActionManager._OnIntersectionExitTrigger;
  113. }
  114. public static get OnKeyDownTrigger(): number {
  115. return ActionManager._OnKeyDownTrigger;
  116. }
  117. public static get OnKeyUpTrigger(): number {
  118. return ActionManager._OnKeyUpTrigger;
  119. }
  120. public static Triggers: { [key: string]: number} = {};
  121. // Members
  122. public actions = new Array<Action>();
  123. public hoverCursor: string = '';
  124. private _scene: Scene;
  125. constructor(scene: Scene) {
  126. this._scene = scene;
  127. scene._actionManagers.push(this);
  128. }
  129. // Methods
  130. public dispose(): void {
  131. var index = this._scene._actionManagers.indexOf(this);
  132. for (var i = 0; i < this.actions.length; i++) {
  133. var action = this.actions[i];
  134. ActionManager.Triggers[action.trigger]--;
  135. if (ActionManager.Triggers[action.trigger] === 0) {
  136. delete ActionManager.Triggers[action.trigger]
  137. }
  138. }
  139. if (index > -1) {
  140. this._scene._actionManagers.splice(index, 1);
  141. }
  142. }
  143. public getScene(): Scene {
  144. return this._scene;
  145. }
  146. /**
  147. * Does this action manager handles actions of any of the given triggers
  148. * @param {number[]} triggers - the triggers to be tested
  149. * @return {boolean} whether one (or more) of the triggers is handeled
  150. */
  151. public hasSpecificTriggers(triggers: number[]): boolean {
  152. for (var index = 0; index < this.actions.length; index++) {
  153. var action = this.actions[index];
  154. if (triggers.indexOf(action.trigger) > -1) {
  155. return true;
  156. }
  157. }
  158. return false;
  159. }
  160. /**
  161. * Does this action manager handles actions of a given trigger
  162. * @param {number} trigger - the trigger to be tested
  163. * @return {boolean} whether the trigger is handeled
  164. */
  165. public hasSpecificTrigger(trigger: number): boolean {
  166. for (var index = 0; index < this.actions.length; index++) {
  167. var action = this.actions[index];
  168. if (action.trigger === trigger) {
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. /**
  175. * Does this action manager has pointer triggers
  176. * @return {boolean} whether or not it has pointer triggers
  177. */
  178. public get hasPointerTriggers(): boolean {
  179. for (var index = 0; index < this.actions.length; index++) {
  180. var action = this.actions[index];
  181. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  182. return true;
  183. }
  184. }
  185. return false;
  186. }
  187. /**
  188. * Does this action manager has pick triggers
  189. * @return {boolean} whether or not it has pick triggers
  190. */
  191. public get hasPickTriggers(): boolean {
  192. for (var index = 0; index < this.actions.length; index++) {
  193. var action = this.actions[index];
  194. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  195. return true;
  196. }
  197. }
  198. return false;
  199. }
  200. /**
  201. * Does exist one action manager with at least one trigger
  202. * @return {boolean} whether or not it exists one action manager with one trigger
  203. **/
  204. public static get HasTriggers(): boolean {
  205. for (var t in ActionManager.Triggers) {
  206. if (ActionManager.Triggers.hasOwnProperty(t)) {
  207. return true;
  208. }
  209. }
  210. return false;
  211. }
  212. /**
  213. * Does exist one action manager with at least one pick trigger
  214. * @return {boolean} whether or not it exists one action manager with one pick trigger
  215. **/
  216. public static get HasPickTriggers(): boolean {
  217. for (var t in ActionManager.Triggers) {
  218. if (ActionManager.Triggers.hasOwnProperty(t)) {
  219. let t_int = parseInt(t);
  220. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  221. return true;
  222. }
  223. }
  224. }
  225. return false;
  226. }
  227. /**
  228. * Does exist one action manager that handles actions of a given trigger
  229. * @param {number} trigger - the trigger to be tested
  230. * @return {boolean} whether the trigger is handeled by at least one action manager
  231. **/
  232. public static HasSpecificTrigger(trigger: number): boolean {
  233. for (var t in ActionManager.Triggers) {
  234. if (ActionManager.Triggers.hasOwnProperty(t)) {
  235. let t_int = parseInt(t);
  236. if (t_int === trigger) {
  237. return true;
  238. }
  239. }
  240. }
  241. return false;
  242. }
  243. /**
  244. * Registers an action to this action manager
  245. * @param {BABYLON.Action} action - the action to be registered
  246. * @return {BABYLON.Action} the action amended (prepared) after registration
  247. */
  248. public registerAction(action: Action): Nullable<Action> {
  249. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  250. if (this.getScene().actionManager !== this) {
  251. Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  252. return null;
  253. }
  254. }
  255. this.actions.push(action);
  256. if (ActionManager.Triggers[action.trigger]) {
  257. ActionManager.Triggers[action.trigger]++;
  258. }
  259. else {
  260. ActionManager.Triggers[action.trigger] = 1;
  261. }
  262. action._actionManager = this;
  263. action._prepare();
  264. return action;
  265. }
  266. /**
  267. * Process a specific trigger
  268. * @param {number} trigger - the trigger to process
  269. * @param evt {BABYLON.ActionEvent} the event details to be processed
  270. */
  271. public processTrigger(trigger: number, evt?: ActionEvent): void {
  272. for (var index = 0; index < this.actions.length; index++) {
  273. var action = this.actions[index];
  274. if (action.trigger === trigger) {
  275. if (evt) {
  276. if (trigger === ActionManager.OnKeyUpTrigger
  277. || trigger === ActionManager.OnKeyDownTrigger) {
  278. var parameter = action.getTriggerParameter();
  279. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  280. if (!parameter.toLowerCase) {
  281. continue;
  282. }
  283. var lowerCase = parameter.toLowerCase();
  284. if (lowerCase !== evt.sourceEvent.key) {
  285. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  286. var actualkey = String.fromCharCode(unicode).toLowerCase();
  287. if (actualkey !== lowerCase) {
  288. continue;
  289. }
  290. }
  291. }
  292. }
  293. }
  294. action._executeCurrent(evt);
  295. }
  296. }
  297. }
  298. public _getEffectiveTarget(target: any, propertyPath: string): any {
  299. var properties = propertyPath.split(".");
  300. for (var index = 0; index < properties.length - 1; index++) {
  301. target = target[properties[index]];
  302. }
  303. return target;
  304. }
  305. public _getProperty(propertyPath: string): string {
  306. var properties = propertyPath.split(".");
  307. return properties[properties.length - 1];
  308. }
  309. public serialize(name: string): any {
  310. var root = {
  311. children: new Array(),
  312. name: name,
  313. type: 3, // Root node
  314. properties: new Array() // Empty for root but required
  315. };
  316. for (var i = 0; i < this.actions.length; i++) {
  317. var triggerObject = {
  318. type: 0, // Trigger
  319. children: new Array(),
  320. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  321. properties: new Array()
  322. };
  323. var triggerOptions = this.actions[i].triggerOptions;
  324. if (triggerOptions && typeof triggerOptions !== "number") {
  325. if (triggerOptions.parameter instanceof Node) {
  326. triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter));
  327. }
  328. else {
  329. var parameter = <any>{};
  330. Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  331. if (triggerOptions.parameter.mesh) {
  332. parameter._meshId = triggerOptions.parameter.mesh.id;
  333. }
  334. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  335. }
  336. }
  337. // Serialize child action, recursively
  338. this.actions[i].serialize(triggerObject);
  339. // Add serialized trigger
  340. root.children.push(triggerObject);
  341. }
  342. return root;
  343. }
  344. public static Parse(parsedActions: any, object: AbstractMesh, scene: Scene) {
  345. var actionManager = new BABYLON.ActionManager(scene);
  346. if (object === null)
  347. scene.actionManager = actionManager;
  348. else
  349. object.actionManager = actionManager;
  350. // instanciate a new object
  351. var instanciate = (name: string, params: Array<any>): any => {
  352. var newInstance: Object = Object.create(Tools.Instantiate("BABYLON." + name).prototype);
  353. newInstance.constructor.apply(newInstance, params);
  354. return newInstance;
  355. };
  356. var parseParameter = (name: string, value: string, target: any, propertyPath: Nullable<string>): any => {
  357. if (propertyPath === null) {
  358. // String, boolean or float
  359. var floatValue = parseFloat(value);
  360. if (value === "true" || value === "false")
  361. return value === "true";
  362. else
  363. return isNaN(floatValue) ? value : floatValue;
  364. }
  365. var effectiveTarget = propertyPath.split(".");
  366. var values = value.split(",");
  367. // Get effective Target
  368. for (var i = 0; i < effectiveTarget.length; i++) {
  369. target = target[effectiveTarget[i]];
  370. }
  371. // Return appropriate value with its type
  372. if (typeof (target) === "boolean")
  373. return values[0] === "true";
  374. if (typeof (target) === "string")
  375. return values[0];
  376. // Parameters with multiple values such as Vector3 etc.
  377. var split = new Array<number>();
  378. for (var i = 0; i < values.length; i++)
  379. split.push(parseFloat(values[i]));
  380. if (target instanceof Vector3)
  381. return Vector3.FromArray(split);
  382. if (target instanceof Vector4)
  383. return Vector4.FromArray(split);
  384. if (target instanceof Color3)
  385. return Color3.FromArray(split);
  386. if (target instanceof Color4)
  387. return Color4.FromArray(split);
  388. return parseFloat(values[0]);
  389. };
  390. // traverse graph per trigger
  391. var traverse = (parsedAction: any, trigger: any, condition: Nullable<Condition>, action: Nullable<Action>, combineArray: Nullable<Array<Action>> = null) => {
  392. if (parsedAction.detached)
  393. return;
  394. var parameters = new Array<any>();
  395. var target: any = null;
  396. var propertyPath: Nullable<string> = null;
  397. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  398. // Parameters
  399. if (parsedAction.type === 2)
  400. parameters.push(actionManager);
  401. else
  402. parameters.push(trigger);
  403. if (combine) {
  404. var actions = new Array<Action>();
  405. for (var j = 0; j < parsedAction.combine.length; j++) {
  406. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  407. }
  408. parameters.push(actions);
  409. }
  410. else {
  411. for (var i = 0; i < parsedAction.properties.length; i++) {
  412. var value = parsedAction.properties[i].value;
  413. var name = parsedAction.properties[i].name;
  414. var targetType = parsedAction.properties[i].targetType;
  415. if (name === "target")
  416. if (targetType !== null && targetType === "SceneProperties")
  417. value = target = scene;
  418. else
  419. value = target = scene.getNodeByName(value);
  420. else if (name === "parent")
  421. value = scene.getNodeByName(value);
  422. else if (name === "sound")
  423. value = scene.getSoundByName(value);
  424. else if (name !== "propertyPath") {
  425. if (parsedAction.type === 2 && name === "operator")
  426. value = (<any>ValueCondition)[value];
  427. else
  428. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  429. } else {
  430. propertyPath = value;
  431. }
  432. parameters.push(value);
  433. }
  434. }
  435. if (combineArray === null) {
  436. parameters.push(condition);
  437. }
  438. else {
  439. parameters.push(null);
  440. }
  441. // If interpolate value action
  442. if (parsedAction.name === "InterpolateValueAction") {
  443. var param = parameters[parameters.length - 2];
  444. parameters[parameters.length - 1] = param;
  445. parameters[parameters.length - 2] = condition;
  446. }
  447. // Action or condition(s) and not CombineAction
  448. var newAction = instanciate(parsedAction.name, parameters);
  449. if (newAction instanceof Condition && condition !== null) {
  450. var nothing = new DoNothingAction(trigger, condition);
  451. if (action)
  452. action.then(nothing);
  453. else
  454. actionManager.registerAction(nothing);
  455. action = nothing;
  456. }
  457. if (combineArray === null) {
  458. if (newAction instanceof Condition) {
  459. condition = newAction;
  460. newAction = action;
  461. } else {
  462. condition = null;
  463. if (action)
  464. action.then(newAction);
  465. else
  466. actionManager.registerAction(newAction);
  467. }
  468. }
  469. else {
  470. combineArray.push(newAction);
  471. }
  472. for (var i = 0; i < parsedAction.children.length; i++)
  473. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  474. };
  475. // triggers
  476. for (var i = 0; i < parsedActions.children.length; i++) {
  477. var triggerParams: any;
  478. var trigger = parsedActions.children[i];
  479. if (trigger.properties.length > 0) {
  480. var param = trigger.properties[0].value;
  481. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  482. if (value._meshId) {
  483. value.mesh = scene.getMeshByID(value._meshId);
  484. }
  485. triggerParams = { trigger: (<any>ActionManager)[trigger.name], parameter: value };
  486. }
  487. else
  488. triggerParams = (<any>ActionManager)[trigger.name];
  489. for (var j = 0; j < trigger.children.length; j++) {
  490. if (!trigger.detached)
  491. traverse(trigger.children[j], triggerParams, null, null);
  492. }
  493. }
  494. }
  495. public static GetTriggerName(trigger: number): string {
  496. switch (trigger) {
  497. case 0: return "NothingTrigger";
  498. case 1: return "OnPickTrigger";
  499. case 2: return "OnLeftPickTrigger";
  500. case 3: return "OnRightPickTrigger";
  501. case 4: return "OnCenterPickTrigger";
  502. case 5: return "OnPickDownTrigger";
  503. case 6: return "OnPickUpTrigger";
  504. case 7: return "OnLongPressTrigger";
  505. case 8: return "OnPointerOverTrigger";
  506. case 9: return "OnPointerOutTrigger";
  507. case 10: return "OnEveryFrameTrigger";
  508. case 11: return "OnIntersectionEnterTrigger";
  509. case 12: return "OnIntersectionExitTrigger";
  510. case 13: return "OnKeyDownTrigger";
  511. case 14: return "OnKeyUpTrigger";
  512. case 15: return "OnPickOutTrigger";
  513. default: return "";
  514. }
  515. }
  516. }
  517. }