Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ addons/*
dev-libs/
*.sum
.vs/
export_classes.info
3 changes: 3 additions & 0 deletions project.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
<!-- NOTE before v1.1.0 release: PLEASE DO THIS ABOVE -->
<define name="DISCORD_RPC" if="desktop"/>

<!-- cppia JIT host: mods can ship .cppia bytecode for hscript to import; disable with -DNO_SCRIPTABLE -->
<define name="scriptable" unless="NO_SCRIPTABLE || STRIPPED_COMPILE"/>

<!-- Compile with video support (hxvlc) -->
<define name="VIDEO_CUTSCENES" if="desktop || mobile"/>
</section>
Expand Down
6 changes: 6 additions & 0 deletions source/cppia/ScriptEntry.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package cppia;

class ScriptEntry
{
public static function main():Void {}
}
131 changes: 131 additions & 0 deletions source/funkin/backend/scripting/CppiaScript.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package funkin.backend.scripting;

#if (cpp && scriptable)
import funkin.backend.scripting.cppia.CppiaModule;
import funkin.backend.system.Logs;

class CppiaScript extends Script
{
/**
* The entry class instance all calls are forwarded to.
*/
public var instance:Dynamic;

// declared fields of the entry class (Reflect.hasField isn't usable on cppia instances)
var __fields:Map<String, Bool>;

// last parent object received through setParent, re-applied after reload
var __lastParent:Dynamic;

/**
* Variables injected by the engine that have no matching instance field (ex: `disableScript` closures).
* Readable via `Script.get` but not accessible from compiled cppia code.
*/
var __extraVars:Map<String, Dynamic> = [];

static function getEntryClassName(script:Script):String
{
var fileName = script.fileName;
var dot = fileName.lastIndexOf(".");
return dot < 0 ? fileName : fileName.substring(0, dot);
}

public override function onCreate(path:String) {
super.onCreate(path);

#if GLOBAL_SCRIPT
funkin.backend.scripting.GlobalScript.call("onScriptCreated", [this, "cppia"]);
#end

// cppia has no top-level code
var className = getEntryClassName(this);
var cls = CppiaModule.resolve(rawPath, className);
if (cls == null) {
error('Failed to load cppia script (entry class "$className" not found)');
return;
}
instance = Type.createInstance(cls, []);
__fields = [for (f in Type.getInstanceFields(cls)) f => true];
}

private override function onCall(funcName:String, parameters:Array<Dynamic>):Dynamic {
if (instance == null) return null;

var func = Reflect.field(instance, funcName);
if (func == null || !Reflect.isFunction(func))
func = __extraVars.get(funcName);
if (func != null && Reflect.isFunction(func))
return Reflect.callMethod(instance, func, parameters == null ? Script._EMPTY_ARGS : parameters);

return null;
}

public override function get(val:String):Dynamic {
if (instance == null) return null;
if (__fields.get(val) == true) {
var v = Reflect.field(instance, val);
// getter-only properties (ex: @:scriptParent forwarders like `dad`) return null here,
// their physical getter method `get_<name>` is still reflectable
if (v == null) {
var getter = Reflect.field(instance, 'get_$val');
if (getter != null && Reflect.isFunction(getter))
return Reflect.callMethod(instance, getter, Script._EMPTY_ARGS);
}
return v;
}
return __extraVars.get(val);
}

public override function set(val:String, value:Dynamic):Void {
if (instance == null) return;
if (__fields.get(val) == true)
Reflect.setProperty(instance, val, value);
else
__extraVars.set(val, value);
}

public override function setParent(variable:Dynamic) {
super.setParent(variable);
__lastParent = variable;
if (instance != null && __fields != null && __fields.get("__parent") == true) {
// validates against the macro-generated type tag; Reflect on a cppia class
// THROWS for missing statics (unlike native classes), so guard it
var expected = null;
try expected = Reflect.field(Type.getClass(instance), "__parentType") catch(_) {}
if (expected != null && variable != null && !Std.isOfType(variable, expected)) {
Logs.warn('Parent type mismatch: expected ${Type.getClassName(expected)} but got ${Type.getClassName(Type.getClass(variable))}, parent forwarders are disabled', fileName);
return;
}
Reflect.setProperty(instance, "__parent", variable);
}
}

public override function reload() {
if (rawPath == null) return;

// CppiaModule's content-signature cache reloads the module if the file changed
var className = getEntryClassName(this);
var cls = CppiaModule.resolve(rawPath, className);
if (cls == null) return;

instance = null;
__extraVars = [];
instance = Type.createInstance(cls, []);
__fields = [for (f in Type.getInstanceFields(cls)) f => true];
// re-inject default variables, the new instance starts fresh
for (k => e in Script.getDefaultVariables(this))
set(k, e);
// restore the parent object on the fresh instance
if (__lastParent != null)
setParent(__lastParent);
}

