forked from 3DRadSpace/3D_Rad_Space
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScriptManager.cs
More file actions
281 lines (243 loc) · 6.86 KB
/
Copy pathScriptManager.cs
File metadata and controls
281 lines (243 loc) · 6.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
using System.Runtime.InteropServices;
using Engine3DRadSpace.Logging;
using Engine3DRadSpace.Objects;
using Engine3DRadSpace.Scripting;
namespace Engine3DRadSpace.Internal;
/// <summary>
/// Manages compiled scripts and provides entry points for the native C++ host.
/// </summary>
public static class ScriptManager
{
private static readonly Dictionary<int, ScriptInstance> _loadedScripts = new();
private static int _nextScriptId = 1;
/// <summary>
/// Compiles a C# script from a file and returns a script handle.
/// </summary>
/// <param name="scriptPath">Path to the .cs script file.</param>
/// <param name="className">Fully qualified class name to instantiate.</param>
/// <returns>Script ID, or -1 on failure.</returns>
[UnmanagedCallersOnly]
public static int LoadScript(IntPtr scriptPath, IntPtr className, IntPtr ownerObject)
{
try
{
string? path = Marshal.PtrToStringUTF8(scriptPath);
string? classNameStr = Marshal.PtrToStringUTF8(className);
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(classNameStr))
{
PrintWarning("Invalid script path or class name");
return -1;
}
var result = CsCompiler.CompileFromFile(path);
if (!result.Success)
{
string errors = string.Join("\n", result.Errors);
PrintWarning($"Script compilation failed:\n{errors}");
return -1;
}
// Try to create an instance
object? instance;
try
{
instance = result.CreateInstance(classNameStr);
}
catch (Exception ex)
{
PrintWarning($"Failed to create instance: {ex.Message}");
result.Unload();
return -1;
}
if (instance == null)
{
PrintWarning("Failed to create script instance");
result.Unload();
return -1;
}
int scriptId = _nextScriptId++;
_loadedScripts[scriptId] = new ScriptInstance
{
Id = scriptId,
Instance = instance,
CompilationResult = result,
ScriptInterface = instance as Script
};
// Call Start if the script implements IScript
if (_loadedScripts[scriptId].ScriptInterface != null)
{
(_loadedScripts[scriptId].ScriptInterface as Script).Object = new InstIObject(ownerObject);
_loadedScripts[scriptId].ScriptInterface!.Start();
}
return scriptId;
}
catch (Exception ex)
{
PrintWarning($"Exception in LoadScript: {ex.Message}");
return -1;
}
}
/// <summary>
/// Updates a loaded script.
/// </summary>
/// <param name="scriptId">ID of the script to update.</param>
/// <returns>1 on success, 0 on failure.</returns>
[UnmanagedCallersOnly]
public static byte UpdateScript(int scriptId)
{
try
{
if (!_loadedScripts.TryGetValue(scriptId, out var scriptInstance))
return 0;
scriptInstance.ScriptInterface?.Update();
return 1;
}
catch(Exception ex)
{
PrintWarning($"Exception in UpdateScript: {ex.Message}");
return 0;
}
}
/// <summary>
/// Unloads a script and frees its resources.
/// </summary>
/// <param name="scriptId">ID of the script to unload.</param>
[UnmanagedCallersOnly]
public static void UnloadScript(int scriptId)
{
try
{
if (!_loadedScripts.TryGetValue(scriptId, out var scriptInstance))
return;
scriptInstance.ScriptInterface?.End();
scriptInstance.CompilationResult.Unload();
_loadedScripts.Remove(scriptId);
}
catch
{
}
}
/// <summary>
/// Invokes a method on a loaded script.
/// </summary>
/// <param name="scriptId">ID of the script.</param>
/// <param name="methodName">Name of the method to invoke.</param>
/// <returns>1 on success, 0 on failure.</returns>
[UnmanagedCallersOnly]
public static byte InvokeScriptMethod(int scriptId, IntPtr methodName)
{
try
{
if (!_loadedScripts.TryGetValue(scriptId, out var scriptInstance))
return 0;
string? method = Marshal.PtrToStringUTF8(methodName);
if (string.IsNullOrEmpty(method))
return 0;
var type = scriptInstance.Instance.GetType();
var methodInfo = type.GetMethod(method);
if (methodInfo == null)
return 0;
methodInfo.Invoke(scriptInstance.Instance, null);
return 1;
}
catch
{
return 0;
}
}
/// <summary>
/// Sets a warning message in the engine's logging system.
/// </summary>
private static void PrintWarning(string message)
{
var warning = new Warning(message, 0, 1, IntPtr.Zero);
Warning.PrintWarning(ref warning);
}
private class ScriptInstance
{
public int Id { get; set; }
public object Instance { get; set; } = null!;
public CsCompiler.CompilationResult CompilationResult { get; set; } = null!;
public IScript? ScriptInterface { get; set; }
}
// Additional helper methods for managed code
/// <summary>
/// Compiles and loads a script from source code (for use from managed code).
/// </summary>
public static int LoadScriptFromSource(string source, string className)
{
var result = CsCompiler.Compile(source);
if (!result.Success)
{
throw new InvalidOperationException($"Compilation failed: {string.Join("\n", result.Errors)}");
}
var instance = result.CreateInstance(className);
if (instance == null)
{
result.Unload();
throw new InvalidOperationException("Failed to create script instance");
}
int scriptId = _nextScriptId++;
_loadedScripts[scriptId] = new ScriptInstance
{
Id = scriptId,
Instance = instance,
CompilationResult = result,
ScriptInterface = instance as IScript
};
_loadedScripts[scriptId].ScriptInterface?.Start();
return scriptId;
}
[UnmanagedCallersOnly]
public static byte CompileScript(IntPtr scriptPath, IntPtr className)
{
try
{
string? path = Marshal.PtrToStringUTF8(scriptPath);
string? classNameStr = Marshal.PtrToStringUTF8(className);
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(classNameStr))
{
PrintWarning("Invalid script path or class name");
return 0;
}
var result = CsCompiler.CompileFromFile(path);
if (!result.Success)
{
string errors = string.Join("\n", result.Errors);
PrintWarning($"Script compilation failed:\n{errors}");
result.Unload();
return 0;
}
// Try to create an instance
object? instance;
try
{
instance = result.CreateInstance(classNameStr);
}
catch (Exception ex)
{
PrintWarning($"Failed to create instance: {ex.Message}");
result.Unload();
return 0;
}
if (instance == null)
{
PrintWarning("Failed to create script instance");
result.Unload();
return 0;
}
result.Unload();
}
catch (Exception ex)
{
PrintWarning($"Exception in CompileScript: {ex.Message}");
return 0;
}
return 1;
}
/// <summary>
/// Gets the script instance by ID (for use from managed code).
/// </summary>
public static object? GetScriptInstance(int scriptId)
{
return _loadedScripts.TryGetValue(scriptId, out var instance) ? instance.Instance : null;
}
}