-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.zig
More file actions
3459 lines (3104 loc) · 131 KB
/
build.zig
File metadata and controls
3459 lines (3104 loc) · 131 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
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2025 Sam Windell
// SPDX-License-Identifier: GPL-3.0-or-later
const std = @import("std");
const builtin = @import("builtin");
const std_extras = @import("src/build/std_extras.zig");
const constants = @import("src/build/constants.zig");
const cdb = @import("src/build/combine_cdb_fragments.zig");
const check_steps = @import("src/build/check_steps.zig");
const configure_binaries = @import("src/build/configure_binaries.zig");
const release_artifacts = @import("src/build/release_artifacts.zig");
const bgfx_shaderc = @import("src/build/bgfx_shaderc.zig");
const build_context = @import("src/build/context.zig");
const BuildContext = build_context.BuildContext;
const Options = build_context.Options;
const TopLevelSteps = build_context.TopLevelSteps;
const TargetConfig = build_context.TargetConfig;
comptime {
const current_zig = builtin.zig_version;
const required_zig = std.SemanticVersion.parse("0.14.0") catch unreachable;
if (current_zig.order(required_zig) != .eq) {
@compileError(std.fmt.comptimePrint(
"Floe requires Zig version {}, but you are using version {}.",
.{ required_zig, current_zig },
));
}
}
const FlagsBuilder = struct {
flags: std.ArrayList([]const u8),
const Options = struct {
// Enable undefined behaviour sanitizer.
ubsan: bool = false,
// Generate JSON fragments for making compile_commands.json.
gen_cdb_fragments: bool = false,
// Reduce size of windows.h to speed up compilation. Although it can sometimes cut too much.
minimise_windows: bool = true,
// Add all reasonable warnings as possible.
all_warnings: bool = false,
// Language modes.
cpp: bool = false,
objcpp: bool = false,
};
pub fn init(
ctx: *const BuildContext,
cfg: *const TargetConfig,
options: FlagsBuilder.Options,
) FlagsBuilder {
var result = FlagsBuilder{
.flags = std.ArrayList([]const u8).init(ctx.b.allocator),
};
result.addCoreFlags(ctx, cfg, options) catch @panic("OOM");
return result;
}
fn addFlag(self: *FlagsBuilder, flag: []const u8) void {
self.flags.append(flag) catch @panic("OOM");
}
fn addFlags(self: *FlagsBuilder, flags: []const []const u8) void {
for (flags) |flag| self.addFlag(flag);
}
fn addCoreFlags(
self: *FlagsBuilder,
ctx: *const BuildContext,
cfg: *const TargetConfig,
options: FlagsBuilder.Options,
) !void {
if (options.all_warnings) {
try self.flags.appendSlice(&.{
"-Werror",
"-Wconversion",
"-Wexit-time-destructors",
"-Wglobal-constructors",
"-Wall",
"-Wextra",
"-Wextra-semi",
"-Wshadow",
"-Wimplicit-fallthrough",
"-Wunused-member-function",
"-Wunused-template",
"-Wcast-align",
"-Wdouble-promotion",
"-Woverloaded-virtual",
"-Wno-missing-field-initializers",
});
}
if (options.minimise_windows and cfg.target.os.tag == .windows) {
// Minimise windows.h size for faster compile times:
// "Define one or more of the NOapi symbols to exclude the API. For example, NOCOMM excludes
// the serial communication API. For a list of support NOapi symbols, see Windows.h."
try self.flags.appendSlice(&.{
"-DWIN32_LEAN_AND_MEAN",
"-DNOKANJI",
"-DNOHELP",
"-DNOMCX",
"-DNOCLIPBOARD",
"-DNOMEMMGR",
"-DNOMETAFILE",
"-DNOMINMAX",
"-DNOOPENFILE",
"-DNOSERVICE",
"-DNOSOUND",
"-DSTRICT",
"-DNOMINMAX",
});
}
try self.flags.append("-fchar8_t");
try self.flags.append("-D_USE_MATH_DEFINES");
try self.flags.append("-D__USE_FILE_OFFSET64");
try self.flags.append("-D_FILE_OFFSET_BITS=64");
try self.flags.append("-ftime-trace"); // ClangBuildAnalyzer
try self.flags.append("-fvisibility=hidden");
// We want __builtin_FILE(), __FILE__ and debug info to be portable because we use this information in
// stacktraces and logging so we change the absolute paths of all files to be relative to the build root.
// __FILE__, __builtin_FILE(), and DWARF info should be made relative.
// -ffile-prefix-map=OLD=NEW is an alias for both -fdebug-prefix-map and -fmacro-prefix-map
try self.flags.append(ctx.b.fmt("-ffile-prefix-map={s}{s}=", .{
ctx.b.pathFromRoot(""),
std.fs.path.sep_str,
}));
switch (cfg.target.os.tag) {
.windows => {
// On Windows, fix compile errors related to deprecated usage of string in mingw.
try self.flags.append("-DSTRSAFE_NO_DEPRECATE");
try self.flags.append("-DUNICODE");
try self.flags.append("-D_UNICODE");
},
.macos => {
try self.flags.append("-DGL_SILENCE_DEPRECATION"); // disable opengl warnings on macos
// Stop errors when compiling macOS obj-c SDK headers.
try self.flags.appendSlice(&.{
"-Wno-elaborated-enum-base",
"-Wno-missing-method-return-type",
"-Wno-deprecated-declarations",
"-Wno-deprecated-anon-enum-enum-conversion",
"-D__kernel_ptr_semantics=",
"-Wno-c99-extensions",
});
},
.linux => {
// NOTE(Sam, June 2024): workaround for a bug in Zig (most likely) where our shared library always causes a
// crash after dlclose(), as described here: https://github.com/ziglang/zig/issues/17908
// The workaround involves adding this flag and also adding a custom bit of code using
// __attribute__((destructor)) to manually call __cxa_finalize():
// https://stackoverflow.com/questions/34308720/where-is-dso-handle-defined/48256026#48256026
try self.flags.append("-fno-use-cxa-atexit");
},
else => {},
}
// A bit of information about debug symbols:
// DWARF is a debugging information format. It is used widely, particularly on Linux and macOS.
// Zig/libbacktrace, which we use for getting nice stack traces can read DWARF information from the
// executable on any OS. All we need to do is make sure that the DWARF info is available for
// Zig/libbacktrace to read.
//
// On Windows, there is the PDB format, this is a separate file that contains the debug information. Zig
// generates this too, but we can tell it to also embed DWARF debug info into the executable, that's what the
// -gdwarf flag does.
//
// On Linux, it's easy, just use the same flag.
//
// On macOS, there is a slightly different approach. DWARF info is embedded in the compiled .o flags. But
// it's not aggregated into the final executable. Instead, the final executable contains a 'debug map' which
// points to all of the object files and shows where the DWARF info is. You can see this map by running
// 'dsymutil --dump-debug-map my-exe'.
//
// In order to aggregate the DWARF info into the final executable, we need to run 'dsymutil my-exe'. This
// then outputs a .dSYM folder which contains the aggregated DWARF info. Zig/libbacktrace looks for this
// dSYM folder adjacent to the executable.
// Include dwarf debug info, even on windows. This means we can use the Zig/libbacktraceeverywhere to get
// really good stack traces.
//
// We use DWARF 4 because Zig has a problem with version 5: https://github.com/ziglang/zig/issues/23732
try self.flags.append("-gdwarf-4");
if (options.ubsan) {
if (ctx.optimise != .ReleaseFast) {
// By default, zig enables UBSan (unless ReleaseFast mode) in trap mode. Meaning it will catch
// undefined behaviour and trigger a trap which can be caught by signal handlers. UBSan also has a
// mode where undefined behaviour will instead call various functions. This is called the UBSan
// runtime. It's really easy to implement the 'minimal' version of this runtime: we just have to
// declare a bunch of functions like __ubsan_handle_x. So that's what we do rather than trying to
// link with the system's version. https://github.com/ziglang/zig/issues/5163#issuecomment-811606110
try self.flags.append("-fno-sanitize-trap=undefined"); // undo zig's default behaviour (trap mode)
try self.flags.append("-fno-sanitize=function");
const minimal_runtime_mode = false; // I think it's better performance. Certainly less information.
if (minimal_runtime_mode) {
try self.flags.append("-fsanitize-runtime"); // set it to 'minimal' mode
}
}
} else {
try self.flags.append("-fno-sanitize=all");
}
if (options.cpp) {
try self.flags.append("-std=c++2c");
}
if (options.objcpp) {
try self.flags.append("-std=c++2b");
try self.flags.append("-ObjC++");
try self.flags.append("-fobjc-arc");
}
if (options.gen_cdb_fragments)
try cdb.addGenerateCdbFragmentFlags(&self.flags, cfg.cdb_fragments_dir_real);
//
// Library specific flags.
try self.flags.appendSlice(&.{
"-DFLAC__NO_DLL",
});
try self.flags.appendSlice(&.{
"-DPUGL_DISABLE_DEPRECATED",
"-DPUGL_STATIC",
});
try self.flags.append(ctx.b.fmt("-DBX_CONFIG_DEBUG={}", .{@intFromBool(ctx.build_mode == .development)}));
try self.flags.appendSlice(&.{
"-DMINIZ_USE_UNALIGNED_LOADS_AND_STORES=0",
"-DMINIZ_NO_STDIO",
"-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES",
ctx.b.fmt("-DMINIZ_LITTLE_ENDIAN={d}", .{@intFromBool(cfg.target.cpu.arch.endian() == .little)}),
"-DMINIZ_HAS_64BIT_REGISTERS=1",
});
try self.flags.appendSlice(&.{
"-DSTBI_NO_STDIO",
"-DSTBI_MAX_DIMENSIONS=65535", // we use u16 for dimensions
});
if (ctx.build_mode != .production and ctx.enable_tracy) {
try self.flags.append("-DTRACY_ENABLE");
try self.flags.append("-DTRACY_MANUAL_LIFETIME");
try self.flags.append("-DTRACY_DELAYED_INIT");
try self.flags.append("-DTRACY_ONLY_LOCALHOST");
if (cfg.target.os.tag == .linux) {
// Couldn't get these working well so just disabling them
try self.flags.append("-DTRACY_NO_CALLSTACK");
try self.flags.append("-DTRACY_NO_SYSTEM_TRACING");
}
}
}
};
fn applyUniversalSettings(
ctx: *const BuildContext,
step: *std.Build.Step.Compile,
) void {
var b = ctx.b;
// NOTE (May 2025, Zig 0.14): LTO on Windows results in debug_info generation that fails to parse with Zig's
// Dwarf parser (InvalidDebugInfo). We've previously had issues on macOS too. So we disable it for now.
step.want_lto = false;
step.rdynamic = true;
step.linkLibC();
step.addIncludePath(ctx.dep_xxhash.path(""));
step.addIncludePath(ctx.dep_stb.path(""));
step.addIncludePath(ctx.dep_clap.path("include"));
step.addIncludePath(ctx.dep_icon_font_cpp_headers.path(""));
step.addIncludePath(ctx.dep_dr_libs.path(""));
step.addIncludePath(ctx.dep_flac.path("include"));
step.addIncludePath(ctx.dep_lua.path(""));
step.addIncludePath(ctx.dep_pugl.path("include"));
step.addIncludePath(ctx.dep_pugl.path("src"));
step.addIncludePath(ctx.dep_clap_wrapper.path("include"));
step.addIncludePath(ctx.dep_tracy.path("public"));
step.addIncludePath(ctx.dep_valgrind_h.path(""));
step.addIncludePath(ctx.dep_portmidi.path("pm_common"));
step.addIncludePath(ctx.dep_miniz.path(""));
step.addIncludePath(b.path("third_party_libs/miniz"));
step.addIncludePath(b.path("."));
step.addIncludePath(b.path("src"));
step.addIncludePath(b.path("third_party_libs"));
if (step.rootModuleTarget().os.tag == .macos) {
// When using Apple codesign, the binary can silently become invalid. After much investigation it turned out
// to be a problem with the Mach-O headers not having enough padding for additional load commands. Zig's
// default is not enough for codesign's needs, and codesign doesn't tell you this is the problem. To resolve
// this we increase the header padding size significantly. The binaries that had the most problem with this
// issue were release-mode x86_64 builds. In the cases I tested, either of these 2 settings alone was enough
// to fix the problem, but I see no harm in having both in case it covers more situations. While Apple's
// codesign never complains about the problem (and you end up getting segfaults at runtime), an open-source
// alternative called rcodesign correctly reports the error: "insufficient room to write code signature load
// command". There's lengthy discussion about this issue here: https://github.com/ziglang/zig/issues/23704
step.headerpad_size = 0x1000;
step.headerpad_max_install_names = true;
if (b.lazyDependency("macos_sdk", .{})) |sdk| {
step.addSystemIncludePath(sdk.path("usr/include"));
step.addLibraryPath(sdk.path("usr/lib"));
step.addFrameworkPath(sdk.path("System/Library/Frameworks"));
}
}
ctx.compile_all.dependOn(&step.step);
if (step.rootModuleTarget().os.tag == .macos and step.kind == .exe) {
// TODO: is dsymutil step needed
}
}
// Floe only supports a certain set of arch/OS/CPU types.
fn resolveTargets(b: *std.Build, user_given_target_presets: ?[]const u8) !std.ArrayList(std.Build.ResolvedTarget) {
var preset_strings: []const u8 = "native";
if (user_given_target_presets != null) {
preset_strings = user_given_target_presets.?;
}
const SupportedTargetId = enum {
native,
x86_64_windows,
x86_64_linux,
x86_64_macos,
aarch64_macos,
};
// declare a hash map of target presets to SupportedTargetId
var target_map = std.StringHashMap([]const SupportedTargetId).init(b.allocator);
// the actual targets
try target_map.put("native", &.{.native});
try target_map.put("x86_64-windows", &.{.x86_64_windows});
try target_map.put("x86_64-linux", &.{.x86_64_linux});
try target_map.put("x86_64-macos", &.{.x86_64_macos});
try target_map.put("aarch64-macos", &.{.aarch64_macos});
// aliases/shortcuts
try target_map.put("windows", &.{.x86_64_windows});
try target_map.put("linux", &.{.x86_64_linux});
try target_map.put("mac_x86", &.{.x86_64_macos});
try target_map.put("mac_arm", &.{.aarch64_macos});
if (builtin.os.tag == .linux) {
try target_map.put("dev", &.{ .native, .x86_64_windows, .aarch64_macos });
} else if (builtin.os.tag == .macos) {
try target_map.put("dev", &.{ .native, .x86_64_windows });
}
var targets = std.ArrayList(std.Build.ResolvedTarget).init(b.allocator);
// I think Win10+ and macOS 11+ would allow us to target x86_64_v2 (which includes SSE3 and SSE4), but I can't
// find definitive information on this. It's not a big deal for now; the baseline x86_64 target includes SSE2
// which is the important feature for our performance-critical code.
const x86_cpu = "x86_64";
const apple_x86_cpu = "x86_64_v2";
const apple_arm_cpu = "apple_m1";
var it = std.mem.splitSequence(u8, preset_strings, ",");
while (it.next()) |preset_string| {
const target_ids = target_map.get(preset_string) orelse {
std.log.err("unknown target preset: {s}\n", .{preset_string});
@panic("unknown target preset");
};
for (target_ids) |t| {
var arch_os_abi: []const u8 = undefined;
var cpu_features: []const u8 = undefined;
switch (t) {
.native => {
arch_os_abi = "native";
// valgrind doesn't like some AVX instructions so we'll target the baseline x86_64 for now
cpu_features = if (builtin.cpu.arch == .x86_64) x86_cpu else "native";
},
.x86_64_windows => {
arch_os_abi = "x86_64-windows." ++ constants.min_windows_version;
cpu_features = x86_cpu;
},
.x86_64_linux => {
arch_os_abi = "x86_64-linux-gnu.2.31";
cpu_features = x86_cpu;
},
.x86_64_macos => {
arch_os_abi = "x86_64-macos." ++ constants.min_macos_version;
cpu_features = apple_x86_cpu;
},
.aarch64_macos => {
arch_os_abi = "aarch64-macos." ++ constants.min_macos_version;
cpu_features = apple_arm_cpu;
},
}
try targets.append(b.resolveTargetQuery(try std.Target.Query.parse(.{
.arch_os_abi = arch_os_abi,
.cpu_features = cpu_features,
})));
}
}
return targets;
}
const linux_use_pkg_config = std.Build.Module.SystemLib.UsePkgConfig.yes;
pub fn build(b: *std.Build) void {
b.reference_trace = 10; // Improve debugging of build.zig itself.
std_extras.loadEnvFile(b.build_root.handle, &b.graph.env_map) catch {};
// IMPORTANT: if you add options here, you may need to also update the config_hash computation below.
const options: Options = .{
.build_mode = b.option(
build_context.BuildMode,
"build-mode",
"The preset for building the project, affects optimisation, debug settings, etc.",
) orelse .development,
.granular = b.option(bool, "granular", "Experimental granular") orelse false,
.mid_panel_tabs = b.option(bool, "mid-panel-tabs", "Experimental mid-panel tabs") orelse false,
// Installing plugins to global plugin folders requires admin rights but it's often easier to debug
// things without requiring admin. For production builds it's always enabled.
.windows_installer_require_admin = b.option(
bool,
"win-installer-elevated",
"Whether the installer should be set to administrator-required mode",
) orelse false,
.enable_tracy = b.option(bool, "tracy", "Enable Tracy profiler") orelse false,
.sanitize_thread = b.option(
bool,
"sanitize-thread",
"Enable thread sanitiser",
) orelse false,
.fetch_floe_logos = b.option(
bool,
"fetch-floe-logos",
"Fetch Floe logos from online - these may have a different licence to the rest of Floe",
) orelse false,
.targets = b.option([]const u8, "targets", "Target operating system"),
};
const floe_version_string = blk: {
var ver: []const u8 = b.build_root.handle.readFileAlloc(b.allocator, "version.txt", 256) catch @panic("version.txt error");
ver = std.mem.trim(u8, ver, " \r\n\t");
if (options.build_mode != .production) {
ver = b.fmt("{s}+{s}", .{
ver,
std.mem.trim(u8, b.run(&.{ "git", "rev-parse", "--short", "HEAD" }), " \r\n\t"),
});
}
break :blk ver;
};
const floe_version = std.SemanticVersion.parse(floe_version_string) catch @panic("invalid version");
const floe_version_hash = std.hash.Fnv1a_32.hash(floe_version_string);
var ctx: BuildContext = .{
.b = b,
.floe_version_string = floe_version_string,
.floe_version = floe_version,
.floe_version_hash = floe_version_hash,
.native_archiver = null,
.native_docs_generator = null,
.enable_tracy = options.enable_tracy,
.build_mode = options.build_mode,
.optimise = switch (options.build_mode) {
.development => std.builtin.OptimizeMode.Debug,
.performance_profiling, .production => std.builtin.OptimizeMode.ReleaseSafe,
},
.windows_installer_require_admin = options.windows_installer_require_admin,
.dep_floe_logos = if (options.fetch_floe_logos)
b.lazyDependency("floe_logos", .{})
else
null,
.dep_xxhash = b.dependency("xxhash", .{}),
.dep_stb = b.dependency("stb", .{}),
.dep_au_sdk = b.dependency("audio_unit_sdk", .{}),
.dep_miniaudio = b.dependency("miniaudio", .{}),
.dep_clap = b.dependency("clap", .{}),
.dep_clap_wrapper = b.dependency("clap_wrapper", .{}),
.dep_dr_libs = b.dependency("dr_libs", .{}),
.dep_flac = b.dependency("flac", .{}),
.dep_icon_font_cpp_headers = b.dependency("icon_font_cpp_headers", .{}),
.dep_miniz = b.dependency("miniz", .{}),
.dep_lua = b.dependency("lua", .{}),
.dep_pugl = b.dependency("pugl", .{}),
.dep_pffft = b.dependency("pffft", .{}),
.dep_valgrind_h = b.dependency("valgrind_h", .{}),
.dep_portmidi = b.dependency("portmidi", .{}),
.dep_tracy = b.dependency("tracy", .{}),
.dep_vst3_sdk = b.dependency("vst3_sdk", .{}),
.dep_bx = b.dependency("bx", .{}),
.dep_bimg = b.dependency("bimg", .{}),
.dep_bgfx = b.dependency("bgfx", .{}),
// Steps are normally on TopLevelSteps, but compile-all is a special case.
.compile_all = b.step("compile", "Compile all"),
};
var top_level_steps: TopLevelSteps = .{
.build_release = b.step("release", "Create release artifacts (zipped, codesigned, etc.)"),
.install_plugins = b.getInstallStep(),
.install_clap = b.step("install:clap", "Install only the CLAP plugin"),
.install_all = b.step("install:all", "Install all; development files as well as plugins"),
.test_step = b.step("test", "Run unit tests"),
.coverage = b.step("test-coverage", "Generate code coverage report of unit tests"),
.clap_val = b.step("test:clap-val", "Test using clap-validator"),
.test_vst3_validator = b.step("test:vst3-val", "Run VST3 Validator on built VST3 plugin"),
.pluginval_au = b.step("test:pluginval-au", "Test AU using pluginval"),
.auval = b.step("test:auval", "Test AU using auval"),
.pluginval = b.step("test:pluginval", "Test using pluginval"),
.valgrind = b.step("test:valgrind", "Test using Valgrind"),
.test_windows_install = b.step("test:windows-install", "Test installation and uninstallation on Windows"),
.ci = b.step("script:ci", "Run CI checks"),
.ci_basic = b.step("script:ci-basic", "Run basic CI checks"),
.clang_tidy = b.step("check:clang-tidy", "Run clang-tidy on source files"),
.format_step = b.step("script:format", "Format code with clang-format"),
.create_gh_release = b.step("script:create-gh-release", "Create a GitHub release"),
.upload_errors = b.step("script:upload-errors", "Upload error reports to Sentry"),
.shaderc = b.step("script:shaderc", "Compile shaders in src/shaders into .bin.h"),
.website_gen = b.step("script:website-generate", "Generate the static JSON for the website"),
.website_build = b.step("script:website-build", "Build the website"),
.website_dev = b.step("script:website-dev", "Start website dev build locally"),
.website_promote = b.step("script:website-promote-beta-to-stable", "Promote the 'beta' documentation to be the latest stable version"),
.remove_unused_gui_defs = b.step("script:remove-unused-gui-defs", "Remove unused size/colour-map entries from def files"),
};
// The default is to compile everything.
b.default_step = ctx.compile_all;
b.build_root.handle.makeDir(constants.floe_cache_relative) catch {};
const targets = resolveTargets(b, options.targets) catch @panic("OOM");
// If we're building for multiple targets at the same time, we need to choose one that gets to be the
// final compile_commands.json. We just say the first one.
const target_for_compile_commands = targets.items[0];
// We do something a little sneaky. We actual replace all the top-level steps with a hidden
// combine-CDB step. The rest of the code can carry on as if it's still the top level step, but
// it means that the combining of CDG fragments happens as the last step without the rest of the
// code having to worry about it.
var cdb_steps = std.ArrayList(*cdb.CombineCdbFragmentsStep).init(b.allocator);
cdb.insertHiddenCombineCdbStep(b, &ctx.compile_all, &cdb_steps);
inline for (@typeInfo(TopLevelSteps).@"struct".fields) |field| {
cdb.insertHiddenCombineCdbStep(b, &@field(&top_level_steps, field.name), &cdb_steps);
}
// We'll try installing the desired compile_commands.json version here in case any previous build already
// created it.
cdb.trySetCdb(b, target_for_compile_commands.result);
const artifacts_list = b.allocator.alloc(release_artifacts.Artifacts, targets.items.len) catch @panic("OOM");
// Compile/install steps
for (targets.items, 0..) |target, i| {
if (target.result.os.tag == .windows and options.sanitize_thread)
@panic("thread sanitiser is not supported on Windows targets");
const cfg = TargetConfig.create(&ctx, target, &options);
for (cdb_steps.items) |cdb_step| {
cdb_step.addTarget(.{
.fragments_dir = cfg.cdb_fragments_dir,
.target = cfg.target,
.set_as_active = target.query.eql(target_for_compile_commands.query),
}) catch unreachable;
}
artifacts_list[i] = doTarget(&ctx, &cfg, &top_level_steps, &options);
}
// check:* steps.
check_steps.addGlobalCheckSteps(b);
// Build scripts CLI program and add script steps
{
const exe = b.addExecutable(.{
.name = "scripts",
.root_module = b.createModule(.{
.root_source_file = b.path("src/build/scripts.zig"),
.optimize = .Debug,
.target = b.graph.host,
}),
});
if (b.graph.host.result.os.tag == .windows) exe.linkLibC(); // GetTempPath2W
addRunScript(exe, top_level_steps.format_step, "format");
addRunScript(exe, top_level_steps.create_gh_release, "create-gh-release");
addRunScript(exe, top_level_steps.upload_errors, "upload-errors");
addRunScript(exe, top_level_steps.ci, "ci");
addRunScript(exe, top_level_steps.ci_basic, "ci-basic");
addRunScript(exe, top_level_steps.website_promote, "website-promote-beta-to-stable");
addRunScript(exe, top_level_steps.remove_unused_gui_defs, "remove-unused-gui-defs");
}
// Shader compiler.
{
const target = if (builtin.target.os.tag == .linux)
// It's only possible to compile DX11 shaders on Windows, so we try to use wine if we can.
b.resolveTargetQuery(std.Target.Query.parse(.{
.arch_os_abi = "x86_64-windows.win10",
.cpu_features = "x86_64",
}) catch unreachable)
else
b.graph.host;
const cfg = TargetConfig.create(&ctx, target, &options);
const shaderc = bgfx_shaderc.buildShaderC(&ctx, &cfg, .{
.bx = buildBx(&ctx, &cfg),
});
const run = bgfx_shaderc.shaderCRunSteps(&ctx, target.result, shaderc);
top_level_steps.shaderc.dependOn(run);
}
// Make release artifacts
{
const archiver = blk: {
if (ctx.native_archiver) |a| break :blk a;
const native_target_cfg = TargetConfig.create(&ctx, b.graph.host, &options);
break :blk buildArchiver(&ctx, &native_target_cfg, .{
.miniz = buildMiniz(&ctx, &native_target_cfg),
});
};
if (builtin.os.tag != .windows) {
for (targets.items) |target| {
if (target.result.os.tag == .windows) {
const warn = std_extras.addWarn(b, "building Windows release on a non-Windows host, codesigning will be skipped");
top_level_steps.build_release.dependOn(&warn.step);
break;
}
}
}
for (artifacts_list, 0..) |artifacts, i| {
const install_steps = release_artifacts.makeRelease(
b,
archiver,
ctx.floe_version,
targets.items[i].result,
artifacts,
);
top_level_steps.build_release.dependOn(install_steps);
}
}
// Docs generator
{
const docs_generator = blk: {
if (ctx.native_docs_generator) |d| break :blk d;
const native_target_cfg = TargetConfig.create(&ctx, b.graph.host, &options);
break :blk buildDocsGenerator(&ctx, &native_target_cfg, .{
.common_infrastructure = buildCommonInfrastructure(&ctx, &native_target_cfg, .{
.dr_wav = buildDrWav(&ctx, &native_target_cfg),
.flac = buildFlac(&ctx, &native_target_cfg),
.xxhash = buildXxhash(&ctx, &native_target_cfg),
.library = buildFloeLibrary(&ctx, &native_target_cfg, .{
.stb_sprintf = buildStbSprintf(&ctx, &native_target_cfg),
.debug_info_lib = buildDebugInfo(&ctx, &native_target_cfg),
.tracy = buildTracy(&ctx, &native_target_cfg),
}),
.miniz = buildMiniz(&ctx, &native_target_cfg),
}),
});
};
// Run the docs generator. It takes no args but outputs JSON to stdout.
{
const run = std.Build.Step.Run.create(b, b.fmt("run {s}", .{docs_generator.name}));
run.addFileArg(configure_binaries.nix_helper.maybePatchElfExecutable(docs_generator));
const copy = b.addUpdateSourceFiles();
copy.addCopyFileToSource(run.captureStdOut(), "website/static/generated-data.json");
top_level_steps.website_gen.dependOn(©.step);
}
// Build the site for production
{
const npm_install = b.addSystemCommand(&.{ "npm", "install" });
npm_install.setCwd(b.path("website"));
npm_install.expectExitCode(0);
const create_api = CreateWebsiteApiFiles.create(b);
const run = std_extras.createCommandWithStdoutToStderr(b, builtin.target, "run docusaurus build");
run.addArgs(&.{ "npm", "run", "build" });
run.setCwd(b.path("website"));
run.step.dependOn(top_level_steps.website_gen);
run.step.dependOn(&npm_install.step);
run.step.dependOn(&create_api.step);
run.expectExitCode(0);
top_level_steps.website_build.dependOn(&run.step);
}
// Start the website locally
{
const npm_install = b.addSystemCommand(&.{ "npm", "install" });
npm_install.setCwd(b.path("website"));
npm_install.expectExitCode(0);
const run = std_extras.createCommandWithStdoutToStderr(b, builtin.target, "run docusaurus start");
run.addArgs(&.{ "npm", "run", "start" });
run.setCwd(b.path("website"));
run.step.dependOn(top_level_steps.website_gen);
run.step.dependOn(&npm_install.step);
top_level_steps.website_dev.dependOn(&run.step);
}
}
}
fn buildStbSprintf(ctx: *const BuildContext, cfg: *const TargetConfig) *std.Build.Step.Compile {
const obj = ctx.b.addObject(.{
.name = "stb_sprintf",
.root_module = ctx.b.createModule(cfg.module_options),
});
obj.addCSourceFile(.{
.file = ctx.b.path("third_party_libs/stb_sprintf.c"),
.flags = FlagsBuilder.init(ctx, cfg, .{
.gen_cdb_fragments = true,
}).flags.items,
});
obj.addIncludePath(ctx.dep_stb.path(""));
return obj;
}
fn buildXxhash(ctx: *const BuildContext, cfg: *const TargetConfig) *std.Build.Step.Compile {
const obj = ctx.b.addObject(.{
.name = "xxhash",
.root_module = ctx.b.createModule(cfg.module_options),
});
obj.addCSourceFile(.{
.file = ctx.dep_xxhash.path("xxhash.c"),
.flags = FlagsBuilder.init(ctx, cfg, .{
.gen_cdb_fragments = true,
}).flags.items,
});
obj.linkLibC();
return obj;
}
fn buildTracy(ctx: *const BuildContext, cfg: *const TargetConfig) *std.Build.Step.Compile {
const lib = ctx.b.addStaticLibrary(.{
.name = "tracy",
.root_module = ctx.b.createModule(cfg.module_options),
});
lib.addCSourceFile(.{
.file = ctx.dep_tracy.path("public/TracyClient.cpp"),
.flags = FlagsBuilder.init(ctx, cfg, .{
.gen_cdb_fragments = true,
}).flags.items,
});
switch (cfg.target.os.tag) {
.windows => {
lib.linkSystemLibrary("ws2_32");
},
.macos => {},
.linux => {},
else => {
unreachable;
},
}
lib.linkLibCpp();
applyUniversalSettings(ctx, lib);
return lib;
}
fn buildVitfx(ctx: *const BuildContext, cfg: *const TargetConfig) *std.Build.Step.Compile {
const lib = ctx.b.addStaticLibrary(.{
.name = "vitfx",
.root_module = ctx.b.createModule(cfg.module_options),
});
const path = "third_party_libs/vitfx";
lib.addCSourceFiles(.{
.root = ctx.b.path(path),
.files = &.{
"src/synthesis/effects/reverb.cpp",
"src/synthesis/effects/phaser.cpp",
"src/synthesis/effects/delay.cpp",
"src/synthesis/framework/processor.cpp",
"src/synthesis/framework/processor_router.cpp",
"src/synthesis/framework/value.cpp",
"src/synthesis/framework/feedback.cpp",
"src/synthesis/framework/operators.cpp",
"src/synthesis/filters/phaser_filter.cpp",
"src/synthesis/filters/synth_filter.cpp",
"src/synthesis/filters/sallen_key_filter.cpp",
"src/synthesis/filters/comb_filter.cpp",
"src/synthesis/filters/digital_svf.cpp",
"src/synthesis/filters/dirty_filter.cpp",
"src/synthesis/filters/ladder_filter.cpp",
"src/synthesis/filters/diode_filter.cpp",
"src/synthesis/filters/formant_filter.cpp",
"src/synthesis/filters/formant_manager.cpp",
"wrapper.cpp",
},
.flags = FlagsBuilder.init(ctx, cfg, .{
.gen_cdb_fragments = true,
}).flags.items,
});
lib.addIncludePath(ctx.b.path(path ++ "/src/synthesis"));
lib.addIncludePath(ctx.b.path(path ++ "/src/synthesis/framework"));
lib.addIncludePath(ctx.b.path(path ++ "/src/synthesis/filters"));
lib.addIncludePath(ctx.b.path(path ++ "/src/synthesis/lookups"));
lib.addIncludePath(ctx.b.path(path ++ "/src/common"));
lib.linkLibCpp();
lib.addIncludePath(ctx.dep_tracy.path("public"));
return lib;
}
fn buildPugl(ctx: *const BuildContext, cfg: *const TargetConfig) *std.Build.Step.Compile {
const lib = ctx.b.addStaticLibrary(.{
.name = "pugl",
.root_module = ctx.b.createModule(cfg.module_options),
});
const src_path = ctx.dep_pugl.path("src");
const pugl_ver_hash = std.hash.Fnv1a_32.hash(ctx.dep_pugl.builder.pkg_hash);
const pugl_flags = FlagsBuilder.init(ctx, cfg, .{
.gen_cdb_fragments = true,
.minimise_windows = false,
}).flags.items;
lib.addCSourceFiles(.{
.root = src_path,
.files = &.{
"common.c",
"internal.c",
"internal.c",
},
.flags = pugl_flags,
});
switch (cfg.target.os.tag) {
.windows => {
lib.addCSourceFiles(.{
.root = src_path,
.files = &.{
"win.c",
"win_stub.c",
},
.flags = pugl_flags,
});
lib.linkSystemLibrary("opengl32");
lib.linkSystemLibrary("gdi32");
lib.linkSystemLibrary("dwmapi");
},
.macos => {
lib.addCSourceFiles(.{
.root = src_path,
.files = &.{
"mac.m",
"mac_gl.m",
"mac_stub.m",
},
.flags = pugl_flags,
});
lib.root_module.addCMacro("PuglWindow", ctx.b.fmt("PuglWindow{d}", .{pugl_ver_hash}));
lib.root_module.addCMacro("PuglWindowDelegate", ctx.b.fmt("PuglWindowDelegate{d}", .{pugl_ver_hash}));
lib.root_module.addCMacro("PuglWrapperView", ctx.b.fmt("PuglWrapperView{d}", .{pugl_ver_hash}));
lib.root_module.addCMacro("PuglOpenGLView", ctx.b.fmt("PuglOpenGLView{d}", .{pugl_ver_hash}));
lib.linkFramework("OpenGL");
lib.linkFramework("CoreVideo");
},
.linux => {
lib.addCSourceFiles(.{
.root = src_path,
.files = &[_][]const u8{
"x11.c",
"x11_stub.c",
"x11_gl.c",
},
.flags = pugl_flags,
});
lib.root_module.addCMacro("USE_XRANDR", "0");
lib.root_module.addCMacro("USE_XSYNC", "1");
lib.root_module.addCMacro("USE_XCURSOR", "1");
lib.linkSystemLibrary2("gl", .{ .use_pkg_config = linux_use_pkg_config });
lib.linkSystemLibrary2("glx", .{ .use_pkg_config = linux_use_pkg_config });
lib.linkSystemLibrary2("x11", .{ .use_pkg_config = linux_use_pkg_config });
lib.linkSystemLibrary2("xcursor", .{ .use_pkg_config = linux_use_pkg_config });
lib.linkSystemLibrary2("xext", .{ .use_pkg_config = linux_use_pkg_config });
},
else => {},
}
lib.root_module.addCMacro("PUGL_DISABLE_DEPRECATED", "1");
lib.root_module.addCMacro("PUGL_STATIC", "1");
applyUniversalSettings(ctx, lib);
return lib;
}
fn buildDebugInfo(ctx: *const BuildContext, cfg: *const TargetConfig) *std.Build.Step.Compile {
var opts = cfg.module_options;
opts.root_source_file = ctx.b.path("src/utils/debug_info/debug_info.zig");
const lib = ctx.b.addObject(.{
.name = "debug_info_lib",
.root_module = ctx.b.createModule(opts),
});
lib.linkLibC(); // Means better debug info on Linux
lib.addIncludePath(ctx.b.path("src/utils/debug_info"));
return lib;
}
// IMPROVE: does this need to be a library? is foundation/os/plugin all linked together?
fn buildFloeLibrary(ctx: *const BuildContext, cfg: *const TargetConfig, deps: struct {
stb_sprintf: *std.Build.Step.Compile,
debug_info_lib: *std.Build.Step.Compile,
tracy: *std.Build.Step.Compile,
}) *std.Build.Step.Compile {
const lib = ctx.b.addStaticLibrary(.{
.name = "library",
.root_module = ctx.b.createModule(cfg.module_options),
});
const common_source_files = .{
"src/utils/debug/debug.cpp",
"src/utils/cli_arg_parse.cpp",
"src/utils/leak_detecting_allocator.cpp",
"src/utils/no_hash.cpp",
"src/tests/framework.cpp",
"src/utils/logger/logger.cpp",
"src/foundation/utils/string.cpp",
"src/os/filesystem.cpp",
"src/os/misc.cpp",
"src/os/web.cpp",
"src/os/threading.cpp",
};
const unix_source_files = .{
"src/os/filesystem_unix.cpp",
"src/os/misc_unix.cpp",
"src/os/threading_pthread.cpp",
};
const windows_source_files = .{
"src/os/filesystem_windows.cpp",
"src/os/misc_windows.cpp",
"src/os/threading_windows.cpp",
"src/os/web_windows.cpp",
};
const macos_source_files = .{
"src/os/filesystem_mac.mm",
"src/os/misc_mac.mm",
"src/os/threading_mac.cpp",
"src/os/web_mac.mm",
};
const linux_source_files = .{
"src/os/filesystem_linux.cpp",
"src/os/misc_linux.cpp",
"src/os/threading_linux.cpp",
"src/os/web_linux.cpp",
};
const library_flags = FlagsBuilder.init(ctx, cfg, .{
.all_warnings = true,
.ubsan = true,
.cpp = true,
.gen_cdb_fragments = true,
}).flags.items;
switch (cfg.target.os.tag) {
.windows => {
lib.addCSourceFiles(.{
.files = &windows_source_files,
.flags = library_flags,
});
lib.linkSystemLibrary("dbghelp");
lib.linkSystemLibrary("shlwapi");
lib.linkSystemLibrary("ole32");
lib.linkSystemLibrary("crypt32");
lib.linkSystemLibrary("uuid");