scripted-engine/src/logic/logic.cpp

117 lines
3.1 KiB
C++

#include "logic.hpp"
#include "engine.hpp"
#include "wren/vm/wren_vm.h"
#include <cassert>
#include <cstdio>
#include <functional>
#include <iostream>
#include <string>
void writeOutput(WrenVM *vm, const char *text) {
std::cout << text;
}
void errorOutput(WrenVM *vm, WrenErrorType type, const char *module, int line, const char *message) {
if (module != nullptr) {
std::cerr << "wren error [module \"" << module << "\", line " << line << "]: " << message << "\n";
} else {
std::cerr << "wren error: " << message << "\n";
}
}
char *fileContent(const char *path) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return nullptr;
}
// Get the file length.
fseek(f, 0, SEEK_END);
size_t fileLength = ftell(f);
rewind(f);
// Read the file.
char *fileContent = (char *)malloc(fileLength + 1);
size_t bytesRead = fread(fileContent, sizeof(char), fileLength, f);
fclose(f);
if (fileLength != bytesRead) {
free(fileContent);
return nullptr;
}
fileContent[fileLength] = '\0';
return fileContent;
}
std::string getPath(const char *name) {
std::string root("/Users/ffreling/Code/scripted-engine/src/scripts/");
return root + name + ".wren";
}
char *loadModule(WrenVM *vm, const char *name) {
std::string path = getPath(name);
return fileContent(path.c_str());
}
Logic::Logic(Engine *engine) {
WrenConfiguration wrenConfig;
wrenInitConfiguration(&wrenConfig);
wrenConfig.bindForeignMethodFn = &Logic::bindForeignMethod;
wrenConfig.writeFn = &writeOutput;
wrenConfig.errorFn = &errorOutput;
wrenConfig.loadModuleFn = &loadModule;
_wrenVm = wrenNewVM(&wrenConfig);
// Setup user-defined data such as pointer to "global" objects.
_bundleData.engine = engine;
wrenSetUserData(_wrenVm, &_bundleData);
WrenInterpretResult result = wrenInterpret(_wrenVm, "scripted-engine", "System.print(\"I am running in a VM!\")");
assert(result == WREN_RESULT_SUCCESS);
}
Logic::~Logic() {
wrenFreeVM(_wrenVm);
}
void get_info(WrenVM *vm) {
// Retrieve "global" objects defined in userData
BundleData *bundleData = reinterpret_cast<BundleData *>(wrenGetUserData(vm));
Engine *engine = bundleData->engine;
assert(engine);
wrenEnsureSlots(vm, 1);
wrenSetSlotDouble(vm, 0, engine->get_info());
}
WrenForeignMethodFn
Logic::bindForeignMethod(WrenVM *vm, const char *module, const char *className, bool isStatic, const char *signature) {
if (strcmp(module, "engine") == 0) {
if (strcmp(className, "Engine") == 0) {
if (isStatic && strcmp(signature, "getInfo()") == 0) {
return get_info;
}
// Other foreign methods on Engine...
}
// Other classes in engine...
}
// Other modules...
return nullptr;
}
void Logic::interpret(const char *name) {
assert(_wrenVm);
std::string path = getPath(name);
char *script = fileContent(path.c_str());
WrenInterpretResult result = wrenInterpret(_wrenVm, name, script);
assert(result == WREN_RESULT_SUCCESS);
}
void Logic::add_item() {
}