@luminocity/lemonate-engine 26.6.1 → 26.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/LoadingManager.d.ts +1 -0
- package/dist/lemonate.es.js +130 -15
- package/dist/lemonate.js +174 -59
- package/dist/lemonate.min.js +14 -14
- package/dist/lemonate.umd.js +130 -15
- package/dist/player.zip +0 -0
- package/dist/subsystems/scripting/ScriptEngine.d.ts +3 -0
- package/dist/subsystems/scripting/ScriptRunner.d.ts +3 -0
- package/dist/subsystems/scripting/runtime/RtItem.d.ts +1 -1
- package/package.json +2 -2
package/dist/LoadingManager.d.ts
CHANGED
|
@@ -349,6 +349,7 @@ export declare class LoadingManager {
|
|
|
349
349
|
_initFromItem(item: PreparedItem): void;
|
|
350
350
|
_initFromFields(fields: Field[]): void;
|
|
351
351
|
_initFromBlocks(blocks: Block[]): void;
|
|
352
|
+
_initFromScripts(scripts: any[]): void;
|
|
352
353
|
isItemLoaded(id: string): boolean;
|
|
353
354
|
removeItem(id: string): void;
|
|
354
355
|
addItem(item: PreparedItem): void;
|
package/dist/lemonate.es.js
CHANGED
|
@@ -11447,7 +11447,7 @@ class Item extends EventEmitter {
|
|
|
11447
11447
|
}
|
|
11448
11448
|
}
|
|
11449
11449
|
|
|
11450
|
-
var engine$1 = "26.6.
|
|
11450
|
+
var engine$1 = "26.6.4";
|
|
11451
11451
|
var bullet = "3.26";
|
|
11452
11452
|
var lua = "5.4.3";
|
|
11453
11453
|
var packageVersionInfo = {
|
|
@@ -68131,7 +68131,7 @@ class RenderView {
|
|
|
68131
68131
|
// ----------------------------------------------------------------------------------
|
|
68132
68132
|
if (!renderPassInfo.playerIsPaused) {
|
|
68133
68133
|
if (doPhysics) {
|
|
68134
|
-
this.engine.profiler.
|
|
68134
|
+
await this.engine.profiler.measureAsync("Physics", "processUpdate", async () => {
|
|
68135
68135
|
this.engine.physics.processPhysicsUpdate();
|
|
68136
68136
|
});
|
|
68137
68137
|
}
|
|
@@ -68181,7 +68181,7 @@ class RenderView {
|
|
|
68181
68181
|
// Animate scene
|
|
68182
68182
|
// ----------------------------------------------------------------------------------
|
|
68183
68183
|
if (!renderPassInfo.playerIsPaused) {
|
|
68184
|
-
this.engine.profiler.
|
|
68184
|
+
await this.engine.profiler.measureAsync("RenderView", "animate", async () => {
|
|
68185
68185
|
this._animate(sceneGraphCollection, renderPassInfo.deltaPlayerTimeMs);
|
|
68186
68186
|
});
|
|
68187
68187
|
}
|
|
@@ -70672,7 +70672,7 @@ class Renderer {
|
|
|
70672
70672
|
}
|
|
70673
70673
|
renderParticleSystems(renderPassInfo) {
|
|
70674
70674
|
if (this.particleSystems && !renderPassInfo.playerIsPaused) {
|
|
70675
|
-
this.engine.profiler.measure("Particles", "render",
|
|
70675
|
+
this.engine.profiler.measure("Particles", "render", () => {
|
|
70676
70676
|
this.particleSystems.forEach(system => {
|
|
70677
70677
|
system.setSize(renderPassInfo.resolution.x, renderPassInfo.resolution.y);
|
|
70678
70678
|
// in the testing environment a time provider has been set.
|
|
@@ -94883,12 +94883,35 @@ class LoadingManager {
|
|
|
94883
94883
|
if (block.fields && block.fields.length) {
|
|
94884
94884
|
this._initFromFields(block.fields);
|
|
94885
94885
|
}
|
|
94886
|
+
if (block.scripts && block.scripts.length) {
|
|
94887
|
+
this._initFromScripts(block.scripts);
|
|
94888
|
+
}
|
|
94886
94889
|
if (block.blocks && block.blocks.length) {
|
|
94887
94890
|
this._initFromBlocks(block.blocks);
|
|
94888
94891
|
}
|
|
94889
94892
|
}
|
|
94890
94893
|
}
|
|
94891
94894
|
}
|
|
94895
|
+
_initFromScripts(scripts) {
|
|
94896
|
+
for (const script of scripts) {
|
|
94897
|
+
if (!script.fields)
|
|
94898
|
+
continue;
|
|
94899
|
+
for (const field of script.fields) {
|
|
94900
|
+
if (field.type === 'Link' && field.value) {
|
|
94901
|
+
const preparedItem = typeof field.value === 'string' ? { _id: field.value } : field.value;
|
|
94902
|
+
if (preparedItem._id)
|
|
94903
|
+
this._initFromItem(preparedItem);
|
|
94904
|
+
}
|
|
94905
|
+
else if (field.type === 'LinkArray' && Array.isArray(field.value)) {
|
|
94906
|
+
for (const linkValue of field.value) {
|
|
94907
|
+
const preparedItem = typeof linkValue === 'string' ? { _id: linkValue } : linkValue;
|
|
94908
|
+
if (preparedItem && preparedItem._id)
|
|
94909
|
+
this._initFromItem(preparedItem);
|
|
94910
|
+
}
|
|
94911
|
+
}
|
|
94912
|
+
}
|
|
94913
|
+
}
|
|
94914
|
+
}
|
|
94892
94915
|
isItemLoaded(id) {
|
|
94893
94916
|
return this.itemsMap.has(id);
|
|
94894
94917
|
}
|
|
@@ -95706,6 +95729,7 @@ class ScriptRunner {
|
|
|
95706
95729
|
scriptItem = undefined;
|
|
95707
95730
|
scriptId = undefined;
|
|
95708
95731
|
injectedFieldsMap = {};
|
|
95732
|
+
referenceId = undefined;
|
|
95709
95733
|
callDepth = 0;
|
|
95710
95734
|
callMutex = new Mutex();
|
|
95711
95735
|
enableMutex = new Mutex();
|
|
@@ -95762,14 +95786,25 @@ class ScriptRunner {
|
|
|
95762
95786
|
setNode(node) {
|
|
95763
95787
|
this.injectedFieldsMap["node"] = { type: 'String', value: node };
|
|
95764
95788
|
}
|
|
95789
|
+
setReferenceId(referenceId) {
|
|
95790
|
+
this.referenceId = referenceId;
|
|
95791
|
+
}
|
|
95792
|
+
getReferenceId() {
|
|
95793
|
+
return this.referenceId || this.scriptId || '';
|
|
95794
|
+
}
|
|
95765
95795
|
setInjectedFields(fields) {
|
|
95766
95796
|
for (const field of fields) {
|
|
95767
|
-
if (!
|
|
95768
|
-
|
|
95769
|
-
|
|
95770
|
-
|
|
95771
|
-
|
|
95772
|
-
|
|
95797
|
+
if (!field.name || field.type === 'Separator')
|
|
95798
|
+
continue;
|
|
95799
|
+
const entryType = field.type === 'Link' || field.type === 'LinkArray'
|
|
95800
|
+
? field.type
|
|
95801
|
+
: field.datatype;
|
|
95802
|
+
if (field.name === 'node' && this.injectedFieldsMap['node'])
|
|
95803
|
+
continue;
|
|
95804
|
+
this.injectedFieldsMap[field.name] = {
|
|
95805
|
+
type: entryType,
|
|
95806
|
+
value: field.value
|
|
95807
|
+
};
|
|
95773
95808
|
}
|
|
95774
95809
|
}
|
|
95775
95810
|
getInjectedFields() {
|
|
@@ -96296,6 +96331,7 @@ class SceneGraphCollection {
|
|
|
96296
96331
|
const name = script.getName();
|
|
96297
96332
|
const item = script.getItem();
|
|
96298
96333
|
const runner = new ScriptRunner(this.engine);
|
|
96334
|
+
runner.setReferenceId(instanceId);
|
|
96299
96335
|
runner.setNode(node);
|
|
96300
96336
|
runner.setInjectedFields(meta.fields);
|
|
96301
96337
|
const scriptId = await runner.loadCode(script);
|
|
@@ -98985,11 +99021,11 @@ var lua_api_internal = "\nlocal msgpack = require('engine/msgpack');\nlocal pack
|
|
|
98985
99021
|
|
|
98986
99022
|
var lua_api_audio = "\nlocal _internal = require('engine/_internal');\n\n--- @module audio\nlocal audio = {}\n\n---Get an FFT analysis from the audio engine. It returns an array of 256 samples\n---@function getAnalysis\nfunction audio.getAnalysis()\n return _internal.sendMessage('audio.getAnalysis')\nend\n\nreturn audio\n";
|
|
98987
99023
|
|
|
98988
|
-
var lua_api_behaviour = "local SceneObject = require('engine/sceneobject')\nlocal Canvas = require('engine/canvas')\nlocal JE = require('engine/json/jsonencoder')()\n\nlocal _behavioursMapByNodeId = {}\nlocal _behavioursMapByScriptId = {}\nlocal _behavioursMapByExecutionOrder = {}\nlocal _executionIndex = 1\n\nlocal Behaviour = Class.new()\n\n-- Put the class in the global scope (Behaviour is the old deprecated name)\n_G.Behaviour = Behaviour\n_G.Entity = Behaviour\n\n--- Constructor hook called when a new Behaviour is created.\n---@private\nfunction Behaviour:__new()\n self._isBehaviour = true\n self._type = \"Behaviour\"\n self._nodeId = nil\n self._scriptName = \"\"\n self._executionIndex = _executionIndex\n self._isActive = true\n self._isInitialized = false\n\n _executionIndex = _executionIndex + 1\n\n -- Adds a default node property\n self:addProperty(\"node\", Property.Node)\nend\n\n--- Destructor hook called before the Behaviour is destroyed.\n---@private\nfunction Behaviour:__destroy()\n print(\"__destroy called for: \", self._nodeId)\nend\n\n--- Get all behaviours attached to a specific node ID.\n---@param nodeId string The ID of the scene graph node\n---@return table A table containing all behaviours attached to the node\nfunction Behaviour.getByNodeId(nodeId)\n local result = {}\n local nodeBehaviours = _behavioursMapByNodeId[nodeId]\n if nodeBehaviours then\n for k,v in pairs(nodeBehaviours) do\n table.insert(result, v.behaviour)\n end\n end\n return result\nend\n\n--- Get a single behaviour attached to a node ID with a specific script name.\n---@param nodeId string The ID of the scene graph node\n---@param scriptName string The script name of the behaviour\n---@return Behaviour|nil The behaviour if found, or nil\nfunction Behaviour.getByNodeIdAndScriptName(nodeId, scriptName)\n local nodeEntities = _behavioursMapByNodeId[nodeId]\n if nodeEntities then\n for k,v in pairs(nodeEntities) do\n if v.scriptName == scriptName then\n return v.behaviour\n end\n end\n end\n return nil\nend\n\n--- Returns the node ID this Behaviour is attached to.\n---@return string|nil Node ID of the attached scene object\nfunction Behaviour:getNodeId()\n return self._nodeId\nend\n\n--- Returns the script name of this Behaviour.\n---@return string Script name\nfunction Behaviour:getScriptName()\n return self._scriptName\nend\n\n--- Returns a table of all properties defined on the behaviour class.\n---@return table A table with fields: name, defaultValue, type, order\nfunction Behaviour:getProperties()\n local props = {}\n local class = self.getClass()\n\n for k,v in pairs(class) do\n if type(v) == 'table' and v._isProperty then\n table.insert(props, { name=k, defaultValue=v.value, type=v.datatype, order=v.order, info=v.info })\n end\n end\n\n for k,v in pairs(class.properties) do\n if type(v) == 'table' and v._isProperty then\n table.insert(props, { name=k, defaultValue=v.value, type=v.datatype, order=v.order, info=v.info })\n end\n end\n\n return props\nend\n\n--- When a script is destroyed, we need to call this to clear the behaviour out of the list\n---@private\nfunction Behaviour:_disposeBehaviour()\n local scripts = _behavioursMapByNodeId[self._nodeId]\n if scripts then\n scripts[self._scriptId] = nil\n end\n\n _behavioursMapByScriptId[self._scriptId] = nil\n _behavioursMapByExecutionOrder[self._executionIndex] = nil\nend\n\n--- Internal setter for a property\n---@private\n---@param name string Property name\n---@param value any Value to set\nfunction Behaviour:_setProperty(name, value)\n self[name] = value\nend\n\n--- Internal method to attach a scene node to this Behaviour\n---@private\n---@param msg table Contains fields: value=nodeId, scriptName, scriptId\nfunction Behaviour:_setNode(msg)\n __assertTrace(type(msg) == 'table', \"_setNode() called with nil or a non-table.\")\n\n if self.node then\n error(\"Node is already set on behaviour!\")\n end\n\n local nodeId = msg.value\n __assertTrace(type(nodeId) == 'string', \"_setNode() needs a nodeId of type string.\")\n\n local node = SceneObject.findById(nodeId)\n __assertTrace(node, \"_setNode() node not found\")\n\n local scriptName = msg.scriptName\n __assertTrace(scriptName, \"_setNode() needs a scriptName\")\n\n local scriptId = msg.scriptId\n __assertTrace(scriptId, \"_setNode() needs a scriptId\")\n\n self.node = node\n self._nodeId = nodeId\n self._scriptName = msg.scriptName\n self._scriptId = scriptId\n\n _behavioursMapByScriptId[scriptId] = self\n _behavioursMapByExecutionOrder[self._executionIndex] = self\n\n if not _behavioursMapByNodeId[nodeId] then\n _behavioursMapByNodeId[nodeId] = {}\n end\n _behavioursMapByNodeId[nodeId][scriptId] = {\n node = node,\n scriptName = scriptName,\n behaviour = self\n }\nend\n\n--- Return the properties of this Behaviour as JSON\n---@private\n---@return string JSON string of properties\nfunction Behaviour:_getPropsJson()\n return JE(self:getProperties())\nend\n\n--- Returns the active state of the behaviour. If the owner item is inactive, so are all attached behaviours\n---@return boolean true, if active, othersise false\nfunction Behaviour:isActive()\n return self._isActive\nend\n\n--- Returns the initialized state of the behaviour. If true, init ran through or there is no init\n---@return boolean true, if initialized, othersise false\nfunction Behaviour:isInitialized()\n return self._isInitialized\nend\n\n--- Clears all registered behaviours (used internally). They are expected to be empty anyway due to scripts\n--- cleaning up behind themselves. This function will assert this\n---@private\nfunction Behaviour._clearBehaviours()\n -- Clear in-place to avoid any stale references to the _behaviours table object\n -- preventing Lua GC from reclaiming behaviour instances.\n for nodeId, nodeBehaviours in pairs(_behavioursMapByNodeId) do\n -- nodeBehaviours is a keyed table (scriptId -> { ... })\n if nodeBehaviours and next(nodeBehaviours) ~= nil then\n -- This warning is useful when scripts forget to dispose their behaviours,\n -- but the check previously used `#nodeBehaviours` which is incorrect for keyed tables.\n print(\"WARNING: Some behaviours did not get cleaned properly. This is an engine bug!\")\n -- Keep clearing anyway to enable GC.\n end\n\n if nodeBehaviours then\n for scriptId in pairs(nodeBehaviours) do\n nodeBehaviours[scriptId] = nil\n end\n end\n\n _behavioursMapByNodeId[nodeId] = nil\n end\n\n -- Also clear the second map that has the behaviours by their script ID directly and the execution order map\n _behavioursMapByScriptId = {}\n _behavioursMapByExecutionOrder = {}\n _executionIndex = 1\nend\n\nfunction Behaviour:_init()\n if type(self.init) == 'function' then\n local ok, err = pcall(self.init, self)\n if not ok then\n print(self._scriptName .. \":init() failed:\", err)\n end\n end\n self._isInitialized = true\n self._isActive = true\nend\n\nfunction Behaviour:_ondisable()\n self._isActive = false\n if type(self.ondisable) == 'function' then\n local ok, err = pcall(self.ondisable, self)\n if not ok then\n print(self._scriptName .. \":ondisable() failed:\", err)\n end\n end\nend\n\nfunction Behaviour:_onenable()\n self._isActive = true\n if type(self.onenable) == 'function' then\n local ok, err = pcall(self.onenable, self)\n if not ok then\n print(self._scriptName .. \":onenable() failed:\", err)\n end\n end\nend\n\nfunction Behaviour:_ondestroy()\n if type(self.ondestroy) == 'function' then\n local ok, err = pcall(self.ondestroy, self)\n if not ok then\n print(self._scriptName .. \":ondestroy() failed:\", err)\n end\n end\n self._isActive = false\n self._isInitialized = false\nend\n\nfunction Behaviour._callHookOnAll(hookName, deltaTime, deltaTimeSmooth)\n local callcount = 0\n\n for _, behaviour in pairs(_behavioursMapByExecutionOrder) do\n local hookFunc = behaviour[hookName]\n if behaviour._isActive and behaviour._isInitialized and type(hookFunc) == 'function' then\n callcount = callcount + 1\n local ok, err = pcall(hookFunc, behaviour, deltaTime, deltaTimeSmooth)\n if not ok then\n print(behaviour._scriptName .. \":\" .. hookName .. \"() failed:\", err)\n end\n end\n end\n\n return callcount\nend\n\nfunction Behaviour._updateAll(deltaTime, deltaTimeSmooth)\n local callcount = 0\n\n callcount = callcount + Behaviour._callHookOnAll(\"preUpdate\", deltaTime, deltaTimeSmooth)\n callcount = callcount + Behaviour._callHookOnAll(\"update\", deltaTime, deltaTimeSmooth)\n callcount = callcount + Behaviour._callHookOnAll(\"lateUpdate\", deltaTime, deltaTimeSmooth)\n\n return callcount\nend\n\nfunction Behaviour._renderAll()\n\n if Canvas.autoClear then\n Canvas.clear()\n end\n\n local callcount = 0\n\n callcount = Behaviour._callHookOnAll(\"prerender\")\n callcount = Behaviour._callHookOnAll(\"render\")\n\n Canvas.commit()\n\n return callcount\nend\n\nfunction Behaviour._renderguiAll()\n return Behaviour._callHookOnAll(\"rendergui\")\nend\n\nfunction Behaviour._setActive(nodes)\n for scriptId, active in pairs(nodes) do\n local behaviour = _behavioursMapByScriptId[scriptId]\n if behaviour then\n behaviour._isActive = active\n else\n print(\"ERROR: Behaviour._setActive() cannot find script: \" .. scriptId)\n end\n end\nend\n\nfunction Behaviour._debugStats()\n local nodeCount = 0\n local behaviourCount = 0\n for _, nodeBehaviours in pairs(_behavioursMapByNodeId) do\n nodeCount = nodeCount + 1\n if nodeBehaviours then\n for _ in pairs(nodeBehaviours) do\n behaviourCount = behaviourCount + 1\n end\n end\n end\n\n return {\n nodeCount = nodeCount,\n behaviourCount = behaviourCount\n }\nend\n\nreturn Behaviour\n";
|
|
99024
|
+
var lua_api_behaviour = "local SceneObject = require('engine/sceneobject')\nlocal Canvas = require('engine/canvas')\nlocal JE = require('engine/json/jsonencoder')()\n\nlocal _behavioursMapByNodeId = {}\nlocal _behavioursMapByScriptId = {}\nlocal _behavioursMapByExecutionOrder = {}\nlocal _executionIndex = 1\n\nlocal Behaviour = Class.new()\n\n-- Put the class in the global scope (Behaviour is the old deprecated name)\n_G.Behaviour = Behaviour\n_G.Entity = Behaviour\n\n--- Constructor hook called when a new Behaviour is created.\n---@private\nfunction Behaviour:__new()\n self._isBehaviour = true\n self._type = \"Behaviour\"\n self._nodeId = nil\n self._scriptName = \"\"\n self._executionIndex = _executionIndex\n self._isActive = true\n self._isInitialized = false\n\n _executionIndex = _executionIndex + 1\n\n -- Adds a default node property\n self:addProperty(\"node\", Property.Node)\nend\n\n--- Destructor hook called before the Behaviour is destroyed.\n---@private\nfunction Behaviour:__destroy()\n print(\"__destroy called for: \", self._nodeId)\nend\n\n--- Get all behaviours attached to a specific node ID.\n---@param nodeId string The ID of the scene graph node\n---@return table A table containing all behaviours attached to the node\nfunction Behaviour.getByNodeId(nodeId)\n local result = {}\n local nodeBehaviours = _behavioursMapByNodeId[nodeId]\n if nodeBehaviours then\n for k,v in pairs(nodeBehaviours) do\n table.insert(result, v.behaviour)\n end\n end\n return result\nend\n\n--- Get a single behaviour attached to a node ID with a specific script name.\n---@param nodeId string The ID of the scene graph node\n---@param scriptName string The script name of the behaviour\n---@return Behaviour|nil The behaviour if found, or nil\nfunction Behaviour.getByNodeIdAndScriptName(nodeId, scriptName)\n local nodeEntities = _behavioursMapByNodeId[nodeId]\n if nodeEntities then\n for k,v in pairs(nodeEntities) do\n if v.scriptName == scriptName then\n return v.behaviour\n end\n end\n end\n return nil\nend\n\n--- Returns the node ID this Behaviour is attached to.\n---@return string|nil Node ID of the attached scene object\nfunction Behaviour:getNodeId()\n return self._nodeId\nend\n\n--- Returns the script name of this Behaviour.\n---@return string Script name\nfunction Behaviour:getScriptName()\n return self._scriptName\nend\n\n--- Returns a table of all properties defined on the behaviour class.\n---@return table A table with fields: name, defaultValue, type, order\nfunction Behaviour:getProperties()\n local propsByName = {}\n local class = self.getClass()\n\n local function addPropertyEntry(name, prop)\n propsByName[name] = {\n name = name,\n defaultValue = prop.value,\n type = prop.datatype,\n order = prop.order,\n info = prop.info,\n minValue = prop.minValue,\n maxValue = prop.maxValue,\n conditions = prop.conditions,\n collapsed = prop.collapsed,\n allowedTypes = prop.allowedTypes,\n }\n end\n\n local SKIP_CLASS_KEYS = {\n metatable = true,\n properties = true,\n super = true,\n new = true,\n getClass = true,\n addProperty = true,\n }\n\n local function collectFromClass(cls)\n if not cls then\n return\n end\n\n collectFromClass(cls.super)\n\n for k, v in pairs(cls.properties) do\n if type(v) == 'table' and v._isProperty then\n addPropertyEntry(k, v)\n end\n end\n\n -- Legacy API: properties assigned directly on the class, e.g. TestEntity.testNode = Property.new(...)\n for k, v in pairs(cls) do\n if type(k) == 'string' and not SKIP_CLASS_KEYS[k] and type(v) == 'table' and v._isProperty and not propsByName[k] then\n addPropertyEntry(k, v)\n end\n end\n end\n\n collectFromClass(class)\n\n local props = {}\n for _, v in pairs(propsByName) do\n table.insert(props, v)\n end\n\n return props\nend\n\n--- When a script is destroyed, we need to call this to clear the behaviour out of the list\n---@private\nfunction Behaviour:_disposeBehaviour()\n local scripts = _behavioursMapByNodeId[self._nodeId]\n if scripts then\n scripts[self._scriptId] = nil\n end\n\n _behavioursMapByScriptId[self._scriptId] = nil\n _behavioursMapByExecutionOrder[self._executionIndex] = nil\nend\n\n--- Internal setter for a property\n---@private\n---@param name string Property name\n---@param value any Value to set\nfunction Behaviour:_setProperty(name, value)\n self[name] = value\nend\n\n--- Internal method to attach a scene node to this Behaviour\n---@private\n---@param msg table Contains fields: value=nodeId, scriptName, scriptId\nfunction Behaviour:_setNode(msg)\n __assertTrace(type(msg) == 'table', \"_setNode() called with nil or a non-table.\")\n\n if self.node then\n error(\"Node is already set on behaviour!\")\n end\n\n local nodeId = msg.value\n __assertTrace(type(nodeId) == 'string', \"_setNode() needs a nodeId of type string.\")\n\n local node = SceneObject.findById(nodeId)\n __assertTrace(node, \"_setNode() node not found\")\n\n local scriptName = msg.scriptName\n __assertTrace(scriptName, \"_setNode() needs a scriptName\")\n\n local scriptId = msg.scriptId\n __assertTrace(scriptId, \"_setNode() needs a scriptId\")\n\n self.node = node\n self._nodeId = nodeId\n self._scriptName = msg.scriptName\n self._scriptId = scriptId\n\n _behavioursMapByScriptId[scriptId] = self\n _behavioursMapByExecutionOrder[self._executionIndex] = self\n\n if not _behavioursMapByNodeId[nodeId] then\n _behavioursMapByNodeId[nodeId] = {}\n end\n _behavioursMapByNodeId[nodeId][scriptId] = {\n node = node,\n scriptName = scriptName,\n behaviour = self\n }\nend\n\n--- Return the properties of this Behaviour as JSON\n---@private\n---@return string JSON string of properties\nfunction Behaviour:_getPropsJson()\n return JE(self:getProperties())\nend\n\n--- Returns the active state of the behaviour. If the owner item is inactive, so are all attached behaviours\n---@return boolean true, if active, othersise false\nfunction Behaviour:isActive()\n return self._isActive\nend\n\n--- Returns the initialized state of the behaviour. If true, init ran through or there is no init\n---@return boolean true, if initialized, othersise false\nfunction Behaviour:isInitialized()\n return self._isInitialized\nend\n\n--- Clears all registered behaviours (used internally). They are expected to be empty anyway due to scripts\n--- cleaning up behind themselves. This function will assert this\n---@private\nfunction Behaviour._clearBehaviours()\n -- Clear in-place to avoid any stale references to the _behaviours table object\n -- preventing Lua GC from reclaiming behaviour instances.\n for nodeId, nodeBehaviours in pairs(_behavioursMapByNodeId) do\n -- nodeBehaviours is a keyed table (scriptId -> { ... })\n if nodeBehaviours and next(nodeBehaviours) ~= nil then\n -- This warning is useful when scripts forget to dispose their behaviours,\n -- but the check previously used `#nodeBehaviours` which is incorrect for keyed tables.\n print(\"WARNING: Some behaviours did not get cleaned properly. This is an engine bug!\")\n -- Keep clearing anyway to enable GC.\n end\n\n if nodeBehaviours then\n for scriptId in pairs(nodeBehaviours) do\n nodeBehaviours[scriptId] = nil\n end\n end\n\n _behavioursMapByNodeId[nodeId] = nil\n end\n\n -- Also clear the second map that has the behaviours by their script ID directly and the execution order map\n _behavioursMapByScriptId = {}\n _behavioursMapByExecutionOrder = {}\n _executionIndex = 1\nend\n\nfunction Behaviour:_init()\n if type(self.init) == 'function' then\n local ok, err = pcall(self.init, self)\n if not ok then\n print(self._scriptName .. \":init() failed:\", err)\n end\n end\n self._isInitialized = true\n self._isActive = true\nend\n\nfunction Behaviour:_ondisable()\n self._isActive = false\n if type(self.ondisable) == 'function' then\n local ok, err = pcall(self.ondisable, self)\n if not ok then\n print(self._scriptName .. \":ondisable() failed:\", err)\n end\n end\nend\n\nfunction Behaviour:_onenable()\n self._isActive = true\n if type(self.onenable) == 'function' then\n local ok, err = pcall(self.onenable, self)\n if not ok then\n print(self._scriptName .. \":onenable() failed:\", err)\n end\n end\nend\n\nfunction Behaviour:_ondestroy()\n if type(self.ondestroy) == 'function' then\n local ok, err = pcall(self.ondestroy, self)\n if not ok then\n print(self._scriptName .. \":ondestroy() failed:\", err)\n end\n end\n self._isActive = false\n self._isInitialized = false\nend\n\nfunction Behaviour._callHookOnAll(hookName, deltaTime, deltaTimeSmooth)\n local callcount = 0\n\n for _, behaviour in pairs(_behavioursMapByExecutionOrder) do\n local hookFunc = behaviour[hookName]\n if behaviour._isActive and behaviour._isInitialized and type(hookFunc) == 'function' then\n callcount = callcount + 1\n local ok, err = pcall(hookFunc, behaviour, deltaTime, deltaTimeSmooth)\n if not ok then\n print(behaviour._scriptName .. \":\" .. hookName .. \"() failed:\", err)\n end\n end\n end\n\n return callcount\nend\n\nfunction Behaviour._updateAll(deltaTime, deltaTimeSmooth)\n local callcount = 0\n\n callcount = callcount + Behaviour._callHookOnAll(\"preUpdate\", deltaTime, deltaTimeSmooth)\n callcount = callcount + Behaviour._callHookOnAll(\"update\", deltaTime, deltaTimeSmooth)\n callcount = callcount + Behaviour._callHookOnAll(\"lateUpdate\", deltaTime, deltaTimeSmooth)\n\n return callcount\nend\n\nfunction Behaviour._renderAll()\n\n if Canvas.autoClear then\n Canvas.clear()\n end\n\n local callcount = 0\n\n callcount = Behaviour._callHookOnAll(\"prerender\")\n callcount = Behaviour._callHookOnAll(\"render\")\n\n Canvas.commit()\n\n return callcount\nend\n\nfunction Behaviour._renderguiAll()\n return Behaviour._callHookOnAll(\"rendergui\")\nend\n\nfunction Behaviour._setActive(nodes)\n for scriptId, active in pairs(nodes) do\n local behaviour = _behavioursMapByScriptId[scriptId]\n if behaviour then\n behaviour._isActive = active\n else\n print(\"ERROR: Behaviour._setActive() cannot find script: \" .. scriptId)\n end\n end\nend\n\nfunction Behaviour._debugStats()\n local nodeCount = 0\n local behaviourCount = 0\n for _, nodeBehaviours in pairs(_behavioursMapByNodeId) do\n nodeCount = nodeCount + 1\n if nodeBehaviours then\n for _ in pairs(nodeBehaviours) do\n behaviourCount = behaviourCount + 1\n end\n end\n end\n\n return {\n nodeCount = nodeCount,\n behaviourCount = behaviourCount\n }\nend\n\nreturn Behaviour\n";
|
|
98989
99025
|
|
|
98990
99026
|
var lua_api_canvas = "\nlocal _internal = require('engine/_internal');\n\n---@module canvas\nlocal canvas = {\n autoClear = false\n}\n\n-- Lua-side command buffer for canvas calls.\nlocal _cmds = {}\n\nlocal function _captureSendMessage(target, payload, buffers)\n table.insert(_cmds, {\n target = target,\n payload = payload,\n buffers = buffers\n })\n return nil\nend\n\nlocal function _runWithCapturedSend(fn, ...)\n local oldSendMessage = _internal.sendMessage\n _internal.sendMessage = _captureSendMessage\n\n local result = { pcall(fn, ...) }\n\n _internal.sendMessage = oldSendMessage\n\n if not result[1] then\n error(result[2])\n end\n\n return table.unpack(result, 2)\nend\n\nlocal function _commitIfNeeded()\n if #_cmds == 0 then\n return { committed = 0 }\n end\n\n local result = _internal.sendMessage('canvas.commit', { cmds = _cmds })\n _cmds = {}\n return result\nend\n\n---If set to true, the canvas will automatically clear once before the render hook is called\n---@param value boolean the flag value\nfunction canvas.setAutoClear(value)\n self.autoClear = value\nend\n\n---Returns the value of the auto clear flag\n---@return boolean the flag value\nfunction canvas.getAutoClear()\n return self.autoClear\nend\n\n---Commit all pending buffered canvas commands.\n---@return table|nil result Optional engine-side debug info.\nfunction canvas.commit()\n return _commitIfNeeded()\nend\n\n---Debug helper: returns count of pending buffered commands in Lua.\n---@return number\nfunction canvas.getPendingCommandCount()\n return #_cmds\nend\n\n---Debug helper: returns current pending buffered commands in Lua.\n---@return table\nfunction canvas.getPendingCommands()\n return _cmds\nend\n\n---Debug helper: returns most recently committed command list on engine side.\n---@return table\nfunction canvas.getLastCommittedCommands()\n _commitIfNeeded()\n return _internal.sendMessage('canvas.getLastCommittedCommands')\nend\n\n---Clear the canvas.\n---@function\nfunction canvas.clear()\n _internal.sendMessage('canvas.clear')\nend\n\n---Returns the width of the canvas in pixels.\n---@function\nfunction canvas.getWidth()\n return _internal.sendMessage('canvas.getWidth')\nend\n\n---Returns the height of the canvas in pixels.\n---@function\nfunction canvas.getHeight()\n return _internal.sendMessage('canvas.getHeight')\nend\n\n---Sets the width of lines in the canvas.\n---@param w number the width to set the lines to.\nfunction canvas.setLineWidth(w)\n _internal.sendMessage('canvas.setLineWidth', { w=w })\nend\n\n---Sets the type of endings applied to the ends of a line.\n---@param cap string the type of corner to create on a line. One of \"butt\", \"round\", \"square\".\nfunction canvas.setLineCap(cap)\n _internal.sendMessage('canvas.setLineCap', { cap=cap })\nend\n\n---Sets the type of corner created when two lines meet.\n---@param join string the type of connection to create between two lines. One of \"bevel\", \"round\", or \"miter\".\nfunction canvas.setLineJoin(join)\n _internal.sendMessage('canvas.setLineJoin', { join=join })\nend\n\n---Sets the maximum miter length. Miter length is the distance between the inner corner and the outer corner of the join.\n---@param limit number the maximum miter length. When the miter length exceeds this value, the corner is trimmed.\nfunction canvas.setMiterLimit(limit)\n _internal.sendMessage('canvas.setMiterLimit', { limit=limit })\nend\n\n---Sets the color of the stroke (outline) for shapes drawn on the canvas.\n---@param r number Red channel value (0–255)\n---@param g number Green channel value (0–255)\n---@param b number Blue channel value (0–255)\n---@param a number Alpha channel value (0–1)\nfunction canvas.setStrokeColor(r, g, b, a)\n _internal.sendMessage('canvas.setStrokeColor', { r=r, g=g, b=b, a=a })\nend\n\n---Sets the color that is used to fill in shapes and text when they are drawn on the canvas.\n---@param r number Red channel value (0–255)\n---@param g number Green channel value (0–255)\n---@param b number Blue channel value (0–255)\n---@param a number Alpha channel value (0–1)\nfunction canvas.setFillColor(r, g, b, a)\n _internal.sendMessage('canvas.setFillColor', { r=r, g=g, b=b, a=a })\nend\n\n---Sets the color to use for shadows.\n---@param r number Red channel value (0–255)\n---@param g number Green channel value (0–255)\n---@param b number Blue channel value (0–255)\n---@param a number Alpha channel value (0–1)\nfunction canvas.setShadowColor(r, g, b, a)\n _internal.sendMessage('canvas.setShadowColor', { r=r, g=g, b=b, a=a })\nend\n\n---Sets the blur level for shadows.\n---@param level number the level of blur to be applied to shadows (in pixels).\nfunction canvas.setShadowBlurLevel(level)\n _internal.sendMessage('canvas.setShadowBlurLevel', { level=level })\nend\n\n---Sets the blur level for shadows.\n---@param x number the vertical offset of the shadow in pixels.\n---@param y number the horizontal offset of the shadow in pixels.\nfunction canvas.setShadowOffset(x, y)\n _internal.sendMessage('canvas.setShadowOffset', { x=x, y=y })\nend\n\n---Begins a new path.\n---@function\nfunction canvas.beginPath()\n _internal.sendMessage('canvas.beginPath')\nend\n\n---Close the current path by connecting the last and first point in the path, creating a loop.\n---@function\nfunction canvas.closePath()\n _internal.sendMessage('canvas.closePath')\nend\n\n---Determines if the specified point is in the current path.\n---@param x number x-coordinate of the point to check.\n---@param y number y-coordinate of the point to check.\n---@return boolean indicating if the point is in the path or not.\nfunction canvas.isPointInPath(x, y)\n return _internal.sendMessage('canvas.isPointInPath', { x=x, y=y })\nend\n\n---Sets the clipping path to the current drawing path.\n---@function\nfunction canvas.clip()\n _internal.sendMessage('canvas.clip')\nend\n\n---Draws the outline of a shape or path using the current stroke style, line width and styles.\n---@function\nfunction canvas.stroke()\n _internal.sendMessage('canvas.stroke')\nend\n\n---Fills a shape or path with the current fill style.\n---@function\nfunction canvas.fill()\n _internal.sendMessage('canvas.fill')\nend\n\n---Moves the current drawing position to the specified coordinates.\n---@param x number x-coordinate of the new current drawing position.\n---@param y number y-coordinate of the new current drawing position.\nfunction canvas.moveTo(x, y)\n _internal.sendMessage('canvas.moveTo', { x=x, y=y })\nend\n\n---Draws a straight line from the current position to the specified coordinates.\n---@param x number the x-coordinate to draw the line to.\n---@param y number the y-coordinate to draw the line to.\nfunction canvas.lineTo(x, y)\n _internal.sendMessage('canvas.lineTo', { x=x, y=y })\nend\n\n---Sets the type of compositing operation to apply when drawing new shapes.\n---@param operation string the compositing operation to use, possible values are:\n---\"source-over\", \"source-in\", \"source-out\", \"source-atop\", \"destination-over\",\n---\"destination-in\", \"destination-out\", \"destination-atop\", \"lighter\", \"copy\", \"xor\".\nfunction canvas.setCompositeOperation(operation)\n _internal.sendMessage('canvas.setCompositeOperation', { operation=operation })\nend\n\n---Sets the transparency value that is applied to all rendering operations.\n---@param value number a value between 0.0 (fully transparent) and 1.0 (fully opaque).\nfunction canvas.setGlobalAlpha(value)\n _internal.sendMessage('canvas.setGlobalAlpha', { value=value })\nend\n\n---Creates a rectangle path which is only drawn after calling stroke() or fill().\n---@param x number x-coordinate of the rectangle upper-left corner.\n---@param y number y-coordinate of the rectangle upper-left corner.\n---@param w number width of the rectangle.\n---@param h number height of the rectangle.\nfunction canvas.pathRect(x, y, w, h)\n _internal.sendMessage('canvas.pathRect', { x=x, y=y, w=w, h=h })\nend\n\n---Adds a rounded rectangle to the current path. Must be followed by stroke() or fill().\n---@param x number x-coordinate of the rectangle upper-left corner.\n---@param y number y-coordinate of the rectangle upper-left corner.\n---@param w number width of the rectangle.\n---@param h number height of the rectangle.\n---@param radius number|table corner radius applied to all four corners (uniform), or a table\n---of 1–4 values to set individual corner radius in the order [top-left, top-right,\n---bottom-right, bottom-left], following the HTML Canvas API specification.\nfunction canvas.roundRect(x, y, w, h, radius)\n _internal.sendMessage('canvas.roundRect', { x=x, y=y, w=w, h=h, radius=radius })\nend\n\n---Draw a rectangle outline using the current stroke style.\n---@param x number x-coordinate of the rectangle upper-left corner.\n---@param y number y-coordinate of the rectangle upper-left corner.\n---@param w number width of the rectangle.\n---@param h number height of the rectangle.\nfunction canvas.strokeRect(x, y, w, h)\n _internal.sendMessage('canvas.strokeRect', { x=x, y=y, w=w, h=h })\nend\n\n---Draw a rectangle with a filled interior using the current fill style,\n---@param x number x-coordinate of the rectangle upper-left corner.\n---@param y number y-coordinate of the rectangle upper-left corner.\n---@param w number width of the rectangle.\n---@param h number height of the rectangle.\nfunction canvas.fillRect(x, y, w, h)\n _internal.sendMessage('canvas.fillRect', { x=x, y=y, w=w, h=h })\nend\n\n---Clears the specified rectangle by setting its pixels to transparent.\n---@param x number x-coordinate of the rectangle upper-left corner.\n---@param y number y-coordinate of the rectangle upper-left corner.\n---@param w number width of the rectangle.\n---@param h number height of the rectangle.\nfunction canvas.clearRect(x, y, w, h)\n _internal.sendMessage('canvas.clearRect', { x=x, y=y, w=w, h=h })\nend\n\n---Draws a circle with given parameters. Must be followed by stroke() or fill().\n---@param x number x-coordinates of the center of the circle.\n---@param y number y-coordinates of the center of the circle.\n---@param r number the radius of the circle\nfunction canvas.circle(x, y, r)\n _internal.sendMessage('canvas.circle', { x=x, y=y, r=r })\nend\n\n---Draws an arc with given parameters. Must be followed by stroke() or fill().\n---@param x number x-coordinates of the center of the circle.\n---@param y number y-coordinates of the center of the circle.\n---@param r number the radius of the circle.\n---@param startAngle number the starting angle in radians.\n---@param endAngle number the ending angle, in radians.\n---@param anticlockwise boolean a flag which specifies whether the drawing should be counterclockwise or clockwise.\nfunction canvas.arc(x, y, r, startAngle, endAngle, anticlockwise)\n _internal.sendMessage('canvas.arc', { x=x, y=y, r=r, startAngle=startAngle,\n endAngle=endAngle, anticlockwise=anticlockwise })\nend\n\n---Adds a quadratic Bézier curve to the path with given control point and end point.\n---@param cpx number x-coordinate of the control point.\n---@param cpy number y-coordinate of the control point.\n---@param x number x-coordinate of the end point.\n---@param y number y-coordinate of the end point.\nfunction canvas.quadraticCurve(cpx, cpy, x, y)\n _internal.sendMessage('canvas.quadraticCurve', { cpx=cpx, cpy=cpy, x=x, y=y })\nend\n\n---Draws a bezier curve from the current position to the specified point, using the specified control points.\n---@param cp1x number x-coordinate of the first control point.\n---@param cp1y number y-coordinate of the first control point.\n---@param cp2x number x-coordinate of the second control point.\n---@param cp2y number y-coordinate of the second control point.\n---@param x number x-coordinate of the end point.\n---@param y number y-coordinate of the end point.\nfunction canvas.bezierCurve(cp1x, cp1y, cp2x, cp2y, x, y)\n _internal.sendMessage('canvas.bezierCurve', { cp1x=cp1x, cp1y=cp1y,\n cp2x=cp2x, cp2y=cp2y,\n x=x, y=y })\nend\n\n---@class Gradient\n---A class to internally link gradient objects from the Lua environment to Lumino codebase.\n---A Gradient object can be create using @{createLinearGradient} or @{createRadialGradient}\n---@private\nlocal Gradient = {}\n\n---Creates a new gradient object with the given index\n---@param idx number index of the gradient object\n---@private\nfunction Gradient:new(idx)\n -- Store the gradient object in a field of the class instance metatable\n local obj = { idx = idx}\n Class.__setmetatable(obj, self)\n self.__index = self\n -- Return the instance\n return obj\nend\n\n---Hook that runs before an object is deleted by the garbage collector.\n---It calls a function to delete the gradient object in JS\n---@private\nfunction Gradient:__gc()\n -- Keep deletion ordering deterministic when gradient operations are buffered.\n _commitIfNeeded()\n _internal.sendMessage('canvas.deleteGradient', { gradientIdx = self.idx })\nend\n-- Add the Gradient class to the Canvas namespace\ncanvas.Gradient = Gradient\n\n---Sets a gradient object to active.\n---@param gradient Gradient a gradient object\nfunction canvas.setGradientActive(gradient)\n if gradient.idx >= 0 then\n _internal.sendMessage('canvas.setGradientActive', { gradientIdx = gradient.idx })\n end\nend\n\n---Adds a new stop, defined by an offset and a color, to a gradient object.\n---@param gradient Gradient a gradient object\n---@param offset number a value between 0.0 and 1.0 where the new color stop is positioned.\n---@param r number Red channel value (0–255)\n---@param g number Green channel value (0–255)\n---@param b number Blue channel value (0–255)\n---@param a number Alpha channel value (0–1)\nfunction canvas.colorStop(gradient, offset, r, g, b, a)\n _internal.sendMessage('canvas.colorStop', { gradientIdx=gradient.idx, offset=offset, r=r, g=g, b=b, a=a })\nend\n\n---Creates a linear gradient object.\n---@param x1 number the x-coordinate of the start point of the gradient\n---@param y1 number the y-coordinate of the start point of the gradient\n---@param x2 number the x-coordinate of the end point of the gradient\n---@param y2 number the y-coordinate of the end point of the gradient\n---@return Gradient a new gradient object\n---@usage local gradient = Canvas.createLinearGradient(0, 0, 50, 0)\nfunction canvas.createLinearGradient(x1, y1, x2, y2)\n local idx = _internal.sendMessage('canvas.createLinearGradient', { x1=x1, y1=y1,\n x2=x2, y2=y2 })\n local gradient = Gradient:new(idx)\n return gradient\nend\n\n---Creates a radial gradient object.\n---@param x1 number x-coordinate of the start circle\n---@param y1 number y-coordinate of the start circle\n---@param r1 number radius of the start circle\n---@param x2 number x-coordinate of the end circle\n---@param y2 number y-coordinate of the end circle\n---@param r2 number radius of the end circle\n---@return Gradient a new gradient object\nfunction canvas.createRadialGradient(x1, y1, r1, x2, y2, r2)\n local idx = _internal.sendMessage('canvas.createRadialGradient', { x1=x1, y1=y1, r1=r1,\n x2=x2, y2=y2, r2=r2})\n local gradient = Gradient:new(idx)\n return gradient\nend\n\n---Returns an array with strings of all available fonts. This will list all custom loaded fonts through Loader.loadFont and\n---fonts registered in Canvas Fonts in your project. It will also probe for common system fonts although the list might not be complete.\n---It is strongly recommended to use only custom uploaded fonts to have reliable results on all platforms.\n---@return table an array with all the available fonts as strings\nfunction canvas.getAvailableFonts()\n return _internal.sendMessage('canvas.getAvailableFonts')\nend\n\n---Sets a font style.\n---@param font string The font style to be set, in the format of 'font-style font-size font-family'. Example: 'italic 20px Arial'.\nfunction canvas.setFont(font)\n _internal.sendMessage('canvas.setFont', { font=font })\nend\n\n---Sets the current text alignment\n---@param align string The new text alignment to be set. One of 'start', 'end', 'left', 'right', or 'center'.\nfunction canvas.setTextAlign(align)\n _internal.sendMessage('canvas.setTextAlign', { align=align })\nend\n\n---Sets the text baseline used when drawing text.\n---@param baseline string The text baseline to set. One of 'alphabetic', 'top', 'hanging', 'middle', 'ideographic', or 'bottom'.\nfunction canvas.setTextBaseline(baseline)\n _internal.sendMessage('canvas.setTextBaseline', { baseline=baseline })\nend\n\n---Measures the width of the specified text in pixels.\n---@param text string The text to measure.\nfunction canvas.measureTextWidth(text)\n return _internal.sendMessage('canvas.measureTextWidth', { text=text })\nend\n\n---Draws and fills a given text string at the specified coordinates.\n---@param text string The text string to be drawn and filled.\n---@param x number The x-coordinate where the text will be drawn.\n---@param y number The y-coordinate where the text will be drawn.\nfunction canvas.fillText(text, x, y)\n _internal.sendMessage('canvas.fillText', { text=text, x=x, y=y })\nend\n\n---Draws the outline of the given text at the specified coordinates.\n---@param text string The text string to be drawn.\n---@param x number The x-coordinate where the text will be drawn.\n---@param y number The y-coordinate where the text will be drawn.\nfunction canvas.strokeText(text, x, y)\n _internal.sendMessage('canvas.strokeText', { text=text, x=x, y=y })\nend\n\n-- -TODO: ImageData is not yet ready for deployment because using it for pixel manipulation would be\n-- -inefficient and slow due to the need for JSON communication with JavaScript. While JSON\n-- -communication is necessary for the security of the application, it is not well-suited for tasks\n-- -that require frequent or high-volume data transfer. It is better to use ImageData for low\n-- -frequency tasks such as updating UI and handling events, rather than trying to use it for more\n-- -demanding tasks that may be slowed down by the use of JSON objects.\n\n-- --- Image class to link imageData objects in the canvas to Lua\n-- ---@class imageData\n-- local Image = {}\n\n-- --- Creates a new Image object with the given index\n-- ---@param idx number index of the imageData object in the canvas\n-- function Image:new(idx)\n-- local obj = {}\n-- Class.__setmetatable(obj, self)\n-- self.__index = self\n-- self.idx = idx\n-- return obj\n-- end\n-- canvas.Image = Image\n\n-- ---Creates a new, blank Image object with the specified dimensions.\n-- ---All of the pixels in the new object are transparent black.\n-- ---@param width number the width of the Image object\n-- ---@param height number the height of the Image object\n-- ---@return Image a new Image object\n-- function canvas.createImage(width, height)\n-- local idx = _internal.sendMessage('canvas.createImage', { width=width, height=height })\n-- local image = Image:new(idx)\n-- return image\n-- end\n\n-- ---Write the RGBA channels of an Image object\n-- ---@param r number the r channel of the Image object\n-- ---@param g number the g channel of the Image object\n-- ---@param b number the b channel of the Image object\n-- ---@param a number the a channel of the Image object\n-- function canvas.writeImageChannels(image, r, g, b, a)\n-- _internal.sendMessage('canvas.writeImageChannels', { imageIdx=image.idx, r=r, g=g, b=b, a=a })\n-- end\n\n-- ---Draws an image given by an url at the specified position and dimensions.\n-- ---@param url string\n-- ---@param x number\n-- ---@param y number\n-- ---@param width number\n-- ---@param height number\n-- function canvas.drawImageFromUrl(url, x, y, width, height)\n-- _internal.sendMessage('canvas.drawImageFromUrl', { url=url, x=x, y=y, width=width, height=height })\n-- end\n\n-- ---Repeats a given image on the canvas with a given pattern.\n-- ---@param image imageSource an image object\n-- ---@param repeat string one of repeat, repeat-x, repeat-y, no-repeat\n-- function canvas.imagePattern(image, repeatPattern)\n-- _internal.sendMessage('canvas.pattern', { image=image, repeatPattern=repeatPattern })\n-- end\n\n---Draws the image data at the given coordinates.\n---@param image Texture the image data to paint\n---@param x number x-coordinate of the top left corner where the image data will be painted\n---@param y number y-coordinate of the top left corner where the image data will be painted\n---@param width number width of the image on screen (optional)\n---@param height number height of the image on screen (optional)\n---@param mode number mode to use for stretching. possible values are 0 = stretch, 1 = fit, 2 = cover\nfunction canvas.drawImage(image, x, y, width, height, mode)\n __assertTrace(image and image._isTexture, \"image is not a Texture object\")\n _internal.sendMessage('canvas.drawImage', { image= image._handle, x=x, y=y, width=width, height=height, mode=mode })\nend\n\n---Draws the image data at the given coordinates.\n---@param image Texture the image data to paint\n---@param x number x-coordinate of the top left corner where the image data will be painted\n---@param y number y-coordinate of the top left corner where the image data will be painted\n---@param width number width of the image on screen (optional)\n---@param height number height of the image on screen (optional)\nfunction canvas.drawSubImage(image, x, y, width, height, sourceX, sourceY, sourceWidth, sourceHeight)\n __assertTrace(image and image._isTexture, \"image is not a Texture object\")\n _internal.sendMessage('canvas.drawSubImage', { image= image._handle,\n x=x, y=y, width=width, height=height,\n sourceX=sourceX, sourceY=sourceY, sourceWidth=sourceWidth, sourceHeight=sourceHeight })\nend\n\n--- Scales the canvas by the specified factors along the x and y axes.\n--- Transformations are applied relative to the canvas origin (0,0).\n--- To scale around a different point, use `translate()` to move the origin before scaling.\n---@param x number Scale factor along the x-axis.\n---@param y number Scale factor along the y-axis.\nfunction canvas.scale(x, y)\n _internal.sendMessage('canvas.scale', { x=x, y=y })\nend\n\n--- Rotates the canvas by the specified angle in radians.\n--- Rotation is performed around the canvas origin (0,0).\n--- To rotate around a different point, translate the canvas to that point before calling rotate().\n---@param a number Angle in radians.\nfunction canvas.rotate(a)\n _internal.sendMessage('canvas.rotate', { a=a })\nend\n\n\n--- Moves (translates) the canvas origin by the specified amounts.\n--- All subsequent drawing and transformations (scale, rotate, etc.) are relative to the new origin.\n---@param x number Amount to translate along the x-axis.\n---@param y number Amount to translate along the y-axis.\nfunction canvas.translate(x, y)\n _internal.sendMessage('canvas.translate', { x=x, y=y })\nend\n\n---Applies a 2D transformation matrix to the canvas.\n---@param horizontal_scale number The amount to scale horizontally.\n---@param horizontal_skew number The amount of horizontal skew.\n---@param vertical_skew number The amount of vertical skew.\n---@param vertical_scale number The amount to scale vertically.\n---@param horizontal_translation number The amount of horizontal translation.\n---@param vertical_translation number The amount of vertical translation.\nfunction canvas.transform(horizontal_scale, horizontal_skew, vertical_skew,\n vertical_scale, horizontal_translation, vertical_translation)\n _internal.sendMessage('canvas.transform', { a=horizontal_scale, b=horizontal_skew,\n c=vertical_skew, d=vertical_scale,\n e=horizontal_translation, f=vertical_translation })\nend\n\n---Resets the current canvas transform to the identity matrix and then invokes the transform() function with the given parameters.\n---@param horizontal_scale number The amount to scale horizontally.\n---@param horizontal_skew number The amount of horizontal skew.\n---@param vertical_skew number The amount of vertical skew.\n---@param vertical_scale number The amount to scale vertically.\n---@param horizontal_translation number The amount of horizontal translation.\n---@param vertical_translation number The amount of vertical translation.\nfunction canvas.resetAndSetTransform(horizontal_scale, horizontal_skew, vertical_skew,\n vertical_scale, horizontal_translation, vertical_translation)\n _internal.sendMessage('canvas.resetAndSetTransform', { a=horizontal_scale, b=horizontal_skew,\n c=vertical_skew, d=vertical_scale,\n e=horizontal_translation, f=vertical_translation })\nend\n\n---Reset the transformation matrix to the identity matrix.\n---@function\nfunction canvas.resetTransform()\n _internal.sendMessage('canvas.resetTransform')\nend\n\n---Pushes the current canvas state to a stack so that you can restore it.\n---This can be useful for performing multiple transformations or styles on the canvas, and\n---then restoring it to its original state. The canvas state in fact includes current transformation matrix\n---stroke and fill styles, shadow styles, and other attributes. To restore the canvas state you call\n---the restoreState() function.\n---@function\nfunction canvas.saveState()\n _internal.sendMessage('canvas.saveState')\nend\n\n---Pops the the most recently saved canvas from the saved state stack and restores it.\n---@function\nfunction canvas.restoreState()\n _internal.sendMessage('canvas.restoreState')\nend\n\n--- Resets the canvas to its default state, clearing the canvas and restoring all\n--- context -properties (transforms, styles, clipping region, etc.) to their\n--- defaults. Reset() is more thorough than -calling clear() alone, which only\n--- erases pixels but leaves context state intact.\n---@function\nfunction canvas.reset()\n _internal.sendMessage('canvas.reset')\nend\n\n-- Automatically wrap canvas methods for buffering, so non-query calls are queued\n-- and query/result-producing calls force an immediate commit first.\nlocal _passthroughMethods = {\n commit = true,\n getPendingCommandCount = true,\n getPendingCommands = true,\n}\n\nlocal _immediateMethods = {\n getLastCommittedCommands = true,\n getWidth = true,\n getHeight = true,\n isPointInPath = true,\n createLinearGradient = true,\n createRadialGradient = true,\n getAvailableFonts = true,\n measureTextWidth = true,\n}\n\nfor name, fn in pairs(canvas) do\n if type(fn) == \"function\" and name ~= \"Gradient\" then\n if _passthroughMethods[name] then\n -- keep as-is\n elseif _immediateMethods[name] then\n canvas[name] = function(...)\n _commitIfNeeded()\n return fn(...)\n end\n else\n canvas[name] = function(...)\n return _runWithCapturedSend(fn, ...)\n end\n end\n end\nend\n\nreturn canvas\n";
|
|
98991
99027
|
|
|
98992
|
-
var lua_api_class = "\nlocal Class = {}\n\nClass.__setmetatable = setmetatable\n_G.setmetatable = function()\n error(\"Do not use setmetatable. Use Class.new() instead!\")\nend\n\n-- Put the class in the global scope\n_G.Class = Class\n\nfunction Class.new(self, super)\n if self ~= Class then\n -- new was called with dot syntax, so we need to move self to super.\n super = self\n end\n\n local class, metatable, properties = {}, {}, {}\n class.metatable = metatable\n class.properties = properties\n\n function metatable:__index(key)\n local prop = properties[key]\n if prop then\n return prop:get()\n elseif class[key] ~= nil then\n return class[key]\n elseif class.__customIndex then\n return class.__customIndex(self, key)\n elseif super then\n return super.metatable.__index(self, key)\n else\n return nil\n end\n end\n\n function metatable:__newindex(key, value)\n local prop = properties[key]\n if prop then\n prop:set(value)\n elseif class.__customNewIndex then\n class.__customNewIndex(self, key, value)\n else\n if (super and super.metatable.__customnewindex(self, key, value)) then\n return\n end\n rawset(self, key, value)\n end\n end\n\n function metatable:__customnewindex(key, value)\n if class.__customNewIndex then\n class.__customNewIndex(self, key, value)\n return true\n elseif super then\n return super.metatable.__customnewindex(self, key, value)\n end\n return false\n end\n\n function class:getClass()\n return class\n end\n\n function class.new(self, ...)\n local obj = Class.__setmetatable({}, class.metatable)\n\n if obj.__new then\n if self ~= class then\n -- new was called with dot syntax\n obj:__new(self, ...)\n else\n obj:__new(...)\n end\n end\n\n return obj\n end\n\n function tableLength(T)\n local count = 0\n for _ in pairs(T) do\n count = count + 1\n end\n return count\n end\n\n function class:addProperty(key, propType, defaultValue, options)\n options = options or {}\n if type(options) == 'string' then\n options = { info=options }\n end\n\n if class.properties[key] then\n error(\"A property with the name '\" .. key .. \"' already exists!\");\n return;\n end\n class.properties[key] = Property.new(propType, defaultValue, tableLength(class.properties), options);\n end\n\n return class\nend\n\nreturn Class\n";
|
|
99028
|
+
var lua_api_class = "\nlocal Class = {}\n\nClass.__setmetatable = setmetatable\n_G.setmetatable = function()\n error(\"Do not use setmetatable. Use Class.new() instead!\")\nend\n\n-- Put the class in the global scope\n_G.Class = Class\n\nfunction Class.new(self, super)\n if self ~= Class then\n -- new was called with dot syntax, so we need to move self to super.\n super = self\n end\n\n local class, metatable, properties = {}, {}, {}\n class.metatable = metatable\n class.properties = properties\n class.super = super\n\n function metatable:__index(key)\n local prop = properties[key]\n if prop then\n return prop:get()\n elseif class[key] ~= nil then\n return class[key]\n elseif class.__customIndex then\n return class.__customIndex(self, key)\n elseif super then\n return super.metatable.__index(self, key)\n else\n return nil\n end\n end\n\n function metatable:__newindex(key, value)\n local prop = properties[key]\n if prop then\n prop:set(value)\n elseif class.__customNewIndex then\n class.__customNewIndex(self, key, value)\n else\n if (super and super.metatable.__customnewindex(self, key, value)) then\n return\n end\n rawset(self, key, value)\n end\n end\n\n function metatable:__customnewindex(key, value)\n if class.__customNewIndex then\n class.__customNewIndex(self, key, value)\n return true\n elseif super then\n return super.metatable.__customnewindex(self, key, value)\n end\n return false\n end\n\n function class:getClass()\n return class\n end\n\n function class.new(self, ...)\n local obj = Class.__setmetatable({}, class.metatable)\n\n if obj.__new then\n if self ~= class then\n -- new was called with dot syntax\n obj:__new(self, ...)\n else\n obj:__new(...)\n end\n end\n\n return obj\n end\n\n function tableLength(T)\n local count = 0\n for _ in pairs(T) do\n count = count + 1\n end\n return count\n end\n\n function class:addProperty(key, propType, defaultValue, options)\n options = options or {}\n if type(options) == 'string' then\n options = { info=options }\n end\n\n if class.properties[key] then\n error(\"A property with the name '\" .. key .. \"' already exists!\");\n return;\n end\n class.properties[key] = Property.new(propType, defaultValue, tableLength(class.properties), options);\n end\n\n return class\nend\n\nreturn Class\n";
|
|
98993
99029
|
|
|
98994
99030
|
var lua_api_console = "\nlocal _internal = require('engine/_internal');\n\n--- @module console\nlocal console = {}\n\n-- Add Console to the global scope\n_G.Console = console\n\n---Output log message\n---@param text string\nfunction console.log(text)\n _internal.sendMessage('console.log', { text=text })\nend\n\n---Output debug message\n---@param text string\nfunction console.debug(text)\n _internal.sendMessage('console.debug', { text=text })\nend\n\n---Output warning message\n---@param text string\nfunction console.warning(text)\n _internal.sendMessage('console.warning', { text=text })\nend\n\n---Output error message\n---@param text string\nfunction console.error(text)\n _internal.sendMessage('console.error', { text=text })\nend\n\n---Output inspector to the console that allows inspecting the value with a UI\n---@param value any\nfunction console.inspect(value)\n _internal.sendMessage('console.inspect', { value=value })\nend\n\nreturn console\n";
|
|
98995
99031
|
|
|
@@ -99073,7 +99109,7 @@ var lua_api_project = "\nlocal SceneEntry = require('engine/sceneentry')\nlocal
|
|
|
99073
99109
|
|
|
99074
99110
|
var lua_api_promise = "\nlocal handle = require 'engine/handle'\nlocal _internal = require 'engine/_internal'\nlocal Console = require 'engine/console'\n\n---@class Promise\nlocal Promise = {}\nPromise.__index = Promise\n\n-- Put the class in the global scope\n_G.Promise = Promise\n\nlocal _managedPromises = {}\nlocal _handleMap = {}\n\nfunction Promise:__init()\n _managedPromises = {}\n _handleMap = {}\nend\n\nfunction Promise.new(self, executorOrHandle)\n\n if self ~= Promise then\n executorOrHandle = self\n end\n\n self = Class.__setmetatable({}, Promise)\n self._type = \"Promise\"\n self._isPromise = true\n self.status = \"pending\"\n self.value = nil\n self.reason = nil\n self.onFulfilled = {}\n self.onRejected = {}\n\n table.insert(_managedPromises, self)\n\n if type(executorOrHandle) == \"string\" then\n self._handle = executorOrHandle\n _handleMap[self._handle] = self\n return self\n elseif type(executorOrHandle) ~= \"function\" then\n error(\"Promise.new() expects a function or a string handle\")\n end\n\n local function resolve(value)\n if self.status ~= \"pending\" then\n return\n end\n\n if value == self then\n return reject(\"Cannot resolve promise with itself\")\n end\n\n -- If value is a Promise, adopt its state\n if type(value) == \"table\" and value._isPromise then\n value:next(resolve, reject)\n return\n end\n\n self.status = \"fulfilled\"\n self.value = value\n coroutine.yield({ __engine_call=true }, \"promiseDone\", self._handle)\n end\n\n local function reject(reason)\n if self.status ~= \"pending\" then return end\n self.status = \"rejected\"\n self.reason = reason\n coroutine.yield({ __engine_call=true }, \"promiseDone\", self._handle)\n end\n\n self._handle = _internal.randomHex8()\n _handleMap[self._handle] = self\n\n local co = coroutine.create(function()\n executorOrHandle(resolve, reject)\n end)\n coroutine.yield({ __engine_call=true }, \"promise\", self._handle, co)\n\n return self\nend\n\nfunction Promise._processQueue()\n local processed = 0\n\n repeat\n processed = 0\n local i = 1\n while i <= #_managedPromises do\n local promise = _managedPromises[i]\n\n if promise == nil then\n table.remove(_managedPromises, i)\n elseif promise.status == \"fulfilled\" then\n for _, callback in ipairs(promise.onFulfilled) do\n callback(promise.value)\n end\n if promise._handle then _handleMap[promise._handle] = nil end\n table.remove(_managedPromises, i) -- removes and shifts\n processed = processed + 1\n elseif promise.status == \"rejected\" then\n local caught = false\n for _, callback in ipairs(promise.onRejected) do\n callback(promise.reason)\n caught = true\n end\n if not caught then\n Console.error(\"Uncaught rejection! -> \" .. promise.reason);\n end\n if promise._handle then _handleMap[promise._handle] = nil end\n table.remove(_managedPromises, i)\n processed = processed + 1\n else\n i = i + 1\n end\n end\n until processed == 0\nend\n\nfunction Promise:next(onFulfilled, onRejected)\n return Promise.new(function(resolve, reject)\n local function handleFulfilled(value)\n if type(onFulfilled) == \"function\" then\n local ok, result = pcall(onFulfilled, value)\n if ok then\n if type(result) == \"table\" and result._isPromise then\n result:next(resolve, reject)\n else\n resolve(result)\n end\n else\n reject(result)\n end\n else\n resolve(value)\n end\n end\n\n local function handleRejected(reason)\n if type(onRejected) == \"function\" then\n local ok, result = pcall(onRejected, reason)\n if ok then\n if type(result) == \"table\" and result._isPromise then\n result:next(resolve, reject)\n else\n resolve(result)\n end\n else\n reject(result)\n end\n else\n reject(reason)\n end\n end\n\n if self.status == \"fulfilled\" then\n handleFulfilled(self.value)\n elseif self.status == \"rejected\" then\n handleRejected(self.reason)\n else\n table.insert(self.onFulfilled, handleFulfilled)\n table.insert(self.onRejected, handleRejected)\n end\n end)\nend\n\nfunction Promise:catch(onRejected)\n return self:next(nil, onRejected)\nend\n\nfunction Promise.all(self, promises)\n\n if self ~= Promise then\n promises = self\n end\n\n return Promise.new(function(resolve, reject)\n local results = {}\n local remaining = #promises\n\n for i, p in ipairs(promises) do\n p:next(function(value)\n results[i] = value\n remaining = remaining - 1\n if remaining == 0 then\n resolve(results)\n end\n end, function(err)\n reject(err)\n end)\n end\n\n if remaining == 0 then\n resolve(table.unpack(results))\n end\n end)\nend\n\n-- Engine calls this to resolve or reject promises externally\n-- res = { handle = \"0xABC\", type = \"resolved\" or \"rejected\", value = ... }\nfunction Promise._externalResult(res)\n local promise = _handleMap[res._handle]\n if not promise or promise.status ~= \"pending\" then return end\n\n if res.type == \"resolved\" then\n if type(res.value) == 'table' and res.value._isHandle then\n res.value = handle.createObject(res.value)\n end\n promise.status = \"fulfilled\"\n promise.value = res.value\n\n elseif res.type == \"rejected\" then\n promise.status = \"rejected\"\n promise.reason = res.error\n end\n\n Promise._processQueue()\n\nend\n\nfunction Promise.awaitAll(self, promises)\n if self ~= Promise then\n promises = self\n end\n\n return await(Promise.all(promises))\nend\n\nfunction Promise:await()\n return await(self)\nend\n\nfunction Promise._debugStats()\n local handleCount = 0\n for _ in pairs(_handleMap) do\n handleCount = handleCount + 1\n end\n\n local pendingCount = 0\n local fulfilledCount = 0\n local rejectedCount = 0\n for i = 1, #_managedPromises do\n local p = _managedPromises[i]\n if p then\n if p.status == \"pending\" then\n pendingCount = pendingCount + 1\n elseif p.status == \"fulfilled\" then\n fulfilledCount = fulfilledCount + 1\n elseif p.status == \"rejected\" then\n rejectedCount = rejectedCount + 1\n end\n end\n end\n\n return {\n managedCount = #_managedPromises,\n pendingCount = pendingCount,\n fulfilledCount = fulfilledCount,\n rejectedCount = rejectedCount,\n handleCount = handleCount\n }\nend\n\nreturn Promise\n";
|
|
99075
99111
|
|
|
99076
|
-
var lua_api_property = "\nlocal Class = require('engine/class')\nlocal Tools = require('engine/tools')\n\nlocal Property = Class.new()\n\n-- Put the class in the global scope\n_G.Property = Property\n\nProperty.String = \"string\"\nProperty.Number = \"number\"\nProperty.Bool = \"bool\"\nProperty.Boolean = \"bool\"\nProperty.Node = \"node\"\nProperty.Separator = \"separator\"\n\nProperty.Datatypes = {
|
|
99112
|
+
var lua_api_property = "\nlocal Class = require('engine/class')\nlocal Tools = require('engine/tools')\n\nlocal Property = Class.new()\n\n-- Put the class in the global scope\n_G.Property = Property\n\nProperty.String = \"string\"\nProperty.Number = \"number\"\nProperty.Bool = \"bool\"\nProperty.Boolean = \"bool\"\nProperty.Node = \"node\"\nProperty.Link = \"link\"\nProperty.Separator = \"separator\"\nProperty.NumberArray = \"numberarray\"\nProperty.StringArray = \"stringarray\"\nProperty.BoolArray = \"boolarray\"\nProperty.BooleanArray = \"boolarray\"\nProperty.NodeArray = \"nodearray\"\nProperty.LinkArray = \"linkarray\"\n\nProperty.Datatypes = {\n Property.String, Property.Number, Property.Bool,\n Property.Node, Property.Link, Property.Separator,\n Property.NumberArray, Property.StringArray, Property.BoolArray,\n Property.NodeArray, Property.LinkArray,\n}\n\n--- Hook for the Class to call when a new object is created\n---@param datatype string type of property\n---@param value any initial value of the property\n---@param order number a number used for odering the properties\n---@param options table options for the property\n---@param options.info string an info text that can be displayed as tooltip in the editor UI\n---@param options.minValue number a minimum possible value for the property\n---@param options.maxValue number a maximum possible value for the property\n---@param options.conditions table a conditions object to determine, if that field should be visible in the UI\n---@param options.collapsed boolean when true, separator sections start collapsed in the editor\n---@param options.allowedTypes string[] when set on Link properties, restricts which item types can be linked\n---@private\nfunction Property:__new(datatype, value, order, options)\n\n if not Tools.isValueInTable(Property.Datatypes, datatype) then\n error(\"Invalid datatype for property: \" .. tostring(datatype));\n end\n\n options = options or {}\n\n self._isProperty = true\n self._type = \"Property\"\n self.datatype = datatype\n self.value = value\n self.order = order or 0\n self.info = options.info\n self.minValue = options.minValue\n self.maxValue = options.maxValue\n self.conditions = options.conditions\n self.collapsed = options.collapsed\n self.allowedTypes = options.allowedTypes\nend\n\n--- Set the value of the property\n---@param value any value of the property\nfunction Property:set(value)\n self.value = value\nend\n\n--- Get the value of the property\n---@return any value of the property\nfunction Property:get()\n return self.value\nend\n\n--- If the property has a value of type Node, this will call behaviour() on the node and return its value.\n--- Otherwise it will return nil\n---@param scriptName string name of the script item\n---@return Behaviour the behaviour if found or nil\nfunction Property:behaviour(scriptName)\n if self.datatype ~= Property.Node or not self.value then\n return nil\n end\n\n return self.value:behaviour(scriptName)\nend\n\n--- If the property has a value of type Node, this will call getEntityByScriptName() on the node and return its value.\n--- Otherwise it will return nil\n---@deprecated\n---@param scriptName string name of the script item\n---@return Behaviour the behaviour if found or nil\nfunction Property:entity(scriptName)\n if self.datatype ~= Property.Node or not self.value then\n return nil\n end\n\n return self.value:behaviour(scriptName)\nend\n\nreturn Property\n";
|
|
99077
99113
|
|
|
99078
99114
|
var lua_api_renderer = "\nlocal _internal = require('engine/_internal');\nlocal handle = require 'engine/handle'\n\n--- @module renderer\nlocal renderer = {}\n\nlocal _data = {}\n\nfunction renderer.__setData(data)\n _data = data;\nend\n\n--- Get width of the output in pixels\n---@return number width\nfunction renderer.getWidth()\n return _data.width or 0\nend\n\n--- Get height of the output in pixels\n---@return number height\nfunction renderer.getHeight()\n return _data.height or 0\nend\n\n---Sets a uniform value inside a background shader\n---@param name string\n---@param value string\nfunction renderer.setBackgroundShaderUniform(name, value)\n if value == nil then\n return\n end\n local valueType = 'float';\n if type(value) == 'object' then\n valueType = value._type\n end\n _internal.sendMessage('renderer.setBackgroundShaderUniform', { name=name, value=value, type=valueType })\nend\n\n---Tests which objects are at the specified pixel position on screen\n---@param camera Camera the camera to use. If nil, the main camera of the scene will be used. if that does not exist, the first found camera will be used. If no camera exists at all, the function will throw an error\n---@param x number x position\n---@param y number y position\n---@param findAll boolean set to true, to get all objects at the position, otherwise only the first is returned\n---@return table list of intersections with the ray if findAll is true or a single result or nil if nothing was found.\nfunction renderer.raycast(camera, x, y, findAll)\n local results = _internal.sendMessage('renderer.raycast', { camera=camera, x=x, y=y, findAll=findAll })\n if results then\n if findAll then\n for k, v in pairs(results) do\n v.object = handle.createObject(v.object)\n end\n else\n results.object = handle.createObject(results.object)\n end\n end\n return results;\nend\n\nreturn renderer\n";
|
|
99079
99115
|
|
|
@@ -100299,7 +100335,16 @@ class RtItem extends RtBase {
|
|
|
100299
100335
|
// TODO!
|
|
100300
100336
|
}
|
|
100301
100337
|
findById(params) {
|
|
100302
|
-
|
|
100338
|
+
const id = params.id;
|
|
100339
|
+
if (!id)
|
|
100340
|
+
return null;
|
|
100341
|
+
const itemInstance = this.loadingManager.get(id, this.refId);
|
|
100342
|
+
if (!itemInstance) {
|
|
100343
|
+
console.warn(`Item.findById: item ${id} is not loaded yet`);
|
|
100344
|
+
return null;
|
|
100345
|
+
}
|
|
100346
|
+
this._addLoadedItemInstance(itemInstance);
|
|
100347
|
+
return this.runtime.makeObjectHandle(itemInstance);
|
|
100303
100348
|
}
|
|
100304
100349
|
getId(params) {
|
|
100305
100350
|
return this.runtime.getObjectOfType(params.obj, Item)?.getId();
|
|
@@ -104719,8 +104764,16 @@ class ScriptEngine {
|
|
|
104719
104764
|
let payload;
|
|
104720
104765
|
if (entry.type === "String" && key === "node")
|
|
104721
104766
|
payload = this.packMessage({ scriptName: scriptItemName, value: value, scriptId: scriptId });
|
|
104767
|
+
else if (entry.type === "Link")
|
|
104768
|
+
payload = await this._packLinkFieldValue(value, scriptRunner.getReferenceId());
|
|
104769
|
+
else if (entry.type === "LinkArray")
|
|
104770
|
+
payload = await this._packLinkArrayFieldValue(value, scriptRunner.getReferenceId());
|
|
104771
|
+
else if (entry.type === "NodeArray")
|
|
104772
|
+
payload = this.packMessage(Array.isArray(value) ? value : []);
|
|
104722
104773
|
else
|
|
104723
104774
|
payload = this.packMessage(value);
|
|
104775
|
+
if (!payload)
|
|
104776
|
+
continue;
|
|
104724
104777
|
const funcName = `__set_object_${key}`;
|
|
104725
104778
|
if (this.functionExists(scriptId, funcName))
|
|
104726
104779
|
await this.callFunctionWithObject(scriptId, funcName, payload);
|
|
@@ -104732,11 +104785,55 @@ class ScriptEngine {
|
|
|
104732
104785
|
}
|
|
104733
104786
|
}
|
|
104734
104787
|
}
|
|
104788
|
+
async _resolveLinkHandle(value, referenceId) {
|
|
104789
|
+
let preparedItem;
|
|
104790
|
+
if (typeof value === 'string') {
|
|
104791
|
+
preparedItem = await this.itemRepo.loadItem(value, { recursive: true });
|
|
104792
|
+
}
|
|
104793
|
+
else if (value && value._id) {
|
|
104794
|
+
if (value.type)
|
|
104795
|
+
preparedItem = value;
|
|
104796
|
+
else
|
|
104797
|
+
preparedItem = await this.itemRepo.loadItem(value._id, { recursive: true });
|
|
104798
|
+
}
|
|
104799
|
+
else {
|
|
104800
|
+
return null;
|
|
104801
|
+
}
|
|
104802
|
+
if (!preparedItem)
|
|
104803
|
+
return null;
|
|
104804
|
+
const loadingManager = this.engine.loadingManager;
|
|
104805
|
+
const ItemType = loadingManager.typeNameToType(preparedItem.type);
|
|
104806
|
+
let itemInstance = loadingManager.get(preparedItem._id, referenceId);
|
|
104807
|
+
if (!itemInstance)
|
|
104808
|
+
itemInstance = await loadingManager.load(referenceId, preparedItem, ItemType, { waitUntilFinished: true });
|
|
104809
|
+
if (!itemInstance)
|
|
104810
|
+
return null;
|
|
104811
|
+
return this.scriptRuntime.makeObjectHandle(itemInstance);
|
|
104812
|
+
}
|
|
104813
|
+
async _packLinkFieldValue(value, referenceId) {
|
|
104814
|
+
const handle = await this._resolveLinkHandle(value, referenceId);
|
|
104815
|
+
return handle ? this.packMessage(handle) : null;
|
|
104816
|
+
}
|
|
104817
|
+
async _packLinkArrayFieldValue(values, referenceId) {
|
|
104818
|
+
if (!Array.isArray(values))
|
|
104819
|
+
return null;
|
|
104820
|
+
const handles = [];
|
|
104821
|
+
for (const value of values) {
|
|
104822
|
+
if (value == null)
|
|
104823
|
+
continue;
|
|
104824
|
+
const handle = await this._resolveLinkHandle(value, referenceId);
|
|
104825
|
+
if (handle)
|
|
104826
|
+
handles.push(handle);
|
|
104827
|
+
}
|
|
104828
|
+
return this.packMessage(handles);
|
|
104829
|
+
}
|
|
104735
104830
|
_prepareCode(code, scriptItemId, injectedFields = undefined) {
|
|
104736
104831
|
let varCode = "";
|
|
104737
104832
|
let injectedVarsNumLines = 0;
|
|
104738
104833
|
if (injectedFields) {
|
|
104739
104834
|
for (const field of injectedFields) {
|
|
104835
|
+
if (field.type === 'separator')
|
|
104836
|
+
continue;
|
|
104740
104837
|
switch (field.type) {
|
|
104741
104838
|
case 'node':
|
|
104742
104839
|
if (field.name === 'node')
|
|
@@ -104745,8 +104842,26 @@ class ScriptEngine {
|
|
|
104745
104842
|
varCode += `function __set_object_${field.name}(object, data, len) if type(object.${field.name}) == 'table' then object.${field.name}:set(__api_sceneobject:findById(__api_internal.fetchAndUnpack(data, len))) else object.${field.name} = __api_sceneobject:findById(__api_internal.fetchAndUnpack(data, len)) end end\n`;
|
|
104746
104843
|
injectedVarsNumLines++;
|
|
104747
104844
|
break;
|
|
104845
|
+
case 'link':
|
|
104846
|
+
varCode += `function __set_object_${field.name}(object, data, len) local __handle = require('engine/handle'); local item = __handle.createObject(__api_internal.fetchAndUnpack(data, len)); if type(object.${field.name}) == 'table' and object.${field.name}.set then object.${field.name}:set(item) else object.${field.name} = item end end\n`;
|
|
104847
|
+
injectedVarsNumLines++;
|
|
104848
|
+
break;
|
|
104849
|
+
case 'numberarray':
|
|
104850
|
+
case 'stringarray':
|
|
104851
|
+
case 'boolarray':
|
|
104852
|
+
varCode += `function __set_object_${field.name}(object, data, len) object.${field.name} = __api_internal.fetchAndUnpack(data, len) end\n`;
|
|
104853
|
+
injectedVarsNumLines++;
|
|
104854
|
+
break;
|
|
104855
|
+
case 'nodearray':
|
|
104856
|
+
varCode += `function __set_object_${field.name}(object, data, len) local ids = __api_internal.fetchAndUnpack(data, len); local nodes = {}; for i, id in ipairs(ids or {}) do nodes[i] = __api_sceneobject:findById(id) end; object.${field.name} = nodes end\n`;
|
|
104857
|
+
injectedVarsNumLines++;
|
|
104858
|
+
break;
|
|
104859
|
+
case 'linkarray':
|
|
104860
|
+
varCode += `function __set_object_${field.name}(object, data, len) local __handle = require('engine/handle'); local handles = __api_internal.fetchAndUnpack(data, len); local items = {}; for i, h in ipairs(handles or {}) do items[i] = __handle.createObject(h) end; object.${field.name} = items end\n`;
|
|
104861
|
+
injectedVarsNumLines++;
|
|
104862
|
+
break;
|
|
104748
104863
|
default:
|
|
104749
|
-
varCode += `function __set_object_${field.name}(object, data, len) if type(object.${field.name}) == 'table' then object.${field.name}:set(__api_internal.fetchAndUnpack(data, len)) else object.${field.name} = __api_internal.fetchAndUnpack(data, len) end end\n`;
|
|
104864
|
+
varCode += `function __set_object_${field.name}(object, data, len) if type(object.${field.name}) == 'table' and object.${field.name}.set then object.${field.name}:set(__api_internal.fetchAndUnpack(data, len)) else object.${field.name} = __api_internal.fetchAndUnpack(data, len) end end\n`;
|
|
104750
104865
|
injectedVarsNumLines++;
|
|
104751
104866
|
break;
|
|
104752
104867
|
}
|