Repository navigation
Expand file tree
/
Copy pathbuild.zig
More file actions
994 lines (854 loc) · 39.3 KB
/
Copy pathbuild.zig
File metadata and controls
994 lines (854 loc) · 39.3 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
const std = @import("std");
const builtin = @import("builtin");
pub const emsdk = struct {
const emsdk_version = "4.0.19"; // inline constant used only in activate
var emsdk_dep: ?*std.Build.Dependency = null;
// ---------- core types ----------
pub const EmccFlags = std.StringHashMap(void);
pub const EmccSettings = std.StringHashMap([]const u8);
const EmsdkAllocator = enum {
none,
dlmalloc,
emmalloc,
@"emmalloc-debug",
@"emmalloc-memvalidate",
@"emmalloc-verbose",
mimalloc,
};
pub const ResourceFile = struct {
src_path: std.Build.LazyPath,
virtual_path: ?[]const u8 = null,
fn get(self: ResourceFile, b: *std.Build) []const u8 {
return if (self.virtual_path) |vp|
b.fmt("{s}@{s}", .{ self.src_path.getDisplayName(), vp })
else
self.src_path.getDisplayName();
}
};
pub const EmccStepOptions = struct {
optimize: std.builtin.OptimizeMode,
flags: EmccFlags,
settings: EmccSettings,
use_preload_plugins: bool = false,
embed_paths: ?[]const ResourceFile = null,
preload_paths: ?[]const ResourceFile = null,
shell_file_path: ?std.Build.LazyPath = null,
js_library_path: ?std.Build.LazyPath = null,
out_file_name: []const u8,
install_dir: std.Build.InstallDir,
};
// ---------- helpers ----------
pub fn emsdkDep(b: *std.Build) !*std.Build.Dependency {
if (emsdk_dep == null) {
emsdk_dep = try b.dependencyLazy("emsdk", .{});
}
return emsdk_dep.?;
}
pub fn path(b: *std.Build, sub_path: []const u8) !std.Build.LazyPath {
return (try emsdkDep(b)).path(sub_path);
}
pub fn emccPath(b: *std.Build) !std.Build.LazyPath {
return try emsdk.path(b, "upstream/emscripten/emcc.py");
}
pub fn emrunPath(b: *std.Build) !std.Build.LazyPath {
return switch (builtin.target.os.tag) {
.windows => try emsdk.path(b, "upstream/emscripten/emrun.bat"),
else => try emsdk.path(b, "upstream/emscripten/emrun"),
};
}
pub fn emccDefaultFlags(allocator: std.mem.Allocator, options: struct {
optimize: std.builtin.OptimizeMode,
asyncify: bool = true,
fsanitize: bool = true,
}) EmccFlags {
var flags = EmccFlags.init(allocator);
switch (options.optimize) {
.Debug => {
flags.put("-O0", {}) catch @panic("OOM");
flags.put("-gsource-map", {}) catch @panic("OOM");
if (options.fsanitize)
flags.put("-fsanitize=undefined", {}) catch @panic("OOM");
},
.ReleaseSafe => {
flags.put("-O3", {}) catch @panic("OOM");
if (options.fsanitize) {
flags.put("-fsanitize=undefined", {}) catch @panic("OOM");
flags.put("-fsanitize-minimal-runtime", {}) catch @panic("OOM");
}
},
.ReleaseFast => flags.put("-O3", {}) catch @panic("OOM"),
.ReleaseSmall => flags.put("-Oz", {}) catch @panic("OOM"),
}
if (options.asyncify)
flags.put("-sASYNCIFY", {}) catch @panic("OOM");
return flags;
}
pub fn emccDefaultSettings(allocator: std.mem.Allocator, options: struct {
optimize: std.builtin.OptimizeMode,
es3: bool = false,
glfw3: bool = true,
memory_growth: bool = false,
total_memory: u32 = 134217728,
emsdk_allocator: EmsdkAllocator = .emmalloc,
}) EmccSettings {
var settings = EmccSettings.init(allocator);
switch (options.optimize) {
.Debug, .ReleaseSafe => {
settings.put("SAFE_HEAP", "1") catch @panic("OOM");
settings.put("STACK_OVERFLOW_CHECK", "1") catch @panic("OOM");
settings.put("ASSERTIONS", "1") catch @panic("OOM");
},
else => {},
}
settings.put("MALLOC", @tagName(options.emsdk_allocator)) catch @panic("OOM");
if (options.es3) {
settings.put("FULL_ES3", "1") catch @panic("OOM");
settings.put("MIN_WEBGL_VERSION", "2") catch @panic("OOM");
settings.put("MAX_WEBGL_VERSION", "2") catch @panic("OOM");
}
if (options.glfw3)
settings.put("USE_GLFW", "3") catch @panic("OOM");
const total_memory = std.fmt.allocPrint(allocator, "{d}", .{options.total_memory}) catch @panic("OOM");
settings.put("EXPORTED_RUNTIME_METHODS", "['requestFullscreen']") catch @panic("OOM");
settings.put("TOTAL_MEMORY", total_memory) catch @panic("OOM");
settings.put("FORCE_FILESYSTEM", "1") catch @panic("OOM");
settings.put("EXPORTED_RUNTIME_METHODS", "ccall") catch @panic("OOM");
if (options.memory_growth)
settings.put("ALLOW_MEMORY_GROWTH", "1") catch @panic("OOM");
return settings;
}
// ---------- step builders ----------
pub fn emccStep(b: *std.Build, src_paths: []const std.Build.LazyPath, compile_steps: []const *std.Build.Step.Compile, options: EmccStepOptions) !*std.Build.Step {
var emcc = b.addRunFile(try emccPath(b));
// flags
{
var it = options.flags.iterator();
while (it.next()) |kv| emcc.addArg(kv.key_ptr.*);
}
// settings
{
var it = options.settings.iterator();
while (it.next()) |kv| {
emcc.addArg(b.fmt("-s{s}={s}", .{ kv.key_ptr.*, kv.value_ptr.* }));
}
}
// source files & artifact dependencies
for (src_paths) |sp| emcc.addFileArg(sp);
for (compile_steps) |cs| {
emcc.addArtifactArg(cs);
cs.root_module.addIncludePath(try emsdk.path(b, "upstream/emscripten/cache/sysroot/include"));
for (cs.root_module.getGraph().modules) |mod| {
for (mod.link_objects.items) |lo| {
if (lo == .other_step) {
const linked = lo.other_step;
if (linked.kind == .lib) emcc.addArtifactArg(linked);
}
}
}
}
emcc.addArg("-o");
const out_file = emcc.addOutputFileArg(options.out_file_name);
// optional args
if (options.use_preload_plugins) emcc.addArg("--use-preload-plugins");
if (options.embed_paths) |eps| for (eps) |ep| {
emcc.addArg("--embed-file");
emcc.addFileArg(ep.src_path);
};
if (options.preload_paths) |pps| for (pps) |pp| {
emcc.addArg("--preload-file");
emcc.addArg(pp.get(b));
};
if (options.shell_file_path) |sfp| {
emcc.addArg("--shell-file");
emcc.addFileArg(sfp);
}
if (options.js_library_path) |jlp| {
emcc.addArg("--js-library");
emcc.addFileArg(jlp);
}
const install = b.addInstallDirectory(.{
.source_dir = out_file.dirname(),
.install_dir = options.install_dir,
.install_subdir = "",
});
install.step.dependOn(&emcc.step);
return &install.step;
}
pub fn emrunStep(b: *std.Build, html_path: std.Build.LazyPath, extra_args: []const []const u8) !*std.Build.Step {
var emrun = b.addRunFile(try emrunPath(b));
emrun.addArgs(extra_args);
emrun.addFileArg(html_path);
return &emrun.step;
}
pub fn activateEmsdkStep(b: *std.Build) !*std.Build.Step {
const user = b.step("Activate EMSDK", "Install/Update and prepare emscripten sdk");
const script = switch (builtin.target.os.tag) {
.windows => try emsdk.path(b, "emsdk.bat"),
else => try emsdk.path(b, "emsdk"),
};
var update = b.addRunFile(script);
update.addArg("update");
// chmod / takeown for script
const make_script_exec: ?*std.Build.Step.Run = switch (builtin.target.os.tag) {
.linux, .macos => blk: {
var cmd = b.addSystemCommand(&.{ "chmod", "+x" });
cmd.addFileArg(script);
break :blk cmd;
},
.windows => blk: {
var cmd = b.addSystemCommand(&.{ "takeown", "/f" });
cmd.addFileArg(script);
break :blk cmd;
},
else => null,
};
if (make_script_exec) |mse| update.step.dependOn(&mse.step);
var install = b.addRunFile(script);
install.addArg("install");
install.addArg(emsdk_version);
install.step.dependOn(&update.step);
var activate = b.addRunFile(script);
activate.addArg("activate");
activate.addArg(emsdk_version);
activate.step.dependOn(&install.step);
user.dependOn(&activate.step);
// also ensure emcc/emrun are executable on Unix
if (builtin.target.os.tag == .linux or builtin.target.os.tag == .macos) {
for ([_]std.Build.LazyPath{ try emccPath(b), try emrunPath(b) }) |p| {
var cmd = b.addSystemCommand(&.{ "chmod", "a+x" });
cmd.addFileArg(p);
cmd.step.dependOn(&install.step);
user.dependOn(&cmd.step);
}
}
return user;
}
};
pub fn linkWindows(mod: *std.Build.Module, opengl: bool, comptime shcore: bool) void {
if (opengl) mod.linkSystemLibrary("opengl32", .{});
mod.linkSystemLibrary("winmm", .{});
mod.linkSystemLibrary("gdi32", .{});
if (shcore) mod.linkSystemLibrary("shcore", .{});
}
fn findWaylandScanner(b: *std.Build) void {
_ = b.findProgram(.{ .names = &.{"wayland-scanner"} }) orelse {
std.log.err(
\\ `wayland-scanner` may not be installed on the system.
\\ You can switch to X11 in your `build.zig` by changing `Options.linux_display_backend`
, .{});
@panic("`wayland-scanner` not found");
};
}
pub fn linkLinux(mod: *std.Build.Module, comptime display_backend: LinuxDisplayBackend) void {
if (display_backend == .None) {
mod.linkSystemLibrary("GL", .{});
}
if (display_backend == .X11) {
mod.linkSystemLibrary("X11", .{});
mod.linkSystemLibrary("Xrandr", .{});
mod.linkSystemLibrary("Xinerama", .{});
mod.linkSystemLibrary("Xi", .{});
mod.linkSystemLibrary("Xcursor", .{});
}
if (display_backend == .Wayland) {
mod.linkSystemLibrary("wayland-client", .{});
mod.linkSystemLibrary("wayland-cursor", .{});
mod.linkSystemLibrary("wayland-egl", .{});
mod.linkSystemLibrary("xkbcommon", .{});
}
}
pub fn linkBSD(_: *std.Build, mod: *std.Build.Module) void {
mod.linkSystemLibrary("GL", .{});
}
pub fn linkMacOS(b: *std.Build, mod: *std.Build.Module) !void {
// Include xcode_frameworks for cross compilation
const dep = try b.dependencyLazy("xcode_frameworks", .{});
mod.addSystemFrameworkPath(dep.path("Frameworks"));
mod.addSystemIncludePath(dep.path("include"));
mod.addLibraryPath(dep.path("lib"));
mod.linkFramework("Foundation", .{});
mod.linkFramework("CoreServices", .{});
mod.linkFramework("CoreGraphics", .{});
mod.linkFramework("AppKit", .{});
mod.linkFramework("IOKit", .{});
mod.linkFramework("QuartzCore", .{});
}
fn compileRaylib(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, options: Options) !*std.Build.Step.Compile {
const raylib_mod = b.createModule(.{
.optimize = optimize,
.target = target,
.link_libc = true,
});
const raylib = b.addLibrary(.{
.name = "raylib",
.linkage = options.linkage,
.root_module = raylib_mod,
});
// On Linux (glibc) avoid _GNU_SOURCE, on glibc >= 2.38 it redirects sscanf(), strtol()...
// to __isoc23_*() symbols, so the generated library fails to link with older glibc versions
if (target.result.os.tag == .linux and !target.result.abi.isAndroid()) {
raylib_mod.addCMacro("_DEFAULT_SOURCE", "");
} else {
raylib_mod.addCMacro("_GNU_SOURCE", "");
}
raylib_mod.addCMacro("GL_SILENCE_DEPRECATION", "199309L");
var arena: std.heap.ArenaAllocator = .init(b.allocator);
defer arena.deinit();
var raylib_flags_arr: std.array_list.Managed([]const u8) = .init(arena.allocator());
var c_source_files: std.array_list.Managed([]const u8) = .init(arena.allocator());
try c_source_files.append("src/rcore.c");
if (target.result.os.tag == .emscripten) {
try raylib_flags_arr.append("-std=gnu99");
} else {
try raylib_flags_arr.append("-std=c99");
}
if (options.linkage == .dynamic) {
raylib_mod.pic = true;
raylib_mod.addCMacro("BUILD_LIBTYPE_SHARED", "");
}
if (options.config.len > 0) {
// Splits a space-separated list of config flags into multiple flags
//
// Note: This means certain flags like `-x c++` won't be processed properly.
// `-xc++` or similar should be used when possible
var config_iter = std.mem.tokenizeScalar(u8, options.config, ' ');
// Apply config flags supplied by the user
while (config_iter.next()) |config_flag| {
try raylib_flags_arr.append(config_flag);
}
}
raylib_mod.addCMacro("SUPPORT_MODULE_RSHAPES", &.{@as(u8, @intFromBool(options.rshapes)) + 0x30});
if (options.rshapes) {
try c_source_files.append("src/rshapes.c");
}
raylib_mod.addCMacro("SUPPORT_MODULE_RTEXTURES", &.{@as(u8, @intFromBool(options.rtextures)) + 0x30});
if (options.rtextures) {
try c_source_files.append("src/rtextures.c");
}
raylib_mod.addCMacro("SUPPORT_MODULE_RTEXT", &.{@as(u8, @intFromBool(options.rtext)) + 0x30});
if (options.rtext) {
try c_source_files.append("src/rtext.c");
}
raylib_mod.addCMacro("SUPPORT_MODULE_RMODELS", &.{@as(u8, @intFromBool(options.rmodels)) + 0x30});
if (options.rmodels) {
try c_source_files.append("src/rmodels.c");
}
raylib_mod.addCMacro("SUPPORT_MODULE_RAUDIO", &.{@as(u8, @intFromBool(options.raudio)) + 0x30});
if (options.raudio) {
try c_source_files.append("src/raudio.c");
}
raylib_mod.addIncludePath(b.path("src/platforms"));
switch (options.platform) {
.glfw => {
var opengl_version: OpenglVersion = options.opengl_version;
if (opengl_version == .gl_soft) {
@panic("The opengl version is not supported by this platform");
}
raylib_mod.addIncludePath(b.path("src/external/glfw/include"));
if (target.result.os.tag != .emscripten) {
if (opengl_version == .auto) {
opengl_version = OpenglVersion.gl_3_3;
}
raylib_mod.addCMacro("PLATFORM_DESKTOP_GLFW", "");
try c_source_files.append("src/rglfw.c");
}
switch (target.result.os.tag) {
.windows => linkWindows(raylib_mod, true, false),
.linux => {
if (target.result.abi.isAndroid()) {
@panic("Target is not supported with this platform");
}
linkLinux(raylib_mod, .None);
if (options.linux_display_backend == .X11 or options.linux_display_backend == .Both) {
raylib_mod.addCMacro("_GLFW_X11", "");
linkLinux(raylib_mod, .X11);
}
if (options.linux_display_backend == .Wayland or options.linux_display_backend == .Both) {
findWaylandScanner(b);
raylib_mod.addCMacro("_GLFW_WAYLAND", "");
linkLinux(raylib_mod, .Wayland);
try waylandGenerate(b, raylib, "src/external/glfw/deps/wayland/", false);
}
},
.freebsd, .openbsd, .netbsd, .dragonfly => linkBSD(b, raylib_mod),
.macos => {
// On macos rglfw.c include Objective-C files.
_ = c_source_files.pop();
try raylib_flags_arr.append("-ObjC");
raylib_mod.addCSourceFile(.{
.file = b.path("src/rglfw.c"),
.flags = raylib_flags_arr.items,
});
_ = raylib_flags_arr.pop();
try linkMacOS(b, raylib_mod);
},
.emscripten => {
switch (opengl_version) {
.auto => opengl_version = OpenglVersion.gles_2,
.gles_2, .gles_3, .gl_soft => {},
else => @panic("opengl version not supported"),
}
raylib_mod.addCMacro("PLATFORM_WEB", "");
raylib_mod.addIncludePath(try emsdk.path(b, "upstream/emscripten/cache/sysroot/include"));
const activate_emsdk_step = try emsdk.activateEmsdkStep(b);
raylib.step.dependOn(activate_emsdk_step);
},
else => @panic("Target is not supported with this platform"),
}
raylib_mod.addCMacro(opengl_version.toCMacroStr(), "");
},
.rgfw => {
var opengl_version: OpenglVersion = options.opengl_version;
if (target.result.os.tag != .emscripten) {
if (opengl_version == .auto) {
opengl_version = OpenglVersion.gl_3_3;
}
raylib_mod.addCMacro("PLATFORM_DESKTOP_RGFW", "");
}
switch (target.result.os.tag) {
.windows => linkWindows(raylib_mod, true, false),
.linux => {
if (target.result.abi.isAndroid()) {
@panic("Target is not supported with this platform");
}
linkLinux(raylib_mod, .None);
if (options.linux_display_backend == .X11 or options.linux_display_backend == .Both) {
raylib_mod.addCMacro("RGFW_X11", "");
raylib_mod.addCMacro("RGFW_UNIX", "");
linkLinux(raylib_mod, .X11);
}
if (options.linux_display_backend == .Wayland or options.linux_display_backend == .Both) {
findWaylandScanner(b);
if (options.linux_display_backend != .Both) {
raylib_mod.addCMacro("RGFW_NO_X11", "");
}
raylib_mod.addCMacro("RGFW_WAYLAND", "");
raylib_mod.addCMacro("EGLAPIENTRY", "");
linkLinux(raylib_mod, .Wayland);
try waylandGenerate(b, raylib, "src/external/RGFW/deps/wayland/", true);
}
},
.freebsd, .openbsd, .netbsd, .dragonfly => linkBSD(b, raylib_mod),
.macos => try linkMacOS(b, raylib_mod),
.emscripten => {
switch (opengl_version) {
.auto => opengl_version = OpenglVersion.gles_2,
.gles_2, .gles_3, .gl_soft => {},
else => @panic("opengl version not supported"),
}
raylib_mod.addCMacro("PLATFORM_WEB_RGFW", "");
raylib_mod.addIncludePath(try emsdk.path(b, "upstream/emscripten/cache/sysroot/include"));
const activate_emsdk_step = try emsdk.activateEmsdkStep(b);
raylib.step.dependOn(activate_emsdk_step);
},
else => @panic("Target is not supported with this platform"),
}
raylib_mod.addCMacro(opengl_version.toCMacroStr(), "");
},
.sdl, .sdl2, .sdl3 => {
if (options.opengl_version == .auto) {
raylib_mod.addCMacro(OpenglVersion.gl_3_3.toCMacroStr(), "");
} else {
raylib_mod.addCMacro(options.opengl_version.toCMacroStr(), "");
}
raylib_mod.addCMacro("PLATFORM_DESKTOP_SDL", "");
if (options.platform == .sdl2) {
raylib_mod.addCMacro("USING_SDL2_PACKAGE", "");
}
if (options.platform == .sdl3) {
raylib_mod.addCMacro("USING_SDL3_PACKAGE", "");
}
},
.memory => {
if (options.opengl_version != .auto and options.opengl_version != .gl_soft) {
@panic("The opengl version is not supported by this platform");
}
raylib_mod.addCMacro(OpenglVersion.gl_soft.toCMacroStr(), "");
raylib_mod.addCMacro("PLATFORM_MEMORY", "");
},
.win32 => {
if (target.result.os.tag != .windows) {
@panic("Target is not supported with this platform");
}
if (options.opengl_version == .auto) {
raylib_mod.addCMacro(OpenglVersion.gl_3_3.toCMacroStr(), "");
} else {
raylib_mod.addCMacro(options.opengl_version.toCMacroStr(), "");
}
raylib_mod.addCMacro("PLATFORM_DESKTOP_WIN32", "");
linkWindows(raylib_mod, options.opengl_version != .gl_soft, true);
},
.drm => {
if (target.result.os.tag != .linux) {
@panic("Target is not supported with this platform");
}
raylib_mod.addCMacro("PLATFORM_DRM", "");
raylib_mod.addCMacro("EGL_NO_X11", "");
raylib_mod.addCMacro("DEFAULT_BATCH_BUFFER_ELEMENT", "");
try raylib_flags_arr.append("-Werror=implicit-function-declaration");
raylib_mod.linkSystemLibrary("libdrm", .{ .use_pkg_config = .force });
raylib_mod.linkSystemLibrary("drm", .{});
raylib_mod.linkSystemLibrary("gbm", .{});
switch (options.opengl_version) {
.auto, .gles_2 => {
raylib_mod.addCMacro(OpenglVersion.gles_2.toCMacroStr(), "");
raylib_mod.linkSystemLibrary("GLESv2", .{});
raylib_mod.linkSystemLibrary("EGL", .{});
},
.gl_soft => {},
else => @panic("The opengl version is not supported by this platform"),
}
},
.android => {
if (!target.result.abi.isAndroid()) {
@panic("Target is not supported with this platform");
}
raylib_mod.addCMacro("PLATFORM_ANDROID", "");
raylib_mod.linkSystemLibrary("EGL", .{});
switch (options.opengl_version) {
.auto, .gles_2 => {
raylib_mod.addCMacro(OpenglVersion.gles_2.toCMacroStr(), "");
raylib_mod.linkSystemLibrary("GLESv2", .{});
},
else => @panic("The opengl version is not supported by this platform"),
}
//these are the only tag options per https://developer.android.com/ndk/guides/other_build_systems
const hostTuple = switch (builtin.target.os.tag) {
.linux => "linux-x86_64",
.windows => "windows-x86_64",
.macos => "darwin-x86_64",
else => @panic("unsupported host OS"),
};
const androidTriple = switch (target.result.cpu.arch) {
.x86 => "i686-linux-android",
.x86_64 => "x86_64-linux-android",
.arm => "arm-linux-androideabi",
.aarch64 => "aarch64-linux-android",
.riscv64 => "riscv64-linux-android",
else => error.InvalidAndroidTarget,
} catch @panic("invalid android target!");
const androidNdkPathString: []const u8 = options.android_ndk;
if (androidNdkPathString.len < 1) @panic("no ndk path provided and ANDROID_NDK_HOME is not set");
const androidApiLevel: []const u8 = options.android_api_version;
const androidSysroot = try std.fs.path.join(b.allocator, &.{ androidNdkPathString, "/toolchains/llvm/prebuilt/", hostTuple, "/sysroot" });
const androidLibPath = try std.fs.path.join(b.allocator, &.{ androidSysroot, "/usr/lib/", androidTriple });
const androidApiSpecificPath = try std.fs.path.join(b.allocator, &.{ androidLibPath, androidApiLevel });
const androidIncludePath = try std.fs.path.join(b.allocator, &.{ androidSysroot, "/usr/include" });
const androidArchIncludePath = try std.fs.path.join(b.allocator, &.{ androidIncludePath, androidTriple });
const androidAsmPath = try std.fs.path.join(b.allocator, &.{ androidIncludePath, "/asm-generic" });
const androidGluePath = try std.fs.path.join(b.allocator, &.{ androidNdkPathString, "/sources/android/native_app_glue/" });
raylib_mod.addLibraryPath(.{ .cwd_relative = androidLibPath });
raylib_mod.addLibraryPath(.{ .cwd_relative = androidApiSpecificPath });
raylib_mod.addSystemIncludePath(.{ .cwd_relative = androidIncludePath });
raylib_mod.addSystemIncludePath(.{ .cwd_relative = androidArchIncludePath });
raylib_mod.addSystemIncludePath(.{ .cwd_relative = androidAsmPath });
raylib_mod.addSystemIncludePath(.{ .cwd_relative = androidGluePath });
const libc_data = try std.fmt.allocPrint(b.allocator,
\\include_dir={0s}/sysroot/usr/include
\\sys_include_dir={0s}/sysroot/usr/include/aarch64-linux-android
\\crt_dir={0s}/sysroot/usr/lib/aarch64-linux-android/24
\\static_lib_dir={0s}/sysroot/usr/lib/aarch64-linux-android/24
\\msvc_lib_dir=
\\kernel32_lib_dir=
\\gcc_dir=
\\
, .{androidNdkPathString});
const write_step = b.addWriteFiles();
const libcFile = write_step.add("android-libc.txt", libc_data);
raylib.setLibCFile(libcFile);
},
}
raylib_mod.addCSourceFiles(.{
.files = c_source_files.items,
.flags = raylib_flags_arr.items,
});
return raylib;
}
fn addRaygui(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, raylib: *std.Build.Step.Compile) !void {
const raygui_dep = try b.dependencyLazy("raygui", .{
.target = target,
.optimize = optimize,
.link_libc = true,
});
var gen_step = b.addWriteFiles();
raylib.step.dependOn(&gen_step.step);
const raygui_c_path = gen_step.add("raygui.c", "#define RAYGUI_IMPLEMENTATION\n#include \"raygui.h\"\n");
raylib.root_module.addCSourceFile(.{ .file = raygui_c_path });
raylib.root_module.addIncludePath(raygui_dep.path("src"));
raylib.root_module.addIncludePath(b.path("src"));
raylib.installHeader(raygui_dep.path("src/raygui.h"), "raygui.h");
const c = b.addTranslateC(.{
.root_source_file = raygui_dep.path("src/raygui.h"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
c.addIncludePath(b.path("src"));
const c_mod = c.createModule();
c_mod.linkLibrary(raylib);
b.modules.put(b.graph.arena, "raygui", c_mod) catch @panic("OOM");
}
pub const Options = struct {
raudio: bool = true,
rmodels: bool = true,
rshapes: bool = true,
rtext: bool = true,
rtextures: bool = true,
raygui: bool = false,
platform: PlatformBackend = .glfw,
linkage: std.builtin.LinkMode = .static,
linux_display_backend: LinuxDisplayBackend = .X11,
opengl_version: OpenglVersion = .auto,
android_ndk: []const u8 = "",
android_api_version: []const u8 = "35",
/// config should be a list of space-separated cflags, eg, "-DSUPPORT_CUSTOM_FRAME_CONTROL"
config: []const u8 = &.{},
const defaults = Options{};
pub fn getOptions(b: *std.Build) Options {
return .{
.platform = b.option(PlatformBackend, "platform", "Choose the platform backend for desktop target") orelse defaults.platform,
.raudio = b.option(bool, "raudio", "Compile with audio support") orelse defaults.raudio,
.rmodels = b.option(bool, "rmodels", "Compile with models support") orelse defaults.rmodels,
.rtext = b.option(bool, "rtext", "Compile with text support") orelse defaults.rtext,
.rtextures = b.option(bool, "rtextures", "Compile with textures support") orelse defaults.rtextures,
.rshapes = b.option(bool, "rshapes", "Compile with shapes support") orelse defaults.rshapes,
.raygui = b.option(bool, "raygui", "Include raygui") orelse defaults.raygui,
.linkage = b.option(std.builtin.LinkMode, "linkage", "Compile as shared or static library") orelse defaults.linkage,
.linux_display_backend = b.option(LinuxDisplayBackend, "linux_display_backend", "Linux display backend to use") orelse defaults.linux_display_backend,
.opengl_version = b.option(OpenglVersion, "opengl_version", "OpenGL version to use") orelse defaults.opengl_version,
.config = b.option([]const u8, "config", "Compile with custom define macros overriding config.h") orelse &.{},
.android_ndk = b.option([]const u8, "android_ndk", "specify path to android ndk") orelse b.graph.environ_map.get("ANDROID_NDK_HOME") orelse "",
.android_api_version = b.option([]const u8, "android_api_version", "specify target android API level") orelse defaults.android_api_version,
};
}
};
pub const OpenglVersion = enum {
auto,
gl_soft,
gl_1_1,
gl_2_1,
gl_3_3,
gl_4_3,
gles_2,
gles_3,
pub fn toCMacroStr(self: @This()) []const u8 {
switch (self) {
.auto => @panic("OpenglVersion.auto cannot be turned into a C macro string"),
.gl_soft => return "GRAPHICS_API_OPENGL_SOFTWARE",
.gl_1_1 => return "GRAPHICS_API_OPENGL_11",
.gl_2_1 => return "GRAPHICS_API_OPENGL_21",
.gl_3_3 => return "GRAPHICS_API_OPENGL_33",
.gl_4_3 => return "GRAPHICS_API_OPENGL_43",
.gles_2 => return "GRAPHICS_API_OPENGL_ES2",
.gles_3 => return "GRAPHICS_API_OPENGL_ES3",
}
}
};
pub const LinuxDisplayBackend = enum {
None,
X11,
Wayland,
Both,
};
pub const PlatformBackend = enum {
glfw,
rgfw,
sdl,
sdl2,
sdl3,
memory,
win32,
drm,
android,
};
fn translateCMod(
comptime header: []const u8,
b: *std.Build,
target: std.Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
raylib: *std.Build.Step.Compile,
) void {
const c = b.addTranslateC(.{
.root_source_file = b.path("src/" ++ header ++ ".h"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
const c_mod = c.createModule();
c_mod.linkLibrary(raylib);
b.modules.put(b.graph.arena, header, c_mod) catch @panic("OOM");
}
pub fn build(b: *std.Build) !void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const options: Options = .getOptions(b);
const lib = try compileRaylib(b, target, optimize, options);
lib.installHeader(b.path("src/raylib.h"), "raylib.h");
lib.installHeader(b.path("src/rcamera.h"), "rcamera.h");
lib.installHeader(b.path("src/raymath.h"), "raymath.h");
lib.installHeader(b.path("src/rlgl.h"), "rlgl.h");
b.installArtifact(lib);
translateCMod("raylib", b, target, optimize, lib);
translateCMod("rcamera", b, target, optimize, lib);
translateCMod("raymath", b, target, optimize, lib);
translateCMod("rlgl", b, target, optimize, lib);
if (options.raygui) {
try addRaygui(b, target, optimize, lib);
}
const examples = b.step("examples", "build/install all examples");
examples.dependOn(try addExamples("core", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("audio", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("models", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("shaders", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("shapes", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("text", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("textures", b, target, optimize, lib, options.platform));
examples.dependOn(try addExamples("others", b, target, optimize, lib, options.platform));
}
fn addExamples(
comptime module: []const u8,
b: *std.Build,
target: std.Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
raylib: *std.Build.Step.Compile,
platform: PlatformBackend,
) !*std.Build.Step {
const all = b.step(module, "All " ++ module ++ " examples");
const module_subpath = b.pathJoin(&.{ "examples", module });
var dir = try b.root.openDir(b.graph.io, module_subpath, .{ .iterate = true });
defer dir.close(b.graph.io);
var iter = dir.iterate();
while (try iter.next(b.graph.io)) |entry| {
if (entry.kind != .file) continue;
const filetype = std.fs.path.extension(entry.name);
if (!std.mem.eql(u8, filetype, ".c")) continue;
const filename = std.fs.path.stem(entry.name);
const path = b.pathJoin(&.{ module_subpath, entry.name });
const exe_mod = b.createModule(.{
.target = target,
.optimize = optimize,
.link_libc = true,
});
exe_mod.addCSourceFile(.{ .file = b.path(path) });
exe_mod.linkLibrary(raylib);
if (platform == .sdl) {
exe_mod.linkSystemLibrary("SDL2", .{});
exe_mod.linkSystemLibrary("SDL3", .{});
}
if (platform == .sdl2) {
exe_mod.linkSystemLibrary("SDL2", .{});
}
if (platform == .sdl3) {
exe_mod.linkSystemLibrary("SDL3", .{});
}
if (std.mem.eql(u8, filename, "rlgl_standalone")) {
if (platform != .glfw) continue;
exe_mod.addIncludePath(b.path("src"));
exe_mod.addIncludePath(b.path("src/external/glfw/include"));
}
if (std.mem.eql(u8, filename, "raylib_opengl_interop")) {
if (platform == .drm) continue;
if (target.result.os.tag == .macos) continue;
exe_mod.addIncludePath(b.path("src/external"));
}
const run_step = b.step(filename, filename);
// web exports are completely separate
if (target.query.os_tag == .emscripten) {
exe_mod.addCMacro("PLATFORM_WEB", "");
const wasm = b.addLibrary(.{
.name = b.fmt("{s}.html", .{filename}),
.root_module = exe_mod,
});
const install_dir: std.Build.InstallDir = .{ .custom = b.fmt("web/{s}/{s}", .{ module, filename }) };
const emcc_flags = emsdk.emccDefaultFlags(b.allocator, .{ .optimize = optimize });
const emcc_settings = emsdk.emccDefaultSettings(b.allocator, .{ .optimize = optimize });
const SerialResourceFile = struct { src_path: []const u8, virtual_path: []const u8 };
const EmccExamplesPreloadMap = std.static_string_map.StaticStringMap([]const SerialResourceFile);
const EmccExamplesPreloadSerial = struct { []const u8, []const SerialResourceFile };
const emcc_examples_preloads_serial: []const EmccExamplesPreloadSerial = @import("examples/example_resources.zon");
const emcc_examples_preloads_map = EmccExamplesPreloadMap.initComptime(emcc_examples_preloads_serial);
const preload_paths: ?[]emsdk.ResourceFile = blk: {
if (emcc_examples_preloads_map.get(filename)) |resource_files| {
var rfs = try b.allocator.alloc(emsdk.ResourceFile, resource_files.len);
for (resource_files, 0..) |resource_file, rfidx| {
rfs[rfidx] = .{
.src_path = b.path(resource_file.src_path),
.virtual_path = resource_file.virtual_path,
};
}
break :blk rfs;
} else break :blk null;
};
const emcc_step = try emsdk.emccStep(b, &.{}, &.{ raylib, wasm }, .{
.optimize = optimize,
.flags = emcc_flags,
.settings = emcc_settings,
.preload_paths = preload_paths,
.shell_file_path = b.path("src/shell.html"),
.install_dir = install_dir,
.out_file_name = wasm.name,
});
const emrun_step = try emsdk.emrunStep(
b,
b.graph.path(.install_prefix, b.fmt(
"web/{s}/{s}/{s}",
.{ module, filename, wasm.name },
)),
&.{},
);
emrun_step.dependOn(emcc_step);
run_step.dependOn(emrun_step);
all.dependOn(emcc_step);
} else {
exe_mod.addCMacro("PLATFORM_DESKTOP", "");
const exe = b.addExecutable(.{
.name = filename,
.root_module = exe_mod,
.use_lld = target.result.os.tag == .windows,
});
const install_cmd = b.addInstallArtifact(exe, .{ .dest_sub_path = b.fmt("{s}/{s}", .{ module, filename }) });
const run_cmd = b.addRunArtifact(exe);
run_cmd.cwd = b.path(module_subpath);
run_cmd.step.dependOn(&install_cmd.step);
run_step.dependOn(&run_cmd.step);
all.dependOn(&install_cmd.step);
}
}
return all;
}
fn waylandGenerate(
b: *std.Build,
raylib: *std.Build.Step.Compile,
comptime waylandDir: []const u8,
comptime source: bool,
) !void {
const dir = try b.root.openDir(b.graph.io, waylandDir, .{ .iterate = true });
defer dir.close(b.graph.io);
var iter = dir.iterate();
while (try iter.next(b.graph.io)) |entry| {
if (entry.kind != .file) continue;
const protocolDir = b.pathJoin(&.{ waylandDir, entry.name });
const filename = std.fs.path.stem(entry.name);
const clientHeader = b.fmt("{s}-client-protocol.h", .{filename});
const client_step = b.addSystemCommand(&.{ "wayland-scanner", "client-header" });
client_step.addFileArg(b.path(protocolDir));
raylib.root_module.addIncludePath(client_step.addOutputFileArg(clientHeader).dirname());
raylib.step.dependOn(&client_step.step);
if (comptime source) {
const privateCode = b.fmt("{s}-client-protocol-code.c", .{filename});
const private_step = b.addSystemCommand(&.{ "wayland-scanner", "private-code" });
private_step.addFileArg(b.path(protocolDir));
raylib.root_module.addCSourceFile(.{
.file = private_step.addOutputFileArg(privateCode),
.flags = &.{ "-std=c99", "-O2" },
});
raylib.step.dependOn(&private_step.step);
} else {
const privateCodeHeader = b.fmt("{s}-client-protocol-code.h", .{filename});
const private_head_step = b.addSystemCommand(&.{ "wayland-scanner", "private-code" });
private_head_step.addFileArg(b.path(protocolDir));
raylib.root_module.addIncludePath(private_head_step.addOutputFileArg(privateCodeHeader).dirname());
raylib.step.dependOn(&private_head_step.step);
}
}
}