override public function destroy() {
// the module itself is process-lifetime resident; only the instance is dropped here
instance = null;
__fields = null;
__extraVars = [];
super.destroy();
}
}
#end
28 changes: 28 additions & 0 deletions source/funkin/backend/scripting/HScript.hx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import hscript.*;
import hscript.Expr.Error;
import hscript.Parser;
import openfl.Assets;
#if (cpp && scriptable)
import funkin.backend.scripting.cppia.CppiaModule;
#end

class HScript extends Script {
public var interp:Interp;
Expand Down Expand Up @@ -113,6 +116,31 @@ class HScript extends Script {
return true;
}
}

#if (cpp && scriptable)
// path: mods/<mod>/source/Class.cppia
// scripts: import Class;
var p = '$assetsPath.cppia';
if (__importedPaths.exists(p))
return true;
if (Assets.exists(p)) {
var cls = CppiaModule.resolve(p, cl.join("."));
if (cls == null && cl.length > 1)
cls = CppiaModule.resolve(p, cl[cl.length - 1]);

if (cls != null) {
var varName = cl[cl.length - 1];
if (cl.length > 1)
interp.variables.set(cl.join("."), cls);
if (varName != cl.join("."))
interp.variables.set(varName, cls);
__importedPaths.set(p, true);
return true;
}
return false;
}
#end

return false;
}

Expand Down
7 changes: 7 additions & 0 deletions source/funkin/backend/scripting/Script.hx
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,9 @@ class Script extends FlxBasic implements IFlxDestroyable
"hscript",
"hsc",
"hxs",
#if (cpp && scriptable)
"cppia", // pre-compiled bytecode (CppiaScript)
#end
"pack", // combined file
"lua" /** ACTUALLY NOT SUPPORTED, ONLY FOR THE MESSAGE **/];

Expand Down Expand Up @@ -272,6 +275,10 @@ class Script extends FlxBasic implements IFlxDestroyable
{
case "hx" | "hscript" | "hsc" | "hxs":
new HScript(path);
#if (cpp && scriptable)
case "cppia":
new CppiaScript(path);
#end
case "pack":
var arr = Assets.getText(path).split("________PACKSEP________");
fromString(arr[1], arr[0]);
Expand Down
66 changes: 66 additions & 0 deletions source/funkin/backend/scripting/cppia/CppiaModule.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package funkin.backend.scripting.cppia;

#if (cpp && scriptable)
import cpp.cppia.Module;
import funkin.backend.system.Logs;
import lime.utils.Assets as LimeAssets;

@:headerCode('#include <hx/Scriptable.h>')
class CppiaModule
{
private static var __modules:Map<String, Module> = [];
private static var __signatures:Map<String, String> = [];

static function getSignature(bytes:haxe.io.Bytes):String
return bytes.length + ":" + haxe.crypto.Md5.make(bytes).toHex();

/**
* Enables the CPPIA JIT compiler.
* Not enabled by default, since the current hxcpp JIT silently swallows thrown errors and crashes on generated code.
*/
@:functionCode('hx::gEnableJit = inEnable;')
public static function enableJit(inEnable:Bool):Void {}

public static function load(assetPath:String):Module
{
try {
if (!LimeAssets.exists(assetPath))
return null;

var bytes = LimeAssets.getBytes(assetPath);
var signature = getSignature(bytes);

if (__signatures.get(assetPath) == signature)
return __modules.get(assetPath);

var module = Module.fromData(bytes.getData());
module.boot();
__modules.set(assetPath, module);
__signatures.set(assetPath, signature);
return module;
} catch(e) {
var reason = Std.string(e);
// prevent the application from crashing outright
try __signatures.set(assetPath, getSignature(LimeAssets.getBytes(assetPath))) catch(_) {}
Logs.error('Error while loading cppia module $assetPath: $reason');
return null;
}
}

public static function resolve(assetPath:String, className:String):Class<Dynamic>
{
var module = load(assetPath);
if (module == null)
return null;

return module.resolveClass(className);
}

// modules can't actually be unloaded
public static function clearCache():Void
{
__modules = [];
__signatures = [];
}
}
#end
3 changes: 3 additions & 0 deletions source/funkin/backend/system/MainState.hx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ class MainState extends FlxState {
funkin.backend.scripting.GlobalScript.destroy();
#end
funkin.backend.scripting.Script.staticVariables.clear();
#if (cpp && scriptable)
funkin.backend.scripting.cppia.CppiaModule.clearCache();
#end

#if MOD_SUPPORT
for (addon in _lowPriorityAddons)
Expand Down
Loading