|
| 1 | +import Node from '../core/Node.js'; |
| 2 | +import { NodeUpdateType } from '../core/constants.js'; |
| 3 | +import { nodeObject } from '../tsl/TSLCore.js'; |
| 4 | + |
| 5 | +/** |
| 6 | + * EventNode is a node that executes a callback during specific update phases. |
| 7 | + * |
| 8 | + * @augments Node |
| 9 | + */ |
| 10 | +class EventNode extends Node { |
| 11 | + |
| 12 | + static get type() { |
| 13 | + |
| 14 | + return 'EventNode'; |
| 15 | + |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Creates an EventNode. |
| 20 | + * |
| 21 | + * @param {string} eventType - The type of event |
| 22 | + * @param {Function} callback - The callback to execute on update. |
| 23 | + */ |
| 24 | + constructor( eventType, callback ) { |
| 25 | + |
| 26 | + super( 'void' ); |
| 27 | + |
| 28 | + this.eventType = eventType; |
| 29 | + this.callback = callback; |
| 30 | + |
| 31 | + if ( eventType === EventNode.OBJECT ) { |
| 32 | + |
| 33 | + this.updateType = NodeUpdateType.OBJECT; |
| 34 | + |
| 35 | + } else if ( eventType === EventNode.MATERIAL ) { |
| 36 | + |
| 37 | + this.updateType = NodeUpdateType.RENDER; |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + update( frame ) { |
| 44 | + |
| 45 | + this.callback( frame ); |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | +} |
| 50 | + |
| 51 | +EventNode.OBJECT = 'object'; |
| 52 | +EventNode.MATERIAL = 'material'; |
| 53 | + |
| 54 | +export default EventNode; |
| 55 | + |
| 56 | +/** |
| 57 | + * Helper to create an EventNode and add it to the stack. |
| 58 | + * |
| 59 | + * @param {string} type - The event type. |
| 60 | + * @param {Function} callback - The callback function. |
| 61 | + * @returns {EventNode} |
| 62 | + */ |
| 63 | +const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack(); |
| 64 | + |
| 65 | +/** |
| 66 | + * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered. |
| 67 | + * |
| 68 | + * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one. |
| 69 | + * |
| 70 | + * @param {Function} callback - The callback function. |
| 71 | + * @returns {EventNode} |
| 72 | + */ |
| 73 | +export const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback ); |
| 74 | + |
| 75 | +/** |
| 76 | + * Creates an event that triggers a function when the first object that uses the material is rendered. |
| 77 | + * |
| 78 | + * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one. |
| 79 | + * |
| 80 | + * @param {Function} callback - The callback function. |
| 81 | + * @returns {EventNode} |
| 82 | + */ |
| 83 | +export const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback ); |
0 commit comments