refactor: script API

This commit is contained in:
cha0s 2024-07-11 15:43:08 -05:00
parent a208863823
commit e2c62a6522
5 changed files with 33 additions and 33 deletions

View File

@ -41,10 +41,22 @@ export default class ClientEcs extends Ecs {
}
return cache.get(key);
}
async readScript(uri, context = {}) {
const code = await this.readAsset(uri);
if (code.byteLength > 0) {
return Script.fromCode((new TextDecoder()).decode(code), context);
async readScript(uriOrCode, context = {}) {
if (!uriOrCode) {
return undefined;
}
let code = '';
if (!uriOrCode.startsWith('/')) {
code = uriOrCode;
}
else {
const buffer = await this.readAsset(uriOrCode);
if (buffer.byteLength > 0) {
code = (new TextDecoder()).decode(buffer);
}
}
if (code) {
return Script.fromCode(code, context);
}
}
}

View File

@ -82,7 +82,7 @@ class ItemProxy {
if (this.scripts.projectionCheckInstance) {
this.scripts.projectionCheckInstance.context.ecs = this.Component.ecs;
this.scripts.projectionCheckInstance.context.projected = projected;
return this.scripts.projectionCheckInstance.evaluateSync();
return this.scripts.projectionCheckInstance.evaluate();
}
else {
return projected;

View File

@ -7,7 +7,7 @@ export default class Plant extends Component {
const Instance = super.instanceFromSchema();
return class PlantInstance extends Instance {
mayGrow() {
return this.mayGrowScriptInstance.evaluateSync();
return this.mayGrowScriptInstance.evaluate();
}
grow() {
const {Ticking} = ecs.get(this.entity);

View File

@ -76,13 +76,22 @@ export default class Engine {
}
return cache.get(key);
}
async readScript(uri, context) {
if (!uri) {
async readScript(uriOrCode, context) {
if (!uriOrCode) {
return undefined;
}
const code = await this.readAsset(uri);
if (code.byteLength > 0) {
return Script.fromCode((new TextDecoder()).decode(code), context);
let code = '';
if (!uriOrCode.startsWith('/')) {
code = uriOrCode;
}
else {
const buffer = await this.readAsset(uriOrCode);
if (buffer.byteLength > 0) {
code = (new TextDecoder()).decode(buffer);
}
}
if (code) {
return Script.fromCode(code, context);
}
}
async switchEcs(entity, path, updates) {

View File

@ -65,28 +65,7 @@ export default class Script {
};
}
// async evaluate(callback) {
// this.sandbox.reset();
// let {done, value} = this.sandbox.next();
// if (value instanceof Promise) {
// await value;
// }
// while (!done) {
// ({done, value} = this.sandbox.next());
// if (value instanceof Promise) {
// // eslint-disable-next-line no-await-in-loop
// await value;
// }
// }
// if (value instanceof Promise) {
// value.then(callback);
// }
// else {
// callback(value);
// }
// }
evaluateSync() {
evaluate() {
this.sandbox.reset();
const {value} = this.sandbox.run();
return value;