Jump to content

Need Help integrating my class


Recommended Posts

Hey guys,

 

I need help to ingrate my lua support class.

 

Quote

//using Database;
//using Harmony;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using MoonSharp.Interpreter;

namespace luascriptmod
{

    public class LuaDebug : MonoBehaviour
    {
        void Start()
        {
            Debug.Log("Start");
            Debug.Log(Helper.scriptpath);
            Scripting.CallScriptOn("initialisation");
        }

    }
    public static  class Helper
    {
        public static bool scriptingstarted = false;
        public static string onidatapath= UnityEngine.Application.dataPath; // TODO add the environment variable datapath
        public static string scriptpath= Path.Combine(onidatapath,"Script");
        public static Dictionary<string, Scripting> scriptlist=new Dictionary<string, Scripting>();
    }
    public class Scripting
    {

        public static void CallScriptOn(string appevent) // TODO insert calls to scripting: initialisation after stuff was loaded, update, on night end, and so on.
        {
            if (appevent == "initialisation")
            {
                if (!Helper.scriptingstarted)
                {
                    Debug.Log("init");
                    new Scripting("init", "gameinitscript", "startscript");
                    Helper.scriptingstarted = true;
                }
            }
            if (Helper.scriptlist.ContainsKey(appevent)) {
                Helper.scriptlist[appevent].ExecuteThisScript(); }
        }
        public void RegisterScriptOnEvent(string appevent)
        {
            Helper.scriptlist[appevent] = this;
        }

        public static string Combinem(params string[] paths)
        {
            string pat = "";
            foreach (string s in paths)
            {
                pat = Path.Combine(pat, s);
            }
            return pat;
        }

        string scriptfolder;
        string scriptfile;
        string scriptname;
        //public scripting(string scriptsetting) { pre("Todo repair this"); }
        public Scripting(string scriptfolderi, string scriptfilen, string scriptnamei = null)
        {
            scriptfolder = scriptfolderi;
            scriptfile = scriptfilen;
            if (scriptnamei != null) { scriptname = scriptnamei; } else { scriptname = "startscript"; }
            ExecuteThisScript();
        }
        public void ExecuteThisScript()
        {
            scriptfile = Combinem(Helper.scriptpath, scriptfolder, scriptfile + ".lua");
            string scriptCode = File.ReadAllText(scriptfile);
            EvalText(scriptCode);
        }
        public Scripting(string scriptCode)
        {
            EvalText(scriptCode);
        }

        Script script;
        public void EvalText(string scriptCode)
        {//this is the Core of the scripting engine it does the actual work.

            script = new Script(); //Generating the script instance

            //UserData.RegisterAssembly(); //registering the asseblys you need to add [MoonSharpUserData] to the data you want to expose more under http://www.moonsharp.org/objects.html

            UserData.RegistrationPolicy = MoonSharp.Interpreter.Interop.InteropRegistrationPolicy.Automatic; //the more dangerous approach
            //script.Globals["CreateBuildingDef"] = (Func<string, int, int, string, int, float, float[], string[], float, BuildLocationRule, EffectorValues, EffectorValues, float, BuildingDef>)BuildingTemplates.CreateBuildingDef; // TODO Integrate with oni
            // public static BuildingDef CreateBuildingDef(string id, int width, int height, string anim, int hitpoints, float construction_time, float[] construction_mass, string[] construction_materials, float melting_point, BuildLocationRule build_location_rule, EffectorValues decor, EffectorValues noise, float temperature_modification_mass_scale = 0.2f)

            script.Globals["NewScript"] = (Func<string, string, string, Scripting>)NewScript;
            script.Globals["RegisterFunction"] = (Func<string, object,object>)RegisterFunction;
            script.Globals["GetClassFromString"] = (Func<string, object>)GetClassFromString;
            script.Globals["GetMethodFromString"] = (Func<string,string,string, object>)GetMethodFromString;
            script.Globals["Log"] = (Func<string,string>)Logger;
            

            //exposing a function so it can be called from lua syntax is: Func<parameters, returntype>

            script.DoString(scriptCode); //The command to load scriptCode as module more under http://www.moonsharp.org/scriptloaders.html

            DynValue res = script.Call(script.Globals[scriptname]); //Calling the function inside the code you should define a default value here More about dynvalue http://www.moonsharp.org/dynvalue.html

        }

