UNPKG

@needle-tools/engine

Version:

Needle Engine is a web-based runtime for 3D apps. It runs on your machine for development with great integrations into editors like Unity or Blender - and can be deployed onto any device! It is flexible, extensible and networking and XR are built-in

643 lines • 24.7 kB
import { Object3D, Vector3 } from "three"; import { isDevEnvironment } from "../engine/debug/index.js"; import { addComponent, destroyComponentInstance, findObjectOfType, findObjectsOfType, getComponent, getComponentInChildren, getComponentInParent, getComponents, getComponentsInChildren, getComponentsInParent, getOrAddComponent, removeComponent } from "../engine/engine_components.js"; import { activeInHierarchyFieldName } from "../engine/engine_constants.js"; import { destroy, findByGuid, foreachComponent, instantiate, isActiveInHierarchy, isActiveSelf, isDestroyed, isUsingInstancing, markAsInstancedRendered, setActive } from "../engine/engine_gameobject.js"; import * as main from "../engine/engine_mainloop_utils.js"; import { syncDestroy, syncInstantiate } from "../engine/engine_networking_instantiate.js"; import { Context, FrameEvent } from "../engine/engine_setup.js"; import * as threeutils from "../engine/engine_three_utils.js"; // export interface ISerializationCallbackReceiver { // onBeforeSerialize?(): object | void; // onAfterSerialize?(); // onBeforeDeserialize?(data?: any); // onAfterDeserialize?(); // onDeserialize?(key: string, value: any): any | void; // } /** * All {@type Object3D} types that are loaded in Needle Engine do automatically receive the GameObject extensions like `addComponent` etc. * Many of the GameObject methods can be imported directly via `@needle-tools/engine` as well: * ```typescript * import { addComponent } from "@needle-tools/engine"; * ``` */ export class GameObject extends Object3D { guid; static isDestroyed(go) { return isDestroyed(go); } static setActive(go, active, processStart = true) { if (!go) return; setActive(go, active); // TODO: do we still need this?: main.updateIsActive(go); if (active && processStart) main.processStart(Context.Current, go); } /** If the object is active (same as go.visible) */ static isActiveSelf(go) { return isActiveSelf(go); } /** If the object is active in the hierarchy (e.g. if any parent is invisible or not in the scene it will be false) * @param go object to check */ static isActiveInHierarchy(go) { return isActiveInHierarchy(go); } static markAsInstancedRendered(go, instanced) { markAsInstancedRendered(go, instanced); } static isUsingInstancing(instance) { return isUsingInstancing(instance); } /** Run a callback for all components of the provided type on the provided object and its children (if recursive is true) * @param instance object to run the method on * @param cb callback to run on each component, "return undefined;" to continue and "return <anything>;" to break the loop * @param recursive if true, the method will be run on all children as well * @returns the last return value of the callback */ static foreachComponent(instance, cb, recursive = true) { return foreachComponent(instance, cb, recursive); } /** Creates a new instance of the provided object. The new instance will be created on all connected clients * @param instance object to instantiate * @param opts options for the instantiation */ static instantiateSynced(instance, opts) { if (!instance) return null; return syncInstantiate(instance, opts); } /** Creates a new instance of the provided object (like cloning it including all components and children) * @param instance object to instantiate * @param opts options for the instantiation (e.g. with what parent, position, etc.) */ static instantiate(instance, opts = null) { return instantiate(instance, opts); } /** Destroys a object on all connected clients (if you are in a networked session) * @param instance object to destroy */ static destroySynced(instance, context, recursive = true) { if (!instance) return; const go = instance; context = context ?? Context.Current; syncDestroy(go, context.connection, recursive); } /** Destroys a object * @param instance object to destroy * @param recursive if true, all children will be destroyed as well. true by default */ static destroy(instance, recursive = true) { return destroy(instance, recursive); } /** * Add an object to parent and also ensure all components are being registered */ static add(instance, parent, context) { if (!instance || !parent) return; if (instance === parent) { console.warn("Can not add object to self", instance); return; } if (!context) { context = Context.Current; } parent.add(instance); setActive(instance, true); main.updateIsActive(instance); if (context) { GameObject.foreachComponent(instance, (comp) => { main.addScriptToArrays(comp, context); if (comp.__internalDidAwakeAndStart) return; if (context.new_script_start.includes(comp) === false) { context.new_script_start.push(comp); } }, true); } else { console.warn("Missing context"); } } /** * Removes the object from its parent and deactivates all of its components */ static remove(instance) { if (!instance) return; instance.parent?.remove(instance); setActive(instance, false); main.updateIsActive(instance); GameObject.foreachComponent(instance, (comp) => { main.processRemoveFromScene(comp); }, true); } /** Invokes a method on all components including children (if a method with that name exists) */ static invokeOnChildren(go, functionName, ...args) { this.invoke(go, functionName, true, args); } /** Invokes a method on all components that have a method matching the provided name * @param go object to invoke the method on all components * @param functionName name of the method to invoke */ static invoke(go, functionName, children = false, ...args) { if (!go) return; this.foreachComponent(go, c => { const fn = c[functionName]; if (fn && typeof fn === "function") { fn?.call(c, ...args); } }, children); } /** @deprecated use `addComponent` */ // eslint-disable-next-line deprecation/deprecation static addNewComponent(go, type, init, callAwake = true) { return addComponent(go, type, init, { callAwake }); } /** * Add a new component (or move an existing component) to the provided object * @param go object to add the component to * @param instanceOrType if an instance is provided it will be moved to the new object, if a type is provided a new instance will be created and moved to the new object * @param init optional init object to initialize the component with * @param callAwake if true, the component will be added and awake will be called immediately */ static addComponent(go, instanceOrType, init, opts) { return addComponent(go, instanceOrType, init, opts); } /** * Moves a component to a new object * @param go component to move the component to * @param instance component to move to the GO */ static moveComponent(go, instance) { return addComponent(go, instance); } /** Removes a component from its object * @param instance component to remove */ static removeComponent(instance) { removeComponent(instance.gameObject, instance); return instance; } static getOrAddComponent(go, typeName) { return getOrAddComponent(go, typeName); } /** Gets a component on the provided object */ static getComponent(go, typeName) { if (go === null) return null; // if names are minified we could also use the type store and work with strings everywhere // not ideal, but I dont know a good/sane way to do this otherwise // const res = TypeStore.get(typeName); // if(res) typeName = res; return getComponent(go, typeName); } static getComponents(go, typeName, arr = null) { if (go === null) return arr ?? []; return getComponents(go, typeName, arr); } static findByGuid(guid, hierarchy) { const res = findByGuid(guid, hierarchy); return res; } static findObjectOfType(typeName, context, includeInactive = true) { return findObjectOfType(typeName, context ?? Context.Current, includeInactive); } static findObjectsOfType(typeName, context) { const arr = []; findObjectsOfType(typeName, arr, context); return arr; } static getComponentInChildren(go, typeName) { return getComponentInChildren(go, typeName); } static getComponentsInChildren(go, typeName, arr = null) { return getComponentsInChildren(go, typeName, arr ?? undefined); } static getComponentInParent(go, typeName) { return getComponentInParent(go, typeName); } static getComponentsInParent(go, typeName, arr = null) { return getComponentsInParent(go, typeName, arr); } static getAllComponents(go) { const componentsList = go.userData?.components; if (!componentsList) return []; const newList = [...componentsList]; return newList; } static *iterateComponents(go) { const list = go?.userData?.components; if (list && Array.isArray(list)) { for (let i = 0; i < list.length; i++) { yield list[i]; } } } } /** * Needle Engine component base class. Component's are the main building blocks of the Needle Engine. * Derive from {@link Behaviour} to implement your own using the provided lifecycle methods. * Components can be added to any {@link Object3D} using {@link addComponent} or {@link GameObject.addComponent}. * * The most common lifecycle methods are {@link update}, {@link awake}, {@link start}, {@link onEnable}, {@link onDisable} and {@link onDestroy}. * * XR specific callbacks include {@link onEnterXR}, {@link onLeaveXR}, {@link onUpdateXR}, {@link onXRControllerAdded} and {@link onXRControllerRemoved}. * * To receive pointer events implement {@link onPointerDown}, {@link onPointerUp}, {@link onPointerEnter}, {@link onPointerExit} and {@link onPointerMove}. * * @example * ```typescript * import { Behaviour } from "@needle-tools/engine"; * export class MyComponent extends Behaviour { * start() { * console.log("Hello World"); * } * update() { * console.log("Frame", this.context.time.frame); * } * } * ``` * * @group Components */ export class Component { /** @internal */ get isComponent() { return true; } __context; /** Use the context to get access to many Needle Engine features and use physics, timing, access the camera or scene */ get context() { return this.__context ?? Context.Current; } set context(context) { this.__context = context; } /** shorthand for `this.context.scene` * @returns the scene of the context */ get scene() { return this.context.scene; } /** @returns the layer of the gameObject this component is attached to */ get layer() { return this.gameObject?.userData?.layer; } /** @returns the name of the gameObject this component is attached to */ get name() { if (this.gameObject?.name) { return this.gameObject.name; } return this.gameObject?.userData.name; } __name; set name(str) { if (this.gameObject) { if (!this.gameObject.userData) this.gameObject.userData = {}; this.gameObject.userData.name = str; this.__name = str; } else { this.__name = str; } } /** @returns the tag of the gameObject this component is attached to */ get tag() { return this.gameObject?.userData.tag; } set tag(str) { if (this.gameObject) { if (!this.gameObject.userData) this.gameObject.userData = {}; this.gameObject.userData.tag = str; } } /** Is the gameObject marked as static */ get static() { return this.gameObject?.userData.static; } set static(value) { if (this.gameObject) { if (!this.gameObject.userData) this.gameObject.userData = {}; this.gameObject.userData.static = value; } } get hideFlags() { return this.gameObject?.userData.hideFlags; } /** @returns true if the object is enabled and active in the hierarchy */ get activeAndEnabled() { if (this.destroyed) return false; if (this.__isEnabled === false) return false; if (!this.__isActiveInHierarchy) return false; // let go = this.gameObject; // do { // // console.log(go.name, go.visible) // if (!go.visible) return false; // go = go.parent as GameObject; // } // while (go); return true; } get __isActive() { return this.gameObject.visible; } get __isActiveInHierarchy() { if (!this.gameObject) return false; const res = this.gameObject[activeInHierarchyFieldName]; if (res === undefined) return true; return res; } set __isActiveInHierarchy(val) { if (!this.gameObject) return; this.gameObject[activeInHierarchyFieldName] = val; } /** the object this component is attached to. Note that this is a threejs Object3D with some additional features */ gameObject; /** the unique identifier for this component */ guid = "invalid"; /** holds the source identifier this object was created with/from (e.g. if it was part of a glTF file the sourceId holds the url to the glTF) */ sourceId; /** called once when the component becomes active for the first time (once per component) * This is the first callback to be called */ awake() { } /** called every time when the component gets enabled (this is invoked after awake and before start) * or when it becomes active in the hierarchy (e.g. if a parent object or this.gameObject gets set to visible) */ onEnable() { } /** called every time the component gets disabled or if a parent object (or this.gameObject) gets set to invisible */ onDisable() { } /** Called when the component gets destroyed */ onDestroy() { this.__destroyed = true; } /** starts a coroutine (javascript generator function) * `yield` will wait for the next frame: * - Use `yield WaitForSeconds(1)` to wait for 1 second. * - Use `yield WaitForFrames(10)` to wait for 10 frames. * - Use `yield new Promise(...)` to wait for a promise to resolve. * @param routine generator function to start * @param evt event to register the coroutine for (default: FrameEvent.Update). Note that all coroutine FrameEvent callbacks are invoked after the matching regular component callbacks. For example `FrameEvent.Update` will be called after regular component `update()` methods) * @returns the generator function (use it to stop the coroutine with `stopCoroutine`) * @example * ```ts * onEnable() { this.startCoroutine(this.myCoroutine()); } * private *myCoroutine() { * while(this.activeAndEnabled) { * console.log("Hello World", this.context.time.frame); * // wait for 5 frames * for(let i = 0; i < 5; i++) yield; * } * } * ``` */ startCoroutine(routine, evt = FrameEvent.Update) { return this.context.registerCoroutineUpdate(this, routine, evt); } /** * Stop a coroutine that was previously started with `startCoroutine` * @param routine the routine to be stopped * @param evt the frame event to unregister the routine from (default: FrameEvent.Update) */ stopCoroutine(routine, evt = FrameEvent.Update) { this.context.unregisterCoroutineUpdate(routine, evt); } /** @returns true if this component was destroyed (`this.destroy()`) or the whole object this component was part of */ get destroyed() { return this.__destroyed; } /** * Destroys this component (and removes it from the object) */ destroy() { if (this.__destroyed) return; this.__internalDestroy(); } /** @internal */ __didAwake = false; /** @internal */ __didStart = false; /** @internal */ __didEnable = false; /** @internal */ __isEnabled = undefined; /** @internal */ __destroyed = false; /** @internal */ get __internalDidAwakeAndStart() { return this.__didAwake && this.__didStart; } /** @internal */ constructor(init) { this.__didAwake = false; this.__didStart = false; this.__didEnable = false; this.__isEnabled = undefined; this.__destroyed = false; this._internalInit(init); } /** @internal */ __internalNewInstanceCreated(init) { this.__didAwake = false; this.__didStart = false; this.__didEnable = false; this.__isEnabled = undefined; this.__destroyed = false; this._internalInit(init); return this; } _internalInit(init) { if (typeof init === "object") { for (const key of Object.keys(init)) { const value = init[key]; // we don't want to allow overriding functions via init if (typeof value === "function") continue; this[key] = value; } } } /** @internal */ __internalAwake() { if (this.__didAwake) return; this.__didAwake = true; this.awake(); } /** @internal */ __internalStart() { if (this.__didStart) return; this.__didStart = true; if (this.start) this.start(); } /** @internal */ __internalEnable(isAddingToScene) { if (this.__destroyed) { if (isDevEnvironment()) { console.warn("[Needle Engine Dev] Trying to enable destroyed component"); } return false; } // Don't change enable before awake // But a user can change enable during awake if (!this.__didAwake) return false; if (this.__didEnable) { // We dont want to change the enable state if we are adding to scene // But we want to change the state when e.g. a user changes the enable state during awake if (isAddingToScene !== true) this.__isEnabled = true; return false; } // console.trace("INTERNAL ENABLE"); this.__didEnable = true; this.__isEnabled = true; this.onEnable(); return true; } /** @internal */ __internalDisable(isRemovingFromScene) { // Don't change enable before awake // But a user can change enable during awake if (!this.__didAwake) return; if (!this.__didEnable) { // We dont want to change the enable state if we are removing from a scene if (isRemovingFromScene !== true) this.__isEnabled = false; return; } this.__didEnable = false; this.__isEnabled = false; this.onDisable(); } /** @internal */ __internalDestroy() { if (this.__destroyed) return; this.__destroyed = true; if (this.__didAwake) { this.onDestroy?.call(this); this.dispatchEvent(new CustomEvent("destroyed", { detail: this })); } destroyComponentInstance(this); } get enabled() { return typeof this.__isEnabled === "boolean" ? this.__isEnabled : true; // if it has no enabled field it is always enabled } set enabled(val) { if (this.__destroyed) { if (isDevEnvironment()) { console.warn(`[Needle Engine Dev] Trying to ${val ? "enable" : "disable"} destroyed component`); } return; } // when called from animationclip we receive numbers // due to interpolation they can be anything between 0 and 1 if (typeof val === "number") { if (val >= 0.5) val = true; else val = false; } // need to check here because codegen is calling this before everything is setup if (!this.__didAwake) { this.__isEnabled = val; return; } if (val) { this.__internalEnable(); } else { this.__internalDisable(); } } get worldPosition() { return threeutils.getWorldPosition(this.gameObject); } set worldPosition(val) { threeutils.setWorldPosition(this.gameObject, val); } setWorldPosition(x, y, z) { threeutils.setWorldPositionXYZ(this.gameObject, x, y, z); } get worldQuaternion() { return threeutils.getWorldQuaternion(this.gameObject); } set worldQuaternion(val) { threeutils.setWorldQuaternion(this.gameObject, val); } setWorldQuaternion(x, y, z, w) { threeutils.setWorldQuaternionXYZW(this.gameObject, x, y, z, w); } // world euler (in radians) get worldEuler() { return threeutils.getWorldEuler(this.gameObject); } // world euler (in radians) set worldEuler(val) { threeutils.setWorldEuler(this.gameObject, val); } // returns rotation in degrees get worldRotation() { return this.gameObject.worldRotation; ; } set worldRotation(val) { this.setWorldRotation(val.x, val.y, val.z, true); } setWorldRotation(x, y, z, degrees = true) { threeutils.setWorldRotationXYZ(this.gameObject, x, y, z, degrees); } static _forward = new Vector3(); /** Forward (0,0,-1) vector in world space */ get forward() { return Component._forward.set(0, 0, -1).applyQuaternion(this.worldQuaternion); } static _right = new Vector3(); /** Right (1,0,0) vector in world space */ get right() { return Component._right.set(1, 0, 0).applyQuaternion(this.worldQuaternion); } static _up = new Vector3(); /** Up (0,1,0) vector in world space */ get up() { return Component._up.set(0, 1, 0).applyQuaternion(this.worldQuaternion); } // EventTarget implementation: _eventListeners = new Map(); addEventListener(type, listener) { this._eventListeners[type] = this._eventListeners[type] || []; this._eventListeners[type].push(listener); } removeEventListener(type, listener) { if (!this._eventListeners[type]) return; const index = this._eventListeners[type].indexOf(listener); if (index >= 0) this._eventListeners[type].splice(index, 1); } dispatchEvent(evt) { if (!evt || !this._eventListeners[evt.type]) return false; const listeners = this._eventListeners[evt.type]; for (let i = 0; i < listeners.length; i++) { listeners[i](evt); } return false; } } // For legacy reasons we need to export this as well // (and we don't use extend to inherit the component docs) export { Component as Behaviour }; //# sourceMappingURL=Component.js.map