Repository navigation
Expand file tree
/
Copy pathUnrealEnginePython.cpp
More file actions
377 lines (313 loc) · 11 KB
/
Copy pathUnrealEnginePython.cpp
File metadata and controls
377 lines (313 loc) · 11 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UnrealEnginePythonPrivatePCH.h"
void unreal_engine_init_py_module();
#if defined(UNREAL_ENGINE_PYTHON_ON_LINUX)
const char *ue4_module_options = "linux_global_symbols";
#endif
#if PY_MAJOR_VERSION < 3
char *PyUnicode_AsUTF8(PyObject *py_str) {
if (PyUnicode_Check(py_str)) {
PyObject *unicode = PyUnicode_AsUTF8String(py_str);
if (unicode) {
return PyString_AsString(unicode);
}
// just a hack to avoid crashes
return (char *)"<invalid_string>";
}
return PyString_AsString(py_str);
}
int PyGILState_Check() {
PyThreadState * tstate = _PyThreadState_Current;
return tstate && (tstate == PyGILState_GetThisThreadState());
}
#endif
bool PyUnicodeOrString_Check(PyObject *py_obj) {
if (PyUnicode_Check(py_obj)) {
return true;
}
#if PY_MAJOR_VERSION < 3
else if (PyString_Check(py_obj)) {
return true;
}
#endif
return false;
}
#define LOCTEXT_NAMESPACE "FUnrealEnginePythonModule"
void FUnrealEnginePythonModule::PythonGILRelease() {
#if defined(UEPY_THREADING)
if (PyGILState_Check() == 1) {
ue_python_gil = PyEval_SaveThread();
}
#endif
}
bool FUnrealEnginePythonModule::PythonGILAcquire() {
#if defined(UEPY_THREADING)
if (PyGILState_Check() == 0) {
PyEval_RestoreThread((PyThreadState *)ue_python_gil);
return true;
}
return false;
#endif
return true;
}
static void UESetupPythonInterpeter(bool verbose) {
unreal_engine_init_py_module();
PyObject *py_sys = PyImport_ImportModule("sys");
PyObject *py_sys_dict = PyModule_GetDict(py_sys);
PyObject *py_path = PyDict_GetItemString(py_sys_dict, "path");
char *zip_path = TCHAR_TO_UTF8(*FPaths::ConvertRelativePathToFull(FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("ue_python.zip"))));
PyObject *py_zip_path = PyUnicode_FromString(zip_path);
PyList_Insert(py_path, 0, py_zip_path);
char *scripts_path = TCHAR_TO_UTF8(*FPaths::ConvertRelativePathToFull(FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"))));
PyObject *py_scripts_path = PyUnicode_FromString(scripts_path);
PyList_Insert(py_path, 0, py_scripts_path);
/* UnrealEnginePython Plugin Content/Scripts path */
FString PluginRoot = IPluginManager::Get().FindPlugin("UnrealEnginePython")->GetBaseDir();
FString ScriptsPath = FPaths::ConvertRelativePathToFull(FPaths::Combine(PluginRoot, "Content/Scripts"));
PyObject *py_plugin_scripts_path = PyUnicode_FromString(TCHAR_TO_UTF8(*ScriptsPath));
PyList_Insert(py_path, 0, py_plugin_scripts_path);
/* add the plugin paths - windows only */
FString PythonHome = FPaths::ConvertRelativePathToFull(FPaths::Combine(*FPaths::GamePluginsDir(), "UnrealEnginePython/Binaries/Win64"));
char *python_path = TCHAR_TO_UTF8(*PythonHome);
char *site_path = TCHAR_TO_UTF8(*FPaths::Combine(*PythonHome, "Lib/site-packages"));
PyList_Insert(py_path, 0, PyUnicode_FromString(python_path));
PyList_Insert(py_path, 0, PyUnicode_FromString(site_path));
if (verbose) {
UE_LOG(LogPython, Log, TEXT("Python VM initialized: %s"), UTF8_TO_TCHAR(Py_GetVersion()));
UE_LOG(LogPython, Log, TEXT("Python Scripts search path: %s"), UTF8_TO_TCHAR(scripts_path));
}
}
void FUnrealEnginePythonModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
FString PyHome;
if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("Home"), PyHome, GEngineIni)) {
#if PY_MAJOR_VERSION >= 3
wchar_t *home = (wchar_t *)*PyHome;
#else
char *home = TCHAR_TO_UTF8(*PyHome);
#endif
Py_SetPythonHome(home);
}
Py_Initialize();
#if PY_MAJOR_VERSION >= 3
wchar_t *argv[] = { UTF8_TO_TCHAR("UnrealEngine"), NULL };
#else
char *argv[] = { (char *)"UnrealEngine", NULL };
#endif
PySys_SetArgv(1, argv);
PyEval_InitThreads();
UESetupPythonInterpeter(true);
main_module = PyImport_AddModule("__main__");
main_dict = PyModule_GetDict((PyObject*)main_module);
local_dict = main_dict;// PyDict_New();
// Redirecting stdout
char const* code = "import sys\n"
"import unreal_engine as ue\n"
"class UnrealEngineOutput:\n"
" def __init__(self, logger):\n"
" self.logger = logger\n"
" def write(self, buf):\n"
" self.logger(buf)\n"
" def flush(self):\n"
" return\n"
"sys.stdout = UnrealEngineOutput(ue.log)\n"
"sys.stderr = UnrealEngineOutput(ue.log_error)\n";
PyRun_SimpleString(code);
//import upymodule_importer
PyImport_ImportModule("upymodule_importer");
if (PyImport_ImportModule("ue_site")) {
UE_LOG(LogPython, Log, TEXT("ue_site Python module successfully imported"));
}
else {
// TODO gracefully manage the error
unreal_engine_py_log_error();
}
#if WITH_EDITOR
// register commands (after importing ue_site)
FPythonSlateCommands::Register();
// apply extenders
FPythonSlateCommands::ApplyPythonExtenders();
#endif
// release the GIL
PythonGILRelease();
}
void FUnrealEnginePythonModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
UE_LOG(LogPython, Log, TEXT("Goodbye Python"));
PythonGILAcquire();
Py_Finalize();
}
void FUnrealEnginePythonModule::RunString(char *str) {
FScopePythonGIL gil;
PyObject *eval_ret = PyRun_String(str, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
Py_DECREF(eval_ret);
}
// run a python string in a new sub interpreter
void FUnrealEnginePythonModule::RunStringSandboxed(char *str) {
FScopePythonGIL gil;
PyThreadState *_main = PyThreadState_Get();
PyThreadState *py_new_state = Py_NewInterpreter();
if (!py_new_state) {
UE_LOG(LogPython, Error, TEXT("Unable to create new Python interpreter"));
return;
}
PyThreadState_Swap(nullptr);
PyThreadState_Swap(py_new_state);
UESetupPythonInterpeter(false);
PyObject *m = PyImport_AddModule("__main__");
if (m == NULL) {
UE_LOG(LogPython, Error, TEXT("Unable to create new global dict"));
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
PyObject *global_dict = PyModule_GetDict(m);
PyObject *eval_ret = PyRun_String(str, Py_file_input, global_dict, global_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
}
void FUnrealEnginePythonModule::RunFile(char *filename) {
FScopePythonGIL gil;
char *full_path = filename;
if (!FPaths::FileExists(filename))
{
full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
}
#if PY_MAJOR_VERSION >= 3
FILE *fd = nullptr;
#if PLATFORM_WINDOWS
if (fopen_s(&fd, full_path, "r") != 0) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#else
fd = fopen(full_path, "r");
if (!fd) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#endif
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
fclose(fd);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
Py_DECREF(eval_ret);
#else
// damn, this is horrible, but it is the only way i found to avoid the CRT error :(
FString command = FString::Printf(TEXT("execfile(\"%s\")"), UTF8_TO_TCHAR(full_path));
PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
#endif
}
// run a python script in a new sub interpreter (useful for unit tests)
void FUnrealEnginePythonModule::RunFileSandboxed(char *filename) {
FScopePythonGIL gil;
char *full_path = filename;
if (!FPaths::FileExists(filename))
{
full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
}
PyThreadState *_main = PyThreadState_Get();
PyThreadState *py_new_state = Py_NewInterpreter();
if (!py_new_state) {
UE_LOG(LogPython, Error, TEXT("Unable to create new Python interpreter"));
return;
}
PyThreadState_Swap(nullptr);
PyThreadState_Swap(py_new_state);
UESetupPythonInterpeter(false);
PyObject *m = PyImport_AddModule("__main__");
if (m == NULL) {
UE_LOG(LogPython, Error, TEXT("Unable to create new global dict"));
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
PyObject *global_dict = PyModule_GetDict(m);
#if PY_MAJOR_VERSION >= 3
FILE *fd = nullptr;
#if PLATFORM_WINDOWS
if (fopen_s(&fd, full_path, "r") != 0) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#else
fd = fopen(full_path, "r");
if (!fd) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#endif
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, global_dict, global_dict);
fclose(fd);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
Py_DECREF(eval_ret);
#else
// damn, this is horrible, but it is the only way i found to avoid the CRT error :(
FString command = FString::Printf(TEXT("execfile(\"%s\")"), UTF8_TO_TCHAR(full_path));
PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, global_dict, global_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
#endif
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
}
void FUnrealEnginePythonModule::AddPathToSysPath(const FString& Path)
{
PythonGILAcquire();
PyObject *py_sys = PyImport_ImportModule("sys");
PyObject *py_sys_dict = PyModule_GetDict(py_sys);
PyObject *py_path = PyDict_GetItemString(py_sys_dict, "path");
char *charPath = TCHAR_TO_UTF8(*Path);
PyObject *py_scripts_path = PyUnicode_FromString(charPath);
PyList_Insert(py_path, 0, py_scripts_path);
PythonGILRelease();
}
void FUnrealEnginePythonModule::AddPythonDependentPlugin(const FString& PluginName)
{
//Add plugin Content/Script to sys.path
FString PluginRoot = IPluginManager::Get().FindPlugin(PluginName)->GetBaseDir();
FString ScriptsPath = FPaths::ConvertRelativePathToFull(FPaths::Combine(PluginRoot, "Content/Scripts"));
FUnrealEnginePythonModule::Get().AddPathToSysPath(ScriptsPath);
UE_LOG(LogPython, Log, TEXT("Added %s Plugin Content/Scripts (%s) to sys.path"), *PluginName, *ScriptsPath);
//run import interpreter on upythonmodule.json inside scripts
FString PyModulePath = FString::Printf(TEXT("%s/upymodule.json"), *ScriptsPath);
FString RunImport = FString::Printf(TEXT("import upymodule_importer\nupymodule_importer.parseJson('%s')"), *PyModulePath);
PythonGILAcquire();
if (PyRun_SimpleString(TCHAR_TO_UTF8(*RunImport)) == 0) {
UE_LOG(LogPython, Log, TEXT("%s Plugin upymodule.json parsed"), *PluginName);
}
else {
unreal_engine_py_log_error();
}
PythonGILRelease();
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FUnrealEnginePythonModule, UnrealEnginePython)