-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.zig
567 lines (531 loc) · 19.5 KB
/
build.zig
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
const std = @import("std");
const builtin = @import("builtin");
const Build = std.Build;
const OptimizeMode = std.builtin.OptimizeMode;
const examples_dir = "examples";
const sokol_tools_bin_dir = "../SDK-Sokols/sokol-tools-bin/bin/";
const shaders_dir = "src/shaders";
const libs_dir = "libs";
const web_dir = "libs/web";
const user_h_dirs = .{
//"libs/Nuklear"
};
const user_c_files = .{
//"libs/Nuklear/nuklear.c",
};
const main_shaders = .{
"main.glsl",
};
// the integrated examples
const examples = .{
"clear",
"triangle",
"quad",
"cube",
"bufferoffsets",
"noninterleaved",
"texcube",
"shapes",
"shapes-transform",
"offscreen",
"offscreen-msaa",
//"nuklear",
//"instancing",
//"mrt",
//"mrt-pixelformats",
//"arraytex",
//"tex3d",
//"dyntex",
//"basisu",
//"cubemap-jpeg",
//"cubemaprt",
//"miprender",
//"layerrender",
//"primtypes",
//"uvwrap",
//"mipmap",
//"uniformtypes",
//"blend",
//"sdf",
//"shadows",
//"shadows-depthtex",
//"imgui",
//"imgui-dock",
//"imgui-highdpi",
//"cimgui",
//"imgui-images",
//"imgui-usercallback",
//"nuklear-images",
//"sgl-microui",
//"fontstash",
//"fontstash-layers",
//"debugtext",
//"debugtext-printf",
//"debugtext-userfont",
//"debugtext-context",
//"debugtext-layers",
//"events",
//"icon",
//"droptest",
//"pixelformats",
//"drawcallperf",
//"saudio",
//"modplay",
//"noentry",
//"restart",
//"sgl",
//"sgl-lines",
//"sgl-points",
//"sgl-context",
//"loadpng",
//"plmpeg",
//"cgltf",
//"ozz-anim",
//"ozz-skin",
//"shdfeatures",
//"spine-simple",
//"spine-inspector",
//"spine-layers",
//"spine-skinsets",
//"spine-switch-skinsets",
//"spine-contexts",
};
pub const SokolBackend = enum {
auto, // Windows: D3D11, macOS/iOS: Metal, otherwise: GL
d3d11,
metal,
gl,
gles3,
wgpu,
};
var main_dir: []const u8 = undefined;
var sokolc: *std.Build.Dependency = undefined;
pub fn build(b: *Build) !void {
const opt_use_gl = b.option(bool, "gl", "Force OpenGL (default: false)") orelse false;
const opt_use_wgpu = b.option(bool, "wgpu", "Force WebGPU (default: false, web only)") orelse false;
const opt_use_x11 = b.option(bool, "x11", "Force X11 (default: true, Linux only)") orelse true;
const opt_use_wayland = b.option(bool, "wayland", "Force Wayland (default: false, Linux only, not supported in main-line headers)") orelse false;
const opt_use_egl = b.option(bool, "egl", "Force EGL (default: false, Linux only)") orelse false;
const sokol_backend: SokolBackend = if (opt_use_gl) .gl else if (opt_use_wgpu) .wgpu else .auto;
const opt_build_example = b.option(bool, "example", "Build example") orelse false;
main_dir = if(opt_build_example) examples_dir else "src";
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const emsdk = b.dependency("emsdk", .{});
sokolc = b.dependency("sokolc", .{
.optimize = optimize,
});
// a module for the actual bindings, and a static link library with the C code
const mod_sokol = b.addModule("sokol", .{ .root_source_file = .{ .path = "" } });
const lib_sokol = try buildLibSokol(b, .{
.target = target,
.optimize = optimize,
.backend = sokol_backend,
.use_wayland = opt_use_wayland,
.use_x11 = opt_use_x11,
.use_egl = opt_use_egl,
.emsdk = emsdk,
});
mod_sokol.linkLibrary(lib_sokol);
if(!opt_build_example) {
try buildExample(b, "src", "main", .{
.target = target,
.optimize = optimize,
.backend = sokol_backend,
.mod_sokol = mod_sokol,
.emsdk = emsdk,
});
// a manually invoked build step to recompile shaders via sokol-shdc
inline for (main_shaders) |name| {
buildShader(b, shaders_dir, name);
}
} else {
inline for (examples) |name| {
try buildExample(b, examples_dir, name, .{
.target = target,
.optimize = optimize,
.backend = sokol_backend,
.mod_sokol = mod_sokol,
.emsdk = emsdk,
});
const f = std.fs.cwd().openFile(examples_dir ++ "/shaders/" ++ name ++ ".glsl", .{.mode = .read_only}) catch null;
if(f != null) {
buildShader(b, examples_dir ++ "/shaders", name ++ ".glsl");
f.?.close();
}
}
}
}
// build one of the examples
const ExampleOptions = struct {
target: Build.ResolvedTarget,
optimize: OptimizeMode,
backend: SokolBackend,
mod_sokol: *Build.Module,
emsdk: *Build.Dependency,
};
fn buildExample(b: *Build, comptime dir: []const u8, comptime name: []const u8, options: ExampleOptions) !void {
const main_src = dir ++ "/" ++ name ++ ".zig";
var run: ?*Build.Step.Run = null;
if (!options.target.result.isWasm()) {
// for native platforms, build into a regular executable
const example = b.addExecutable(.{
.name = name,
.root_source_file = .{ .path = main_src },
.target = options.target,
.optimize = options.optimize,
});
example.root_module.addImport("sokol", options.mod_sokol);
example.addIncludePath(sokolc.path(""));
example.addIncludePath(sokolc.path("util"));
example.addIncludePath(.{.path = libs_dir});
example.addIncludePath(.{.path = shaders_dir});
example.addIncludePath(.{.path = main_dir});
inline for(user_h_dirs) |dd| {
if(dd.len > 0) example.addIncludePath(.{.path = dd});
}
b.installArtifact(example);
run = b.addRunArtifact(example);
} else {
// for WASM, need to build the Zig code as static library, since linking happens via emcc
const example = b.addStaticLibrary(.{
.name = name,
.root_source_file = .{ .path = main_src },
.target = options.target,
.optimize = options.optimize,
});
example.root_module.addImport("sokol", options.mod_sokol);
// create a special emcc linker run step
const backend = resolveSokolBackend(options.backend, options.target.result);
const link_step = try emLinkStep(b, .{
.lib_main = example,
.target = options.target,
.optimize = options.optimize,
.emsdk = options.emsdk,
.use_webgpu = backend == .wgpu,
.use_webgl2 = backend != .wgpu,
.use_emmalloc = true,
.use_filesystem = false,
// NOTE: when sokol-zig is used as package, this path needs to be absolute!
.shell_file_path = web_dir ++ "/shell.html",
});
// ...and a special run step to run the build result via emrun
run = emRunStep(b, .{ .name = name, .emsdk = options.emsdk });
run.?.step.dependOn(&link_step.step);
}
if(std.mem.eql(u8, name, "main")) {
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run.?.step);
} else {
//b.step("run-" ++ name, "Run " ++ name).dependOn(&run.?.step);
b.step(name, "Run example/" ++ name).dependOn(&run.?.step);
}
}
// helper function to resolve .auto backend based on target platform
pub fn resolveSokolBackend(backend: SokolBackend, target: std.Target) SokolBackend {
if (backend != .auto) {
return backend;
} else if (target.isDarwin()) {
return .metal;
} else if (target.os.tag == .windows) {
return .d3d11;
} else if (target.isWasm()) {
return .gles3;
} else if (target.isAndroid()) {
return .gles3;
} else {
return .gl;
}
}
// build the sokol C headers into a static library
pub const LibSokolOptions = struct {
target: Build.ResolvedTarget,
optimize: OptimizeMode,
backend: SokolBackend = .auto,
use_egl: bool = false,
use_x11: bool = true,
use_wayland: bool = false,
emsdk: ?*Build.Dependency = null,
};
pub fn buildLibSokol(b: *Build, options: LibSokolOptions) !*Build.Step.Compile {
const lib = b.addStaticLibrary(.{
.name = "sokol",
.target = options.target,
.optimize = options.optimize,
.link_libc = true,
});
if (options.target.result.isWasm()) {
// make sure we're building for the wasm32-emscripten target, not wasm32-freestanding
if (lib.rootModuleTarget().os.tag != .emscripten) {
std.log.err("Please build with 'zig build -Dtarget=wasm32-emscripten", .{});
return error.Wasm32EmscriptenExpected;
}
// one-time setup of Emscripten SDK
if (try emSdkSetupStep(b, options.emsdk.?)) |emsdk_setup| {
lib.step.dependOn(&emsdk_setup.step);
}
// add the Emscripten system include seach path
const emsdk_sysroot = b.pathJoin(&.{ emSdkPath(b, options.emsdk.?), "upstream", "emscripten", "cache", "sysroot" });
const include_path = b.pathJoin(&.{ emsdk_sysroot, "include" });
lib.addSystemIncludePath(.{ .path = include_path });
}
// resolve .auto backend into specific backend by platform
const backend = resolveSokolBackend(options.backend, lib.rootModuleTarget());
const backend_cflags = switch (backend) {
.d3d11 => "-DSOKOL_D3D11",
.metal => "-DSOKOL_METAL",
.gl => "-DSOKOL_GLCORE33",
.gles3 => "-DSOKOL_GLES3",
.wgpu => "-DSOKOL_WGPU",
else => @panic("unknown sokol backend"),
};
// platform specific compile and link options
var cflags: []const []const u8 = &.{ "-DIMPL", backend_cflags };
if (lib.rootModuleTarget().isDarwin()) {
cflags = &.{ "-ObjC", "-DIMPL", backend_cflags };
lib.linkFramework("Foundation");
lib.linkFramework("AudioToolbox");
if (.metal == backend) {
lib.linkFramework("MetalKit");
lib.linkFramework("Metal");
}
if (lib.rootModuleTarget().os.tag == .ios) {
lib.linkFramework("UIKit");
lib.linkFramework("AVFoundation");
if (.gl == backend) {
lib.linkFramework("OpenGLES");
lib.linkFramework("GLKit");
}
} else if (lib.rootModuleTarget().os.tag == .macos) {
lib.linkFramework("Cocoa");
lib.linkFramework("QuartzCore");
if (.gl == backend) {
lib.linkFramework("OpenGL");
}
}
} else if (lib.rootModuleTarget().isAndroid()) {
if (.gles3 != backend) {
@panic("For android targets, you must have backend set to GLES3");
}
lib.linkSystemLibrary("GLESv3");
lib.linkSystemLibrary("EGL");
lib.linkSystemLibrary("android");
lib.linkSystemLibrary("log");
} else if (lib.rootModuleTarget().os.tag == .linux) {
const egl_cflags = if (options.use_egl) "-DSOKOL_FORCE_EGL " else "";
const x11_cflags = if (!options.use_x11) "-DSOKOL_DISABLE_X11 " else "";
const wayland_cflags = if (!options.use_wayland) "-DSOKOL_DISABLE_WAYLAND" else "";
const link_egl = options.use_egl or options.use_wayland;
cflags = &.{ "-DIMPL", backend_cflags, egl_cflags, x11_cflags, wayland_cflags };
lib.linkSystemLibrary("asound");
lib.linkSystemLibrary("GL");
if (options.use_x11) {
lib.linkSystemLibrary("X11");
lib.linkSystemLibrary("Xi");
lib.linkSystemLibrary("Xcursor");
}
if (options.use_wayland) {
lib.linkSystemLibrary("wayland-client");
lib.linkSystemLibrary("wayland-cursor");
lib.linkSystemLibrary("wayland-egl");
lib.linkSystemLibrary("xkbcommon");
}
if (link_egl) {
lib.linkSystemLibrary("egl");
}
} else if (lib.rootModuleTarget().os.tag == .windows) {
lib.linkSystemLibrary("kernel32");
lib.linkSystemLibrary("user32");
lib.linkSystemLibrary("gdi32");
lib.linkSystemLibrary("ole32");
if (.d3d11 == backend) {
lib.linkSystemLibrary("d3d11");
lib.linkSystemLibrary("dxgi");
}
}
// finally add the C source files
lib.addIncludePath(sokolc.path(""));
lib.addIncludePath(sokolc.path("util"));
lib.addIncludePath(.{.path = libs_dir});
lib.addIncludePath(.{.path = shaders_dir});
lib.addIncludePath(.{.path = main_dir});
lib.addCSourceFile(.{
.file = if (lib.rootModuleTarget().os.tag == .macos)
.{.path = libs_dir ++ "/sokol.m"}
else .{ .path = libs_dir ++ "/sokol.c" },
.flags = &.{
"-std=c99",
"-fno-sanitize=undefined",
},
});
inline for(user_h_dirs) |dd| {
if(dd.len > 0) lib.addIncludePath(.{.path = dd});
}
inline for(user_c_files) |ff| {
if(ff.len < 3) continue;
lib.addCSourceFile(.{
.file = .{.path = ff},
});
}
return lib;
}
// for wasm32-emscripten, need to run the Emscripten linker from the Emscripten SDK
// NOTE: ideally this would go into a separate emsdk-zig package
pub const EmLinkOptions = struct {
target: Build.ResolvedTarget,
optimize: OptimizeMode,
lib_main: *Build.Step.Compile, // the actual Zig code must be compiled to a static link library
emsdk: *Build.Dependency,
release_use_closure: bool = true,
release_use_lto: bool = true,
use_webgpu: bool = false,
use_webgl2: bool = false,
use_emmalloc: bool = false,
use_filesystem: bool = true,
shell_file_path: ?[]const u8 = null,
extra_args: []const []const u8 = &.{},
};
pub fn emLinkStep(b: *Build, options: EmLinkOptions) !*Build.Step.Run {
const emcc_path = b.findProgram(&.{"emcc"}, &.{}) catch b.pathJoin(&.{ emSdkPath(b, options.emsdk), "upstream", "emscripten", "emcc" });
// create a separate output directory zig-out/web
try std.fs.cwd().makePath(b.fmt("{s}/web", .{b.install_path}));
var emcc_cmd = std.ArrayList([]const u8).init(b.allocator);
defer emcc_cmd.deinit();
try emcc_cmd.append(emcc_path);
if (options.optimize == .Debug) {
try emcc_cmd.append("-Og");
try emcc_cmd.append("-sSAFE_HEAP=1");
try emcc_cmd.append("-sSTACK_OVERFLOW_CHECK=1");
} else {
try emcc_cmd.append("-sASSERTIONS=0");
if (options.optimize == .ReleaseSmall) {
try emcc_cmd.append("-Oz");
} else {
try emcc_cmd.append("-O3");
}
if (options.release_use_lto) {
try emcc_cmd.append("-flto");
}
if (options.release_use_closure) {
try emcc_cmd.append("--closure");
try emcc_cmd.append("1");
}
}
if (options.use_webgpu) {
try emcc_cmd.append("-sUSE_WEBGPU=1");
}
if (options.use_webgl2) {
try emcc_cmd.append("-sUSE_WEBGL2=1");
}
if (!options.use_filesystem) {
try emcc_cmd.append("-sNO_FILESYSTEM=1");
}
if (options.use_emmalloc) {
try emcc_cmd.append("-sMALLOC='emmalloc'");
}
if (options.shell_file_path) |shell_file_path| {
try emcc_cmd.append(b.fmt("--shell-file={s}", .{shell_file_path}));
}
try emcc_cmd.append(b.fmt("-o{s}/web/{s}.html", .{ b.install_path, options.lib_main.name }));
for (options.extra_args) |arg| {
try emcc_cmd.append(arg);
}
const emcc = b.addSystemCommand(emcc_cmd.items);
emcc.setName("emcc"); // hide emcc path
// add the main lib, and then scan for library dependencies and add those too
emcc.addArtifactArg(options.lib_main);
var it = options.lib_main.root_module.iterateDependencies(options.lib_main, false);
while (it.next()) |item| {
for (item.module.link_objects.items) |link_object| {
switch (link_object) {
.other_step => |compile_step| {
switch (compile_step.kind) {
.lib => {
emcc.addArtifactArg(compile_step);
},
else => {},
}
},
else => {},
}
}
}
// get the emcc step to run on 'zig build'
b.getInstallStep().dependOn(&emcc.step);
return emcc;
}
// build a run step which uses the emsdk emrun command to run a build target in the browser
// NOTE: ideally this would go into a separate emsdk-zig package
pub const EmRunOptions = struct {
name: []const u8,
emsdk: *Build.Dependency,
};
pub fn emRunStep(b: *Build, options: EmRunOptions) *Build.Step.Run {
const emrun_path = b.findProgram(&.{"emrun"}, &.{}) catch b.pathJoin(&.{ emSdkPath(b, options.emsdk), "upstream", "emscripten", "emrun" });
const emrun = b.addSystemCommand(&.{ emrun_path, b.fmt("{s}/web/{s}.html", .{ b.install_path, options.name }) });
return emrun;
}
// helper function to extract emsdk path from the emsdk package dependency
fn emSdkPath(b: *Build, emsdk: *Build.Dependency) []const u8 {
return emsdk.path("").getPath(b);
}
// One-time setup of the Emscripten SDK (runs 'emsdk install + activate'). If the
// SDK had to be setup, a run step will be returned which should be added
// as dependency to the sokol library (since this needs the emsdk in place),
// if the emsdk was already setup, null will be returned.
// NOTE: ideally this would go into a separate emsdk-zig package
fn emSdkSetupStep(b: *Build, emsdk: *Build.Dependency) !?*Build.Step.Run {
const emsdk_path = emSdkPath(b, emsdk);
const dot_emsc_path = b.pathJoin(&.{ emsdk_path, ".emscripten" });
const dot_emsc_exists = !std.meta.isError(std.fs.accessAbsolute(dot_emsc_path, .{}));
if (!dot_emsc_exists) {
var cmd = std.ArrayList([]const u8).init(b.allocator);
defer cmd.deinit();
if (builtin.os.tag == .windows)
try cmd.append(b.pathJoin(&.{ emsdk_path, "emsdk.bat" }))
else {
try cmd.append("bash"); // or try chmod
try cmd.append(b.pathJoin(&.{ emsdk_path, "emsdk" }));
}
const emsdk_install = b.addSystemCommand(cmd.items);
emsdk_install.addArgs(&.{ "install", "latest" });
const emsdk_activate = b.addSystemCommand(cmd.items);
emsdk_activate.addArgs(&.{ "activate", "latest" });
emsdk_activate.step.dependOn(&emsdk_install.step);
return emsdk_activate;
} else {
return null;
}
}
// a separate step to compile shaders, expects the shader compiler in ../sokol-tools-bin/
// TODO: install sokol-shdc via package manager
var shdc_step: ?*std.Build.Step = null;
fn buildShader(b: *Build, comptime dir: []const u8, comptime shader: []const u8) void {
const optional_shdc: ?[:0]const u8 = comptime switch (builtin.os.tag) {
.windows => "win32/sokol-shdc.exe",
.linux => "linux/sokol-shdc",
.macos => if (builtin.cpu.arch.isX86()) "osx/sokol-shdc" else "osx_arm64/sokol-shdc",
else => null,
};
if (optional_shdc == null) {
std.log.warn("unsupported host platform, skipping shader compiler step", .{});
return;
}
const shdc_path = sokol_tools_bin_dir ++ optional_shdc.?;
if(shdc_step == null) {
shdc_step = b.step("shaders", "Compile shaders (needs " ++ sokol_tools_bin_dir ++ ")");
}
const cmd = b.addSystemCommand(&.{
shdc_path,
"-i",
dir ++ "/" ++ shader,
"-o",
dir ++ "/" ++ shader ++ ".h",
"-l",
"glsl330:metal_macos:hlsl4:glsl300es:wgsl",
"-f",
"sokol",
//"sokol_zig",
});
shdc_step.?.dependOn(&cmd.step);
}