This repository has been archived by the owner on Feb 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
tasks.nim
808 lines (657 loc) · 26.4 KB
/
tasks.nim
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# nim says anycase is unused, but pascal and snake are from anycase
{.push warning[UnusedImport]: off.}
from sequtils import toSeq, filter, mapIt
import anycase, threadpool
const script_nim_template = """
import gdnim, godotapi / [$1]
gdnim $2 of $3:
#first: # runs when instanced, ignored on reload
#dependencies: # specify names of components referenced by this component
unload:
save()
reload: # definition required for hot reloading, inserted at top of method enter_tree
load()
"""
const tool_nim_template = """
import godot, godotapi / [editor_plugin, resource_loader]
#[
WARNING: GDNative reloading of tool scripts is broken.
If you enable and disable the plugin, or unfocus the editor window while
the plugin is enabled which will cause the plugin to reload, you might
get a crash. You also might get warnings about leaked resources, when the
plugin is enabled while the editor is closed.
As a workaround, gdnlib's reloadable flag is set to false, so the
plugin will not reload when the editor is unfocused. To see your
changes, close the editor and reopen after compilation.
]#
gdobj($2 of EditorPlugin, tool):
method enter_tree() =
discard
method exit_tree() =
discard
"""
const lib_nim_template = """
# import modules for $1
"""
const lib_cfg_template = """
# cfg for $1
--path:"../$2"
"""
const gdns_template = """
[gd_resource type="NativeScript" load_steps=2 format=2]
[ext_resource path="res://$3/$1.gdnlib" type="GDNativeLibrary" id=1]
[resource]
resource_name = "$2"
class_name = "$2"
library = ExtResource( 1 )
"""
const gdnlib_template = """
[general]
singleton=false
load_once=true
symbol_prefix="godot_"
reloadable=$4
[entry]
Android.arm64-v8a="res://$3/lib$1.so"
Android.armeabi="res://$3/lib$1.so"
Android.armeabi-v7a="res://$3/lib$1.so"
Android.x86="res://$3/lib$1.so"
Android.x86_64="res://$3/lib$1.so"
Windows.64 = "res://$3/$1.dll"
X11.64 = "res://$3/lib$1.so"
OSX.64 = "res://$3/$1.dylib"
[dependencies]
Android.arm64-v8a=[ ]
Android.armeabi=[ ]
Android.armeabi-v7a=[ ]
Android.x86=[ ]
Android.x86_64=[ ]
Windows.64=[ ]
X11.64=[ ]
OSX.64=[ ]
"""
const tscn_template = """
[gd_scene load_steps=2 format=2]
[ext_resource path="res://$3/$1.gdns" type="Script" id=1]
[node name="$2" type="$4"]
script = ExtResource( 1 )
"""
const plugin_cfg_template = """
[plugin]
name="$1"
description=""
author=""
version=""
script="$1.gdns"
"""
let appDir = config.getSectionValue("Dir", "app")
let compsDir = config.getSectionValue("Dir", "comps")
let compsSrcDir = config.getSectionValue("Dir", "comps_src")
let depsDir = config.getSectionValue("Dir", "deps")
let depsGodotDir = config.getSectionValue("Dir", "deps_godot")
let gdpathFlags = &"--path:gdnim --path:{depsDir} --path:{depsDir}/{depsGodotDir} "
# generated files
let baseDllDir = config.getSectionValue("App", "dll")
let dllDir = appDir / baseDllDir
let gdnsDir = appDir / config.getSectionValue("App", "gdns")
let gdnlibDir = appDir / config.getSectionValue("App", "gdnlib")
let baseTscnDir = config.getSectionValue("App", "tscn")
let tscnDir = appDir / baseTscnDir
let gd_scons_flags = config.getSectionValue("Godot", "scons_flags")
let gd_src = expandTilde(config.getSectionValue("Godot", "src"))
let gd_base_branch = config.getSectionValue("Godot", "base_branch")
let gd_build_branch = config.getSectionValue("Godot", "build_branch")
let gd_branches = config.getSectionValue("Godot", "merge_branches").split(",")
let gd_platform = config.getSectionValue("Godot", "platform")
case gd_platform:
of "windows", "android", "linuxbsd", "x11", "macosx": discard
else: quit(&"Invalid build.ini: platform =\"{gd_platform}\"", QuitFailure)
#let gd_arch = config.getSectionValue("Godot", "arch")
let gd_bits = config.getSectionValue("Godot", "bits")
let gd_tools_debug_bin = expandTilde(config.getSectionValue("Godot", "tools_debug_bin"))
let gd_tools_release_bin = expandTilde(config.getSectionValue("Godot", "tools_release_bin"))
var cwatch_interval = parseInt(config.getSectionValue("Build", "cwatch_interval"))
if cwatch_interval == 0: cwatch_interval = 300
let dllPrefix = case gd_platform
of "android", "linuxbsd", "x11": "lib"
else: ""
let dllExt = case gd_platform
of "windows": "dll"
of "android", "linuxbsd", "x11": "so"
of "macosx": "dylib"
else: "unknown platform"
var compilerDefines = &"{gdpathFlags}" &
&" --define:baseDllDir:{baseDllDir} --define:dllPrefix:{dllPrefix} " &
&" --define:dllExt:{dllExt} --define:baseTscnDir:{baseTscnDir} " &
&" --define:compsDir:{compsDir} --define:depsDir:{depsDir} "
let does_reload = config.getSectionValue("Hot", "reload") == "on"
if does_reload:
compilerDefines &= &" --define:does_reload:true "
if config.getSectionValue("Hot", "verbose_nil_check") == "on":
compilerDefines &= &" --define:verbose_nil_check:true "
proc genGdns(name: string, isTool: bool = false) =
var comp = &"{compsDir}/{name}.nim"
var gdns = &"{gdnsDir}/{name}.gdns"
var gdnlib = &"{gdnlibDir}/{name}.gdnlib"
if not fileExists(comp):
# might be a tool or watcher
comp = &"{compsDir}/tools/{name}.nim"
if fileExists(comp):
gdns = &"{appDir}/addons/{name}/{name}.gdns"
gdnlib = &"{appDir}/addons/{name}/{name}.gdnlib"
else:
comp = &"gdnim/watcher.nim"
gdns = &"{gdnsDir}/watcher.gdns"
gdnlib = &"{gdnlibDir}/watcher.gdnlib"
if fileExists(comp):
if not fileExists(gdns):
var f = open(gdns, fmWrite)
f.write(gdns_template % [name, name.pascal, relativePath(parentDir(gdnlib), appDir)])
f.close()
echo &"generated {gdns}"
if not fileExists(gdnlib):
var f = open(gdnlib, fmWrite)
var reloadable = not isTool
f.write(gdnlib_template % [name, name.pascal, relativePath(dllDir, appDir), $reloadable])
f.close()
echo &"generated {gdnlib}"
else:
echo &"genGdns could not find {comp}"
quit(QuitFailure)
proc execOrQuit(command: string) =
if execShellCmd(command) != 0: quit(QuitFailure)
task gdengine_update, "update the 3.x custom branch with changes from upstream":
var projDir = getCurrentDir()
setCurrentDir(gd_src)
if not ("keeplocal" in args):
execOrQuit(&"git checkout {gd_base_branch}")
execOrQuit("git pull")
for branch in gd_branches:
execOrQuit(&"git checkout {branch}")
execOrQuit(&"git rebase {gd_base_branch}")
execOrQuit(&"git checkout {gd_base_branch}")
discard execShellCmd(&"git branch -D {gd_build_branch}")
execOrQuit(&"git checkout -b {gd_build_branch} {gd_base_branch}")
for branch in gd_branches:
execOrQuit(&"git merge {branch}")
if "push" in args:
execOrQuit(&"git push --force origin {gd_build_branch}")
setCurrentDir(projDir)
task gdengine, "build the godot engine, default does release build with tools. args:\n\tupdate: updates the branch with branches in gdengine_upstream task\n\tclean: clean build\n\texport: export build without tools\n\tdebug: generates debug build":
if "update" in args: gdengineUpdateTask()
# run scons --help to see godot flags
var flags = ""
var info = ""
if "export" in args:
info &= "export, "
if "debug" in args:
flags = "tools=no target=debug"
info &= "debug"
else:
flags = "tools=no target=release production=yes"
info &= "release"
else:
info &= "tools, "
if "debug" in args:
flags = "target=debug debug_symbols=yes"
info &= "debug"
else:
flags = "target=release_debug production=yes"
info &= "release"
flags &= &" {gd_scons_flags}"
var projDir = getCurrentDir()
setCurrentDir(gd_src)
discard execShellCmd &"git checkout {gd_build_branch}"
if "clean" in args:
echo "Cleaning godot engine"
discard execShellCmd "git clean -fdx" # clean generated files
discard execShellCmd &"scons -c {flags}"
var threads = countProcessors()
echo &"Compiling godot {info} scons -j{threads} p={gd_platform} bits={gd_bits} {flags}"
discard execShellCmd &"scons -j{threads} p={gd_platform} bits={gd_bits} {flags}"
setCurrentDir(projDir)
task term, "launches the terminal with cwatch, pass in another arg for second panel":
if hostOS == "windows":
var curDir = getCurrentDir()
var second = ""
if args.len == 1:
second = &"cmd /k \".\\build.exe {args[0]}\""
discard execShellCmd &"wt -d {curDir} ./build cwatch; split-pane -d {curDir} {second}"
else:
echo &"not implemented on {hostOS}"
task gd, "launches terminal with godot project\n\toptional argument 'debug' to launch debug godot editor":
var gdbin = if "debug" in args: gd_tools_debug_bin else: gd_tools_release_bin
echo &"{gdbin} --verbose -e --path {appDir}"
discard execShellCmd &"{gdbin} --verbose -e --path {appDir}"
task play, "launches the project without editor\n\toptional argument 'debug' to launch debug godot editor":
var gdbin = if "debug" in args: gd_tools_debug_bin else: gd_tools_release_bin
var projDir = "app"
echo &"{gdbin} --verbose --path {projDir}"
discard execShellCmd &"{gdbin} --verbose --path {projDir}"
proc checkPrereq(packageName, sourceName: string, verbose: bool = true) =
var (output, exitCode) = execCmdEx(&"nimble path {packageName}")
if exitCode != 0:
echo &"{packageName} is not installed. Installing."
execOrQuit(&"nimble install {sourceName}")
else:
if verbose:
echo &"{packageName} installed @ {output}"
task genapi, "generate the godot api bindings":
execOrQuit(&"nim c -r {gdpathFlags} {depsDir}/genapi.nim --ini:{buildini}")
var ext = if hostOS == "windows": ".exe" else: ""
removeFile(&"{depsDir}/genapi{ext}")
task prereqs, "Install prerequisites, and calls genapi task":
let packages = @[
("nim", "nim"),
("msgpack4nim", "https://github.com/jangko/msgpack4nim@#master"),
("optionsutils", "https://github.com/PMunch/nim-optionsutils")
]
for (packageName, sourceName) in packages:
checkPrereq(packageName, sourceName)
#genapiTask()
proc buildWatcher(): string =
{.cast(gcsafe).}:
var flags = getSharedFlags()
let dllPath = &"{dllDir}/{dllPrefix}watcher.{dllExt}"
let watcherPath = "gdnim/watcher.nim"
if ("force" in flags) or not fileExists(&"{dllPath}") or (getLastModificationTime(watcherPath) > getLastModificationTime(&"{dllPath}")):
result = execnim(compilerDefines, flags, &"{dllPath}", watcherPath)
else:
result = "Watcher is unchanged"
task watcher, "build the watcher dll":
genGdns("watcher")
echo buildWatcher()
# compiling with gcc, vcc spitting out warnings about incompatible pointer types with NimGodotObj, which was added for gc:arc
# include to include libgcc_s_seh-1.dll, libwinpthread-1.dll in the app/_dlls folder for project to run
const gccDlls = @["libgcc_s_seh-1", "libwinpthread-1"]
final:
if hostOS == "windows":
if taskCompilerFlagsTable["cc"] == allCompilerFlagsTable["gcc"]:
var copyFromDeps = false
var msg = ""
for dll in gccDlls:
if not fileExists(&"{dllDir}/{dll}.dll"):
createDir dllDir
copyFromDeps = true
msg &= &"\tCopying from {depsDir}\\gcc\\windows\\{dll}.dll to {dllDir}\\{dll}.dll\n"
copyFile(&"{depsDir}/gcc/windows/{dll}.dll", &"{dllDir}/{dll}.dll")
if copyFromDeps:
echo ">>> gcc dlls check <<<"
echo msg
echo "If the app fails to run with the dll(s), try copying from your gcc/bin directory"
task cleandll, "clean the dlls, arguments are component names, default all non-gcc dlls":
var dllPaths: seq[string]
if args.len > 1:
var seqDllPaths = args.mapIt(toSeq(walkFiles(&"{dllDir}/{it}*.*")))
for paths in seqDllPaths:
dllPaths &= paths
else:
dllPaths = toSeq(walkFiles(&"{dllDir}/*.*"))
dllPaths = dllPaths.filterIt(splitFile(it)[1] notin gccDlls)
for dllPath in dllPaths:
echo &"rm {dllPath}"
removeFile dllPath
proc getBuildSettings(): BuildSettings =
result.sharedFlags = getSharedFlags()
var settingsTable: Table[string, bool]
settingsTable["move"] = "move" in otherFlagsTable
settingsTable["newOnly"] = "force" notin result.sharedFlags
settingsTable["noCheck"] = "nocheck" in otherFlagsTable
result.settingsTable = settingsTable
proc safeDllFilePath(compName: string): string =
&"{dllDir}/{dllPrefix}{compName}_safe.{dllExt}"
proc hotDllFilePath(compName: string): string =
&"{dllDir}/{dllPrefix}{compName}.{dllExt}"
proc nimFilePath(compName: string): string =
var nimFilePath = &"{compsDir}/{compName}.nim"
if not fileExists(nimFilePath):
nimFilePath = &"{compsDir}/tools/{compName}.nim"
nimFilePath
proc gdnsFilePath(compName: string): string =
&"{gdnsDir}/{compName}.gdns"
proc gdnlibFilePath(compName: string): string =
&"{gdnlibDir}/{compName}.gdnlib"
proc tscnFilePath(compName: string): string =
&"{tscnDir}/{compName}.tscn"
proc shouldBuild(compName: string, buildSettings: BuildSettings): bool =
let safe = safeDllFilePath(compName)
let hot = hotDllFilePath(compName)
let nim = nimFilePath(compName)
result = buildSettings.settingsTable["noCheck"] or
(not buildSettings.settingsTable["newOnly"]) or
(buildSettings.settingsTable["newOnly"] and (
(not fileExists(hot) and not fileExists(safe)) or
(fileExists(safe) and getLastModificationTime(nim) > getLastModificationTime(safe)) or
(fileExists(hot) and not fileExists(safe) and getLastModificationTime(nim) > getLastModificationTime(hot)) or
(fileExists(safe) and buildSettings.settingsTable["move"])
))
proc buildComp(compName: string, buildSettings: BuildSettings): string =
{.cast(gcsafe).}:
let safe = safeDllFilePath(compName)
let hot = hotDllFilePath(compName)
let nim = nimFilePath(compName)
if not fileExists(nim):
result &= &"Error: '{compName}' not found in components or components/tools"
return
genGdns(compName)
if shouldBuild(compName, buildSettings):
result &= &">>> Build {compName} <<<\n"
result &= execnim(&"{compilerDefines} --skipParentCfg:on --path:.", buildSettings.sharedFlags, &"{safe}", &"{nim}")
if fileExists(safe) and getLastModificationTime(nim) < getLastModificationTime(safe) and
(not fileExists(hot) or buildSettings.settingsTable["move"]) or (fileExists(safe) and not does_reload):
moveFile(safe, hot)
result &= ">>> dll moved safe to hot <<<"
proc buildAllComps(res: var seq[FlowVar[string]], buildSettings: BuildSettings): int =
var count = 0
echo "building components: "
for compPath in walkFiles(&"{compsDir}/*.nim"):
inc count
var compName = splitFile(compPath)[1].snake
if shouldBuild(compName, buildSettings):
echo " " & compName
res.add(spawn buildComp(compName, buildSettings))
for compPath in walkFiles(&"{compsDir}/tools/*.nim"):
inc count
var compName = splitFile(compPath)[1].snake
if shouldBuild(compName, buildSettings):
echo " " & compName
res.add(spawn buildComp(compName, buildSettings))
count
task gencomp, "generate a component template (nim, gdns, gdnlib, tscn files), pass in the component name and base class name in snake case\n\tUsage: ./build gencomp [notscn] comp_name base_node":
var compName: string
var baseClassModuleName: string
case args.len:
of 2:
compName = args[0]
baseClassModuleName = args[1].tolower
of 3:
compName = args[1]
baseClassModuleName = args[2].tolower
else:
echo "Usage: ./build gencomp [notscn] comp_name base_node"
echo "Example: ./build gencomp player kinematic_body_2d"
echo "Example without tscn: ./build gencomp notscn effect animated_sprite"
quit()
var compClassName = compName.pascal
var baseClassName = baseClassModuleName.pascal
if baseClassName[^2].isDigit and baseClassName.endsWith("d"):
baseClassName[^1] = 'D'
baseClassModuleName = case baseClassModuleName:
of "object": "objects"
else: baseClassModuleName
var classFilename = &"{depsDir}/godotapi/{baseClassModuleName}.nim"
if not fileExists(classFilename):
echo &"Error generating component. Could not find {classFilename}!"
quit()
let nim = &"{compsDir}/{compName}.nim"
if not fileExists(nim):
var f = open(nim, fmWrite)
f.write(script_nim_template % [baseClassModuleName, compClassName, baseClassName])
f.close()
echo &"generated {nim}"
else:
echo &"{nim} already exists"
if "notscn" notin args[0]:
let tscn = &"{tscnDir}/{compName}.tscn"
if not fileExists(tscn):
var f = open(tscn, fmWrite)
f.write(tscn_template % [compName, compClassName, relativePath(gdnsDir, appDir), baseClassName])
f.close()
echo &"generated {tscn}"
else:
echo &"{tscn} already exists"
genGdns(compName)
var buildSettings = getBuildSettings()
echo &"building {compName}"
echo buildComp(compName, buildSettings)
task genlib, "Generates a library, .nim, .nim.cfg and .gdnlib files. Use with genclass so multiple classes share one gdnlib. For godot-nim style projects with limited hot reloading.":
if args.len != 1:
echo "Usage: ./build genlib gdnlib_name"
quit()
var compName = args[0]
let nim = &"{compsDir}/{compName}.nim"
var gdnlib = &"{gdnlibDir}/{compName}.gdnlib"
if not fileExists(nim):
var f = open(nim, fmWrite)
f.write(lib_nim_template % [compName])
f.close()
echo &"generated {nim}"
else:
echo &"{nim} already exists"
var cfg = &"{compsDir}/{compName}.nim.cfg"
if not fileExists(cfg):
var f = open(cfg, fmWrite)
f.write(lib_cfg_template % [compName, compsSrcDir])
f.close()
echo &"generated {cfg}"
else:
echo &"{cfg} already exists"
if not fileExists(gdnlib):
var f = open(gdnlib, fmWrite)
f.write(gdnlib_template % [compName, compName.pascal, relativePath(dllDir, appDir), $true])
f.close()
echo &"generated {gdnlib}"
else:
echo &"{gdnlib} already exists"
task genclass, "Used with task genlib: Generates a nim and gdns that points to a gdnlib, optionally takes a relative dir inside comps_src to save the file":
var compName: string
var baseClassModuleName: string
var gdnlibName: string
var path: string
case args.len:
of 3:
compName = args[0]
baseClassModuleName = args[1].tolower
gdnlibName = args[2].tolower
of 4:
compName = args[0]
baseClassModuleName = args[1].tolower
gdnlibName = args[2].tolower
path = args[3]
else:
echo "Usage: ./build genclass comp_name base_node gdnlib [comps_src_path]"
echo "Example: ./build genclass player sprite main"
echo "Example: ./build genclass player sprite main player/stuff"
quit()
var compClassName = compName.pascal
var baseClassName = baseClassModuleName.pascal
if baseClassName[^2].isDigit and baseClassName.endsWith("d"):
baseClassName[^1] = 'D'
baseClassModuleName = case baseClassModuleName:
of "object": "objects"
else: baseClassModuleName
var classFilename = &"{depsDir}/godotapi/{baseClassModuleName}.nim"
if not fileExists(classFilename):
echo &"Error generating component. Could not find {classFilename}!"
quit()
let nimDir = &"{compsSrcDir}/" & (if path.len > 0: &"{path}/" else: "")
let nim = nimDir & &"{compName}.nim"
createDir(nimDir)
if not fileExists(nim):
var f = open(nim, fmWrite)
f.write(script_nim_template % [baseClassModuleName, compClassName, baseClassName])
f.close()
echo &"generated {nim}"
else:
echo &"{nim} already exists"
var gdnsDir = &"{gdnsDir}/" & (if path.len > 0: &"{path}/" else: "")
createDir(gdnsDir)
var gdns = gdnsDir & &"{compName}.gdns"
var gdnlib = &"{gdnlibDir}/{gdnlibName}.gdnlib"
if not fileExists(gdns):
var f = open(gdns, fmWrite)
f.write(gdns_template % [gdnlibName, compName.pascal, relativePath(parentDir(gdnlib), appDir)])
f.close()
echo &"generated {gdns}"
var buildSettings = getBuildSettings()
echo &"building {compName}"
echo buildComp(gdnlibName, buildSettings)
task delcomp, "delete a component, removes the nim, gdns, gdnlib, tscn, and dlls associated with the component":
if args.len != 1:
echo "Usage: ./build delcomp comp_name"
quit()
var compName = args[0]
var files = @[nimFilePath(compName),
gdnsFilePath(compName),
gdnlibFilePath(compName),
tscnFilePath(compName)]
for dllFile in walkFiles(&"{dllDir}/{dllPrefix}{compName}*"):
files.add dllFile
for filepath in files:
if fileExists(filepath):
echo &"removing {filepath}"
removeFile(filepath)
# components are named {compName}_safe.dll and
# are loaded by the watcher.dll via resources. At runtime, the watcher.dll will copy
# the {compName}_safe.dll to the {compName}.dll and monitor the _dlls
# folder to see if _safe.dll is rebuilt.
task comp, "build component and generate a gdns and a gdnlib files\n\tno component name means all components are rebuilt\n\tmove safe to hot with 'move' or 'm' flag (e.g.) build -m target\n\t--force or --f force rebuilds\n\t--nocheck or --nc skips compile without dll check but not force rebuilt":
var buildSettings = getBuildSettings()
if not (compName == ""):
compName = compName.snake
echo buildComp(compName, buildSettings)
else:
# compile all the comps
var res = newSeq[FlowVar[string]]()
discard buildAllComps(res, buildSettings)
sync()
for f in res:
echo ^f
task gentool, "generate a tool / editor plugin scaffold":
if args.len != 1:
echo "Usage: ./build gentool tool_name"
quit()
var compName = args[0]
var compClassName = compName.pascal
let nim = &"{compsDir}/tools/{compName}.nim"
if not fileExists(nim):
var f = open(nim, fmWrite)
f.write(tool_nim_template % [compName, compClassName])
f.close()
echo &"generated {nim}"
else:
echo &"{nim} already exists"
let cfg = &"{appDir}/addons/{compName}/plugin.cfg"
if not fileExists(cfg):
createDir(&"{appDir}/addons/{compName}")
var f = open(cfg, fmWrite)
f.write(plugin_cfg_template % [compName])
f.close()
echo &"generated {cfg}"
else:
echo &"{cfg} already exists"
genGdns(compName, isTool = true)
task flags, "display the flags used for compiling components":
echo ">>> Task compiler flags <<<"
for flag in taskCompilerFlagsTable.keys:
echo &"\t{flag} {taskCompilerFlagsTable[flag]}"
echo ">>> Other flags <<<"
for flag in otherFlagsTable.keys:
echo &"\t{flag} {otherFlagsTable[flag]}"
echo ">>> Defined Symbols <<<"
echo &"\t{compilerDefines}"
task cleanbuild, "Rebuild all":
cleandllTask()
# created if vcc and debug flags are used
removeDir(config.getSectionValue("VCC", "pdbdir"))
setFlag("force")
setFlag("move")
var startTime = getTime()
var res = newSeq[FlowVar[string]]()
# watcher task
var watcherFile = tscnDir / "watcher.tscn"
var watcherLineEditFile = tscnDir / "watcher_lineedit.tscn"
var compileCount = 0
if does_reload:
compileCount = 1
echo "building watcher"
if not fileExists(watcherFile):
copyFile(depsDir / "watcher/watcher.tscn", watcherFile)
if not fileExists(watcherLineEditFile):
copyFile(depsDir / "watcher/watcher_lineedit.tscn", watcherLineEditFile)
genGdns("watcher")
res.add(spawn buildWatcher())
else: # remove the watcher
echo "removing watcher"
removeFile(watcherFile)
removeFile(watcherLineEditFile)
removeFile(gdnsDir / "watcher.gdns")
removeFile(gdnlibDir / "watcher.gdnlib")
# comp task
compileCount += buildAllComps(res, getBuildSettings())
sync()
var successes = 0
var failures: seq[string]
for f in res:
var output = ^f
if "[SuccessX]" in output:
inc successes
else:
failures.add output
if successes == compileCount:
var parts = toParts(getTime() - startTime)
var timeStr = ""
timeStr &= (if parts[Minutes] > 0: $parts[Minutes] & " minutes " else: "")
timeStr &= (if parts[Seconds] > 0: $parts[Seconds] & "." & $parts[Milliseconds] & " seconds " else: "")
echo "=== Build OK! === ", timeStr
else:
echo "=== >>> Build Failed >>> ==="
for f in failures:
echo f
echo "=== <<< Build Failed <<< ==="
task init, "creates a new clean branch from master for a new project, pass in the new branch name as an argument":
if args.len != 1:
echo "Usage: ./build init branch_name"
quit()
var branch_name = args[0]
execOrQuit(&"git checkout -b {branch_name} master")
for dir in [compsDir, gdnsDir, gdnlibDir, tscnDir, appDir / "addons", appDir / "gdscripts"]:
execOrQuit(&"git rm {dir}/*")
execOrQuit(&"git rm {appDir}/scenes/main.tscn")
for f in walkFiles(&"{appDir}/*.png.*"):
if "icon.png" notin f:
execOrQuit(&"git rm {f}")
removeDir(dllDir)
for dir in [dllDir, compsDir, gdnsDir, gdnlibDir, tscnDir]:
createDir(dir)
# setup watcher
var watcherFile = tscnDir / "watcher.tscn"
var watcherLineEditFile = tscnDir / "watcher_lineedit.tscn"
if not fileExists(watcherFile):
copyFile(depsDir / "watcher/watcher.tscn", watcherFile)
if not fileExists(watcherLineEditFile):
copyFile(depsDir / "watcher/watcher_lineedit.tscn", watcherLineEditFile)
genGdns("watcher")
copyFile(depsDir / "app/project.godot", appDir / "project.godot")
execOrQuit(&"git add app/")
execOrQuit(&"git commit -m \"init {branch_name}\"")
echo "Running prereqs task"
prereqsTask()
task cwatch, "Monitors the components folder for changes to recompile.":
echo "Monitoring components for changes. Ctrl+C to stop"
var lastTimes = newTable[string, Time]()
for compPath in walkFiles(&"{compsDir}/*.nim"):
lastTimes[compPath] = getLastModificationTime(compPath)
var buildSettings = getBuildSettings()
while true:
for compPath in walkFiles(&"{compsDir}/*.nim"):
var curLastTime = getLastModificationTime(compPath)
if curLastTime > lastTimes[compPath]:
lastTimes[compPath] = curLastTime
var compFilename = splitFile(compPath)[1].snake
echo &"-- Recompiling {compFilename} --"
echo buildComp(compFilename, buildSettings)
sleep cwatch_interval
task diagnostic, "Displays code that contributes to your dll size. Pass in the comp name as an argument: ./build diagnostic comp_name":
checkPrereq("dumpincludes", "https://github.com/treeform/dumpincludes", false)
if config.getSectionValue("Compiler", "build_kind") != "diagnostic":
echo "Dlls must be compiled with Compiler.build_kind == \"diagnostic\""
quit()
execOrQuit(&"dumpincludes -f:{dllDir}/{args[0]}.{dllExt}")
task help, "display list of tasks":
echo "Call build with a task:"
for i in 0..<tasks.len:
echo " ", tasks[i].task_name, " : ", tasks[i].description
echo "\nAdditional flags"
echo " --ini:build.ini : sets the config file"
echo " --nimcheck : runs nim check: checks for syntax and semantics (no compilation)"