-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SCsub
395 lines (333 loc) · 15.1 KB
/
SCsub
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/env python
import os
import io
import time
import re
from typing import TypedDict
Import("env")
Import("env_modules")
class LibraryDetails:
def __init__(self, platform: str, arch: str, libname: str, delimiter: str):
self.platform = platform
self.arch = arch
self.libname = libname
self.delimiter = delimiter
def platform_base(self) -> str:
return self.platform + self.delimiter + self.arch + self.delimiter + "release"
class LibraryDescriptor:
def __init__(self, name: str, details: list[LibraryDetails]):
self.name = name
self.details = details
jsb_platform = "linux" if env["platform"] == "linuxbsd" else env["platform"]
jsb_arch = env["arch"]
prebuilt_deps_url = "https://github.com/ialex32x/GodotJS-Dependencies/releases/download/v8_r11/v8_r11.zip"
module_path = os.path.dirname(os.path.abspath("jsb.h"))
module_name = os.path.basename(module_path)
# godot 4.3.1 generates `ActiveProjectItemList_` variable name with the path name (see methods.py)
# it'll fail if the path contains '.' or any other characters invalid as variable name
# detect and rename them for better compatibility
v8_prebuilt_libs = LibraryDescriptor("v8", \
[
LibraryDetails("windows", "x86_64", "v8_monolith.lib", "_"),
LibraryDetails("linux", "x86_64", "libv8_monolith.a", "."),
LibraryDetails("macos", "x86_64", "libv8_monolith.a", "."),
LibraryDetails("macos", "arm64", "libv8_monolith.a", "."),
LibraryDetails("ios", "x86_64", "libv8_monolith.a", "."),
LibraryDetails("ios", "arm64", "libv8_monolith.a", "."),
LibraryDetails("ios", "arm32", "libv8_monolith.a", "."),
LibraryDetails("android", "x86_64", "libv8_monolith.a", "."),
LibraryDetails("android", "arm64", "libv8_monolith.a", "."),
LibraryDetails("android", "arm32", "libv8_monolith.a", "."),
])
lws_prebuilt_libs = LibraryDescriptor("lws", \
[
LibraryDetails("windows", "x86_64", "websockets.lib", "_"),
LibraryDetails("linux", "x86_64", "libwebsockets.a", "_"),
LibraryDetails("macos", "arm64", "libwebsockets.a", "_"),
])
class CompileDefines:
def __init__(self, name, value, help = None):
self.name = name
self.value = value
self.help = help
def get_library_support(support: LibraryDescriptor) -> tuple[LibraryDescriptor, LibraryDetails]:
for details in support.details:
if jsb_platform != details.platform or jsb_arch != details.arch:
continue
libpath = support.name + "/" \
+ details.platform_base() + "/" \
+ details.libname
if os.path.exists(libpath):
return (support, details)
return None
v8_support = get_library_support(v8_prebuilt_libs)
lws_support = get_library_support(lws_prebuilt_libs)
jsb_defines = [
CompileDefines("JSB_WITH_V8", 1 if v8_support is not None else 0),
CompileDefines("JSB_WITH_WEB", 1 if jsb_platform == "web" else 0),
CompileDefines("JSB_WITH_EDITOR_UTILITY_FUNCS", 1 if jsb_platform != "web" and env.editor_build else 0, [
"enables 'jsb.editor'",
]),
CompileDefines("JSB_WITH_DEBUGGER", 1 if v8_support is not None else 0, [
"enable to debug with Chrome devtools with the following link by default:",
"devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/1",
]),
CompileDefines("JSB_WITH_QUICKJS", 0),
CompileDefines("JSB_WITH_LWS", 1 if lws_support is not None else 0, [
"NOTE: currently use `libwebsockets` to handle v8 debugger connection since `modules/websocket` fail to handshake with `devtools`",
"`devtools` do not response the upgrading request with a `sec-websocket-protocol` header which does not apply the handshake requirements of `WSLPeer`",
"and the connection will break immediately by `devtools` if `selected_protocol` is assigned manually in `WSLPeer`",
]),
]
print("compiling:", module_name)
print("javascript engine:", "none" if v8_support is None else v8_support[0].name)
print("websocket lib:", "none" if lws_support is None else lws_support[0].name)
print("platform:", jsb_platform)
print("arch:", jsb_arch)
if jsb_platform == "android":
print("ndk_platform:", env["ndk_platform"])
print("ANDROID_NDK_ROOT:", env["ANDROID_NDK_ROOT"])
class PresetTransformer:
def transform(self, data: bytes):
return data
class PresetDefine:
def __init__(self, sourcename: str, targetname: str, transformer: PresetTransformer = None):
self.sourcename = sourcename
self.targetname = targetname
self.transformer = transformer
def read_source(self):
with open(self.sourcename, "rb") as input:
data = input.read()
return data if self.transformer is None else self.transformer.transform(data)
class AMDSourceTransformer(PresetTransformer):
def transform(self, data: bytes):
return b"(function(define){"+data+b"\n})"
def check(condition, text):
if not condition:
print("Error: " + text)
Exit(2)
def is_defined(name, value):
for t in jsb_defines:
if t.name == name:
return t.value == value
return False
def set_defined(name, value):
for t in jsb_defines:
if t.name == name:
t.value = value
check(False, f"can not set value to '{name}' which is not defined")
def remove_file(filename):
if os.path.exists(filename):
print(f"deleting deprecated file {filename}")
os.remove(filename)
# def write_file(filename, ostream: io.StringIO):
def write_file(filename, ostream):
ostream.seek(0)
content = ostream.read()
if os.path.exists(filename):
with open(filename, "rt", encoding="utf-8") as input:
if input.read() == content:
print(f"generate {filename}: no diff")
return
with open(filename, "wt", encoding="utf-8") as output:
print(f"generating {filename}")
output.write(content)
def generate_method_code(output, methodname, indent, preset_defines: list[PresetDefine]):
output.write(f"const char* GodotJSProjectPreset::{methodname}(const String& p_filename, size_t& r_len)\n")
output.write("{\n")
output.write(indent+"static const char data[] = {\n")
positions = {}
cursor = 0
for preset_define in preset_defines:
sourcename = preset_define.sourcename
targetname = preset_define.targetname
if len(targetname) == 0:
targetname = os.path.basename(sourcename)
targetstart = cursor
newline = 0
mtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(sourcename)))
bytes = preset_define.read_source()
length = len(bytes)
output.write(indent+indent+f"// target: {targetname} length: {length} modified: {mtime}\n")
output.write(indent+indent)
cursor += length
positions[targetname] = (targetstart, cursor - targetstart)
for byte in bytes:
output.write(f"0x{byte:02x}, ")
newline += 1
if newline >= 64:
newline = 0
output.write("\n")
output.write(indent+indent)
if newline != 0:
newline = 0
output.write("\n")
output.write("\n")
output.write(indent+"};\n")
for targetname in positions:
start = positions[targetname][0]
size = positions[targetname][1]
output.write(indent+f"if (p_filename == \"{targetname}\") {{ r_len = {size}; return data+{start}; }}\n")
output.write(indent+"r_len = 0;\n")
output.write(indent+"return nullptr;\n")
output.write("}\n")
def read_bundle_version():
with open("jsb.config.h", "rt", encoding="utf-8") as input:
regex = r"^#define\s+JSB_BUNDLE_VERSION\s+(\d+)$"
for line in input:
matches = re.finditer(regex, line)
for _, match in enumerate(matches, start=1):
return match.group(1)
raise ValueError("no JSB_BUNDLE_VERSION defined in jsb.config.h")
def generate_code(rt_preset_defines, ed_preset_defines):
indent = " "
output = io.StringIO()
# delete obsolete files
remove_file("weaver-editor/jsb_project_preset.cpp")
remove_file("jsb_project_preset.cpp")
outfile = "jsb_project_preset.gen.cpp"
# with open(outfile, "wt", encoding="utf-8") as output:
if True:
output.write("// AUTO-GENERATED\n")
output.write("\n")
output.write("#include \"jsb_project_preset.h\"\n")
output.write("#include \"jsb.config.h\"\n")
# js.bundle version checker
output.write(f"static_assert({read_bundle_version()} == JSB_BUNDLE_VERSION, \"obsolete preset data found, please regenerate project sources with scons\");\n")
# bundled source for runtime
generate_method_code(output, "get_source_rt", indent, rt_preset_defines)
# bundled source for editor
output.write("#ifdef TOOLS_ENABLED\n")
generate_method_code(output, "get_source_ed", indent, ed_preset_defines)
output.write("#endif\n")
write_file(outfile, output)
def generate_jsb_gen_header():
output = io.StringIO()
if True:
output.write("// AUTO-GENERATED\n")
output.write("#ifndef GODOTJS_GEN_H\n")
output.write("#define GODOTJS_GEN_H\n")
output.write("\n")
output.write(f"#define JSB_MODULE_NAME {module_name}\n")
output.write(f"#define jsb_initialize_module initialize_{module_name}_module\n")
output.write(f"#define jsb_uninitialize_module uninitialize_{module_name}_module\n")
output.write("\n")
first_define = True
for t in jsb_defines:
if t.help != None:
if not first_define:
output.write("\n")
if isinstance(t.help, str):
output.write(f"// {t.help}\n")
elif isinstance(t.help, list):
for line in t.help:
output.write(f"// {line}\n")
output.write(f"#define {t.name} {t.value}\n")
first_define = False
output.write("\n")
output.write("#endif\n")
write_file("jsb.gen.h", output)
def get_godot_version_info():
try:
# it's available since godot 4.3
return env.version_info
except:
# fallback to the tricky way
import os
import sys
# We want /methods.py.
engine_path = os.path.join(os.curdir, "../..")
sys.path.insert(0, engine_path)
from methods import get_version_info
version_info = get_version_info("")
sys.path.remove(engine_path)
return version_info
version_info = get_godot_version_info()
def check_godot_version_newer_than(major, minor, patch):
return version_info["major"] > major or (version_info["major"] == major and (version_info["minor"] > minor or (version_info["minor"] == minor and version_info["patch"] >= patch)))
env_jsb = env_modules.Clone()
module_obj = []
print(f"godot engine: {version_info['major']}.{version_info['minor']}")
if v8_support is not None:
# it seems godot always links MT_StaticRelease even if env["dev_build"]
# it seems v8_monolith must be compiled with `use_rtti=true` explicitly, or the linker will fail on `v8::ArrayBuffer::Allocator`
# check existence of v8 (since it's setup manually)
v8_missing_msg = f"The v8 engine is not found in GodotJS, please build it initially or download the prebuilt v8 library from {prebuilt_deps_url}"
v8_basename = v8_support[1].platform_base()
v8_lib_path = f"v8/{v8_basename}/{v8_support[1].libname}"
check(os.path.exists("v8/include/v8.h"), v8_missing_msg)
check(os.path.exists(v8_lib_path), v8_missing_msg)
if jsb_platform == "macos":
env.Append(LIBPATH=[f'#modules/{module_name}/v8/{v8_basename}'])
env.Append(LINKFLAGS=["-lv8_monolith"])
elif jsb_platform in ["linux", "windows", "android", "ios"]:
env.Append(LIBS=[File(v8_lib_path)])
else:
check(False, f'v8 is not supported on {env["platform"]}')
# platform-specific defines
if jsb_platform == "windows":
env.Append(LINKFLAGS=["winmm.lib", "Dbghelp.lib"])
if jsb_platform not in ["ios", "android"]:
env_jsb.AppendUnique(CPPDEFINES=["V8_COMPRESS_POINTERS"])
pass
# env_jsb.AppendUnique(CPPDEFINES=["V8_ENABLE_TURBOFAN"])
env_jsb.Append(CPPDEFINES=["_ITERATOR_DEBUG_LEVEL=0"])
# headers
# env_jsb is enough for compiler, but IDE lookup paths from `env`
if env.msvc and env["vsproj"]:
env.Append(CPPPATH=[f"#modules/{module_name}/v8/include"])
env_jsb.Append(CPPPATH=["v8/include"])
env_jsb.add_source_files(module_obj, "impl/v8/*.cpp")
# lws
if lws_support is not None:
lws_missing_msg = "The prebuilt lws lib is missing? Please build it at first."
lws_basename = lws_support[1].platform_base()
lws_lib_path = f"lws/{lws_basename}/{lws_support[1].libname}"
check(os.path.exists(lws_lib_path), lws_missing_msg)
if jsb_platform == "macos":
env_jsb.Append(CPPPATH=[f"lws/{lws_basename}/include"])
env.Append(LIBPATH=[f'#modules/{module_name}/lws/{lws_basename}'])
env.Append(LINKFLAGS=["-lwebsockets"])
elif jsb_platform in ["linux", "windows"]:
env_jsb.Append(CPPPATH=[f"lws/{lws_basename}/include"])
env.Append(LIBS=[File(lws_lib_path)])
else:
check(False, f'lws is not supported on {env["platform"]}')
# platform-specific defines
if env.msvc and env["vsproj"]:
env.Append(CPPPATH=[f"#modules/{module_name}/lws/{lws_basename}/include"])
if is_defined("JSB_WITH_QUICKJS", 1):
print("WARNING: quickjs support has not been implemented yet")
# quickjs is directly built from source
env_jsb.add_source_files(module_obj, "quickjs/*.c")
env_jsb.add_source_files(module_obj, "impl/quickjs/*.cpp")
if jsb_platform == "web":
print("WARNING: web support has not been implemented yet")
env_jsb.add_source_files(module_obj, "impl/web/*.cpp")
env.AddJSLibraries([
"impl/web/jsb_web.library.js",
])
generate_code([\
# presets for runtime
PresetDefine("scripts/jsb.bundle/out/jsb.bundle.js", "", AMDSourceTransformer()),
], [\
# presets for editor only
PresetDefine("scripts/jsb.bundle/typings/godot.minimal.d.ts", ""),
PresetDefine("scripts/jsb.bundle/typings/godot.mix.d.ts", ""),
PresetDefine("scripts/jsb.bundle/out/jsb.bundle.d.ts", ""),
PresetDefine("scripts/jsb.bundle/out/jsb.bundle.js.map", ""),
PresetDefine("scripts/presets/package.json.txt", "package.json"),
PresetDefine("scripts/presets/tsconfig.json.txt", "tsconfig.json"),
PresetDefine("scripts/presets/gdignore.txt", ".gdignore"),
])
# common parts
env_jsb.add_source_files(module_obj, ["register_types.cpp", "jsb_project_preset.gen.cpp"])
env_jsb.add_source_files(module_obj, "internal/*.cpp")
env_jsb.add_source_files(module_obj, "weaver/*.cpp")
env_jsb.add_source_files(module_obj, "bridge/*.cpp")
# editor functionalities
if env.editor_build:
env_jsb.add_source_files(module_obj, "weaver-editor/*.cpp")
SConscript("weaver-editor/templates/SCsub")
generate_jsb_gen_header()
env.modules_sources += module_obj