        public object GetClassFromString(string className)
        {
            //return System.Activator.CreateInstance(Type.GetType(className));
            return Type.GetType(className);
        }
        public object GetMethodFromString(string className, string methodName, string stringparameter)
        {
            //return System.Activator.CreateInstance(Type.GetType(className));
            return Type.GetType(className).GetMethod(methodName).Invoke( null, new object[] { (object) stringparameter});
        }
        public object RegisterFunction(string scriptName, object functionToCall)
        {
            script.Globals["scriptName"] = functionToCall;
            return functionToCall;
        }


        public Scripting NewScript(string scriptfolderi, string scriptfilen, string scriptnamei)
        {
            return new Scripting(scriptfolderi, scriptfilen, scriptnamei);
        }
        static public string Logger(string logging)
        {
            Debug.Log(logging);
            return logging;
        }
    }
}

 

I have now few options:

A) someone who has access to the sourcecode integrates it. In that case please just post here that would close this topic.

B) I wait for some way.

C) I Use the modloader to slip the code into the game. I dont know how to do this an would need quite some help.

Tested with unity i attached the project.

I would need help with the 3 todos:

i need the variable for the onidatapath.

I need a way to place the functions to call CallScriptOn in different places: before start, after template was loaded, onupdate, ondaystart

I need help to use the modloader and actually get the code in.

 

Also the code would need a proper way to get and execute classes and methods since likely that would greatly benefit modding since then mods could really be based on simple lua files.

 

Assets.zip

Link to comment
Share on other sites

29 minutes ago, Skrivener said:

Its not a suggestion or proposal. Its a request for help with a mod especially since i think the community has to do it itself. I have seen the devs only answer to updates and bugs thats why i personally dont think they will integrate it anytime soon.

My best bet is that someone who does know a bit about code injection will answer me and integrate it.

Link to comment
Share on other sites

I've gotta admit that I'm unsure why you'd want to integrate a scripting engine to use LUA. Can't you just use the ModLoader and then develop your mods with direct access to the source code because of the Injector?

Honestly, I think you'll quickly run into issues having to maintain that layer between the Unity engine and the scripting engine, effectively having to do all the work that ModLoader already does for generating IL and giving access to all methods, types and properties through reflection, but instead, having to expose that to the scripting engine.

Link to comment
Share on other sites

Actually its exactly the opposite with the modloader you have to compile everything and inject it. With the lua integrated you can just add some lines in a file and try how it woks inside maybe you could even add buildings during runtime. Also it could support adding events.

 

My experience with the modloader is that all that is very complicated right now so complicated that i cannot use it. A lua script would be a simple file you put in a folder and its executed and inserted automatically.

 

Quote

breaks any EULA,

Why? Which part you refer to? i doubt this fits under the cheating part. I think if the lua stuff breaks it, the modloader would too.

Link to comment
Share on other sites

1 hour ago, Rainbowdesign said:

My experience with the modloader is that all that is very complicated right now so complicated that i cannot use it. A lua script would be a simple file you put in a folder and its executed and inserted automatically.

That's exactly all you have to do with mods. You run injector.exe once when the game is updated by steam (it overrides the dlls) then put compiled mods in the Mods folder, no need to inject every mod separately. The only downside is that you need to restart a game, but that's pretty common in most games with lua support, because they do a great deal of stuff on startup. Really not rocket science, especially if you are a dev.

Link to comment
Share on other sites

You sure you placed all files in the correct folder? Instructions are here: https://github.com/javisar/ONI-Modloader#installation . It's an exe with a bunch of dlls that you need to place in the game data folder.

Mod examples are here: https://github.com/javisar/ONI-Modloader-Mods; or some more in my repo https://github.com/Cairath/ONI-Mods

The first two links literally have links to Harmony documentation (or you can even google harmony mods, there's tons for many games). It's normal that they won't release an official mod API during such early stages when so much stuff is changing. 

edit: might wanna keep in mind that if you are playing the preview branch, the target framework changed from 3.5 to 4.0 and both the mods and the injector are not compatible between cosmic and expression upgrades.

Link to comment
Share on other sites

I redownloaded it now installed it and executed it without a sandbox its behaving different now.

It shows:

Reading modules:

\Assembly-CSharp.dll
\Assembly-CSharp-firstpass.dll
LaunchInitializer.Awake not found

 

I dont use the preview branch. So i use the cosmic upgrade.

As for modding:

I have big problems to find things inside oni i wanted to change what the pacus and sage hatch excrete. I looked long where and how to change that. But still no idea.

For the lua stuff i guess maybe it will be better to wait till oni is more mature.

I digged into harmony i think i can atleast adapt existing mods. But i am insecure if the syntax is right:

 

 

using Harmony;
using JetBrains.Annotations;
using TUNING;
using UnityEngine;

namespace Patches
{
    [HarmonyPatch(typeof(LiquidHeaterConfig), "CreateBuildingDef", null)]
    public static class LiquidHeaterMod
    {
        public static void Postfix([NotNull] BuildingDef __result)
        {
            Debug.Log((object)" === LiquidHeaterMod INI === ", (Object)null);
            __result.MaterialCategory = MATERIALS.ANY_BUILDABLE;
            __result.OverheatTemperature = 1000398.15f;
        }
    }

    [HarmonyPatch(typeof(LiquidPumpConfig), "CreateBuildingDef", null)]
    public static class LiquidPumpmod
    {
        public static void Postfix([NotNull] BuildingDef __result)
        {
            __result.MaterialCategory = MATERIALS.ANY_BUILDABLE;
            __result.OverheatTemperature = 1000398.15f;
        }
    }

    [HarmonyPatch(typeof(GasPumpConfig), "CreateBuildingDef", null)]
    public static class GasPumpMod
    {
        public static void Postfix([NotNull] BuildingDef __result)
        {
            __result.MaterialCategory = MATERIALS.ANY_BUILDABLE;
            __result.OverheatTemperature = 1000398.15f;
            Debug.Log((object)" === LiquidHeaterMod END === ", (Object)null);
        }
    }
}

Link to comment
Share on other sites

First of all, don't use jetbrains annotations. That's another lib you'd need to include.

If you want to modify the result you need to use ref (basically all C# rules apply here).

10 minutes ago, Rainbowdesign said:

Reading modules:

\Assembly-CSharp.dll
\Assembly-CSharp-firstpass.dll
LaunchInitializer.Awake not found

Sooo... either it's in a wrong location (it should be in \OxygenNotIncluded\OxygenNotIncluded_Data\Managed) or you're on preview, cause it's not finding the game startup.

 

If you're in the oni discord you can find me there, or pm me on discord for more help, easier than typing here

Link to comment
Share on other sites

17 hours ago, Rainbowdesign said:

I redownloaded it now installed it and executed it without a sandbox its behaving different now.

It shows:

Reading modules:

\Assembly-CSharp.dll
\Assembly-CSharp-firstpass.dll
LaunchInitializer.Awake not found

 

I dont use the preview branch. So i use the cosmic upgrade.

As for modding:

That 'LaunchInitializer.Awake not found' message is probably because you have the Expression Upgrade (preview).

17 hours ago, Rainbowdesign said:

As for modding:

I have big problems to find things inside oni i wanted to change what the pacus and sage hatch excrete. I looked long where and how to change that. But still no idea.

For the lua stuff i guess maybe it will be better to wait till oni is more mature.

I digged into harmony i think i can atleast adapt existing mods. But i am insecure if the syntax is right:

It's not easy to find the right place, sometimes could take hours to dig into the code. The best way I found is trial and error with something simple.

I agree with you in the lua stuff, it is likely that Klei will add somekind of mod Api in the future. If i'm in the mood I'll have a look. I haven't tried to hook important functions in the game due it's early nature, but I've identified some of them.

The hatch diet seems to be setted in functions like HatchMetalConfig.CreateHatch so you could in theory mess with the parameter 'diet_infos' passed to the function BaseHatchConfig.SetupDiet in a Prefix,

For the onidatapath you can use the .Net function Directory.GetCurrentDirectory() and navigate from there or have a look to the (messy) code of

https://github.com/javisar/ONI-Modloader/tree/master/Source

 

Link to comment
Share on other sites

hehe same as if i try to explain anything my girlfriend ;)

5 hours ago, trevice said:

It's not easy to find the right place, sometimes could take hours to dig into the code.

 

Indeed.... Cairath has helped me with the modding stuff so i go something already now like the lava heater mod might get ready today.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

Please be aware that the content of this thread may be outdated and no longer applicable.

×
  • Create New...