You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

424 lines
17 KiB

  1. const std = @import("std");
  2. const builtin = @import("builtin");
  3. /// Minimum supported version of Zig
  4. const min_ver = "0.13.0";
  5. comptime {
  6. const order = std.SemanticVersion.order;
  7. const parse = std.SemanticVersion.parse;
  8. if (order(builtin.zig_version, parse(min_ver) catch unreachable) == .lt)
  9. @compileError("Raylib requires zig version " ++ min_ver);
  10. }
  11. fn setDesktopPlatform(raylib: *std.Build.Step.Compile, platform: PlatformBackend) void {
  12. raylib.defineCMacro("PLATFORM_DESKTOP", null);
  13. switch (platform) {
  14. .glfw => raylib.defineCMacro("PLATFORM_DESKTOP_GLFW", null),
  15. .rgfw => raylib.defineCMacro("PLATFORM_DESKTOP_RGFW", null),
  16. .sdl => raylib.defineCMacro("PLATFORM_DESKTOP_SDL", null),
  17. else => {},
  18. }
  19. }
  20. fn createEmsdkStep(b: *std.Build, emsdk: *std.Build.Dependency) *std.Build.Step.Run {
  21. if (builtin.os.tag == .windows) {
  22. return b.addSystemCommand(&.{emsdk.path("emsdk.bat").getPath(b)});
  23. } else {
  24. return b.addSystemCommand(&.{emsdk.path("emsdk").getPath(b)});
  25. }
  26. }
  27. fn emSdkSetupStep(b: *std.Build, emsdk: *std.Build.Dependency) !?*std.Build.Step.Run {
  28. const dot_emsc_path = emsdk.path(".emscripten").getPath(b);
  29. const dot_emsc_exists = !std.meta.isError(std.fs.accessAbsolute(dot_emsc_path, .{}));
  30. if (!dot_emsc_exists) {
  31. const emsdk_install = createEmsdkStep(b, emsdk);
  32. emsdk_install.addArgs(&.{ "install", "latest" });
  33. const emsdk_activate = createEmsdkStep(b, emsdk);
  34. emsdk_activate.addArgs(&.{ "activate", "latest" });
  35. emsdk_activate.step.dependOn(&emsdk_install.step);
  36. return emsdk_activate;
  37. } else {
  38. return null;
  39. }
  40. }
  41. /// A list of all flags from `src/config.h` that one may override
  42. const config_h_flags = outer: {
  43. // Set this value higher if compile errors happen as `src/config.h` gets larger
  44. @setEvalBranchQuota(1 << 20);
  45. const config_h = @embedFile("src/config.h");
  46. var flags: [std.mem.count(u8, config_h, "\n") + 1][]const u8 = undefined;
  47. var i = 0;
  48. var lines = std.mem.tokenizeScalar(u8, config_h, '\n');
  49. while (lines.next()) |line| {
  50. if (!std.mem.containsAtLeast(u8, line, 1, "SUPPORT")) continue;
  51. if (std.mem.startsWith(u8, line, "//")) continue;
  52. if (std.mem.startsWith(u8, line, "#if")) continue;
  53. var flag = std.mem.trimLeft(u8, line, " \t"); // Trim whitespace
  54. flag = flag["#define ".len - 1 ..]; // Remove #define
  55. flag = std.mem.trimLeft(u8, flag, " \t"); // Trim whitespace
  56. flag = flag[0 .. std.mem.indexOf(u8, flag, " ") orelse continue]; // Flag is only one word, so capture till space
  57. flag = "-D" ++ flag; // Prepend with -D
  58. flags[i] = flag;
  59. i += 1;
  60. }
  61. // Uncomment this to check what flags normally get passed
  62. //@compileLog(flags[0..i].*);
  63. break :outer flags[0..i].*;
  64. };
  65. fn compileRaylib(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, options: Options) !*std.Build.Step.Compile {
  66. var raylib_flags_arr = std.ArrayList([]const u8).init(b.allocator);
  67. defer raylib_flags_arr.deinit();
  68. try raylib_flags_arr.appendSlice(&[_][]const u8{
  69. "-std=gnu99",
  70. "-D_GNU_SOURCE",
  71. "-DGL_SILENCE_DEPRECATION=199309L",
  72. "-fno-sanitize=undefined", // https://github.com/raysan5/raylib/issues/3674
  73. });
  74. if (options.shared) {
  75. try raylib_flags_arr.appendSlice(&[_][]const u8{
  76. "-fPIC",
  77. "-DBUILD_LIBTYPE_SHARED",
  78. });
  79. }
  80. if (options.config.len > 0) {
  81. // Sets a flag indiciating the use of a custom `config.h`
  82. try raylib_flags_arr.append("-DEXTERNAL_CONFIG_FLAGS");
  83. // Splits a space-separated list of config flags into multiple flags
  84. //
  85. // Note: This means certain flags like `-x c++` won't be processed properly.
  86. // `-xc++` or similar should be used when possible
  87. var config_iter = std.mem.tokenizeScalar(u8, options.config, ' ');
  88. // Apply config flags supplied by the user
  89. while (config_iter.next()) |config_flag|
  90. try raylib_flags_arr.append(config_flag);
  91. // Apply all relevant configs from `src/config.h` *except* the user-specified ones
  92. //
  93. // Note: Currently using a suboptimal `O(m*n)` time algorithm where:
  94. // `m` corresponds roughly to the number of lines in `src/config.h`
  95. // `n` corresponds to the number of user-specified flags
  96. outer: for (config_h_flags) |flag| {
  97. // If a user already specified the flag, skip it
  98. config_iter.reset();
  99. while (config_iter.next()) |config_flag| {
  100. // For a user-specified flag to match, it must share the same prefix and have the
  101. // same length or be followed by an equals sign
  102. if (!std.mem.startsWith(u8, config_flag, flag)) continue;
  103. if (config_flag.len == flag.len or config_flag[flag.len] == '=') continue :outer;
  104. }
  105. // Otherwise, append default value from config.h to compile flags
  106. try raylib_flags_arr.append(flag);
  107. }
  108. }
  109. const raylib = if (options.shared)
  110. b.addSharedLibrary(.{
  111. .name = "raylib",
  112. .target = target,
  113. .optimize = optimize,
  114. })
  115. else
  116. b.addStaticLibrary(.{
  117. .name = "raylib",
  118. .target = target,
  119. .optimize = optimize,
  120. });
  121. raylib.linkLibC();
  122. // No GLFW required on PLATFORM_DRM
  123. if (options.platform != .drm) {
  124. raylib.addIncludePath(b.path("src/external/glfw/include"));
  125. }
  126. var c_source_files = try std.ArrayList([]const u8).initCapacity(b.allocator, 2);
  127. c_source_files.appendSliceAssumeCapacity(&.{ "src/rcore.c", "src/utils.c" });
  128. if (options.raudio) {
  129. try c_source_files.append("src/raudio.c");
  130. }
  131. if (options.rmodels) {
  132. try c_source_files.append("src/rmodels.c");
  133. }
  134. if (options.rshapes) {
  135. try c_source_files.append("src/rshapes.c");
  136. }
  137. if (options.rtext) {
  138. try c_source_files.append("src/rtext.c");
  139. }
  140. if (options.rtextures) {
  141. try c_source_files.append("src/rtextures.c");
  142. }
  143. if (options.opengl_version != .auto) {
  144. raylib.defineCMacro(options.opengl_version.toCMacroStr(), null);
  145. }
  146. switch (target.result.os.tag) {
  147. .windows => {
  148. try c_source_files.append("src/rglfw.c");
  149. raylib.linkSystemLibrary("winmm");
  150. raylib.linkSystemLibrary("gdi32");
  151. raylib.linkSystemLibrary("opengl32");
  152. setDesktopPlatform(raylib, options.platform);
  153. },
  154. .linux => {
  155. if (options.platform != .drm) {
  156. try c_source_files.append("src/rglfw.c");
  157. if (options.linux_display_backend == .X11 or options.linux_display_backend == .Both) {
  158. raylib.defineCMacro("_GLFW_X11", null);
  159. raylib.linkSystemLibrary("GLX");
  160. raylib.linkSystemLibrary("X11");
  161. raylib.linkSystemLibrary("Xcursor");
  162. raylib.linkSystemLibrary("Xext");
  163. raylib.linkSystemLibrary("Xfixes");
  164. raylib.linkSystemLibrary("Xi");
  165. raylib.linkSystemLibrary("Xinerama");
  166. raylib.linkSystemLibrary("Xrandr");
  167. raylib.linkSystemLibrary("Xrender");
  168. }
  169. if (options.linux_display_backend == .Wayland or options.linux_display_backend == .Both) {
  170. _ = b.findProgram(&.{"wayland-scanner"}, &.{}) catch {
  171. std.log.err(
  172. \\ `wayland-scanner` may not be installed on the system.
  173. \\ You can switch to X11 in your `build.zig` by changing `Options.linux_display_backend`
  174. , .{});
  175. @panic("`wayland-scanner` not found");
  176. };
  177. raylib.defineCMacro("_GLFW_WAYLAND", null);
  178. raylib.linkSystemLibrary("EGL");
  179. raylib.linkSystemLibrary("wayland-client");
  180. raylib.linkSystemLibrary("xkbcommon");
  181. waylandGenerate(b, raylib, "wayland.xml", "wayland-client-protocol");
  182. waylandGenerate(b, raylib, "xdg-shell.xml", "xdg-shell-client-protocol");
  183. waylandGenerate(b, raylib, "xdg-decoration-unstable-v1.xml", "xdg-decoration-unstable-v1-client-protocol");
  184. waylandGenerate(b, raylib, "viewporter.xml", "viewporter-client-protocol");
  185. waylandGenerate(b, raylib, "relative-pointer-unstable-v1.xml", "relative-pointer-unstable-v1-client-protocol");
  186. waylandGenerate(b, raylib, "pointer-constraints-unstable-v1.xml", "pointer-constraints-unstable-v1-client-protocol");
  187. waylandGenerate(b, raylib, "fractional-scale-v1.xml", "fractional-scale-v1-client-protocol");
  188. waylandGenerate(b, raylib, "xdg-activation-v1.xml", "xdg-activation-v1-client-protocol");
  189. waylandGenerate(b, raylib, "idle-inhibit-unstable-v1.xml", "idle-inhibit-unstable-v1-client-protocol");
  190. }
  191. setDesktopPlatform(raylib, options.platform);
  192. } else {
  193. if (options.opengl_version == .auto) {
  194. raylib.linkSystemLibrary("GLESv2");
  195. raylib.defineCMacro("GRAPHICS_API_OPENGL_ES2", null);
  196. }
  197. raylib.linkSystemLibrary("EGL");
  198. raylib.linkSystemLibrary("gbm");
  199. raylib.linkSystemLibrary2("libdrm", .{ .use_pkg_config = .force });
  200. raylib.defineCMacro("PLATFORM_DRM", null);
  201. raylib.defineCMacro("EGL_NO_X11", null);
  202. raylib.defineCMacro("DEFAULT_BATCH_BUFFER_ELEMENT", "2048");
  203. }
  204. },
  205. .freebsd, .openbsd, .netbsd, .dragonfly => {
  206. try c_source_files.append("rglfw.c");
  207. raylib.linkSystemLibrary("GL");
  208. raylib.linkSystemLibrary("rt");
  209. raylib.linkSystemLibrary("dl");
  210. raylib.linkSystemLibrary("m");
  211. raylib.linkSystemLibrary("X11");
  212. raylib.linkSystemLibrary("Xrandr");
  213. raylib.linkSystemLibrary("Xinerama");
  214. raylib.linkSystemLibrary("Xi");
  215. raylib.linkSystemLibrary("Xxf86vm");
  216. raylib.linkSystemLibrary("Xcursor");
  217. setDesktopPlatform(raylib, options.platform);
  218. },
  219. .macos => {
  220. // Include xcode_frameworks for cross compilation
  221. if (b.lazyDependency("xcode_frameworks", .{})) |dep| {
  222. raylib.addSystemFrameworkPath(dep.path("Frameworks"));
  223. raylib.addSystemIncludePath(dep.path("include"));
  224. raylib.addLibraryPath(dep.path("lib"));
  225. }
  226. // On macos rglfw.c include Objective-C files.
  227. try raylib_flags_arr.append("-ObjC");
  228. raylib.root_module.addCSourceFile(.{
  229. .file = b.path("src/rglfw.c"),
  230. .flags = raylib_flags_arr.items,
  231. });
  232. _ = raylib_flags_arr.pop();
  233. raylib.linkFramework("Foundation");
  234. raylib.linkFramework("CoreServices");
  235. raylib.linkFramework("CoreGraphics");
  236. raylib.linkFramework("AppKit");
  237. raylib.linkFramework("IOKit");
  238. setDesktopPlatform(raylib, options.platform);
  239. },
  240. .emscripten => {
  241. // Include emscripten for cross compilation
  242. if (b.lazyDependency("emsdk", .{})) |dep| {
  243. if (try emSdkSetupStep(b, dep)) |emSdkStep| {
  244. raylib.step.dependOn(&emSdkStep.step);
  245. }
  246. raylib.addIncludePath(dep.path("upstream/emscripten/cache/sysroot/include"));
  247. }
  248. raylib.defineCMacro("PLATFORM_WEB", null);
  249. if (options.opengl_version == .auto) {
  250. raylib.defineCMacro("GRAPHICS_API_OPENGL_ES2", null);
  251. }
  252. },
  253. else => {
  254. @panic("Unsupported OS");
  255. },
  256. }
  257. raylib.root_module.addCSourceFiles(.{
  258. .files = c_source_files.items,
  259. .flags = raylib_flags_arr.items,
  260. });
  261. return raylib;
  262. }
  263. pub fn addRaygui(b: *std.Build, raylib: *std.Build.Step.Compile, raygui_dep: *std.Build.Dependency) void {
  264. const raylib_dep = b.dependencyFromBuildZig(@This(), .{});
  265. var gen_step = b.addWriteFiles();
  266. raylib.step.dependOn(&gen_step.step);
  267. const raygui_c_path = gen_step.add("raygui.c", "#define RAYGUI_IMPLEMENTATION\n#include \"raygui.h\"\n");
  268. raylib.addCSourceFile(.{ .file = raygui_c_path });
  269. raylib.addIncludePath(raygui_dep.path("src"));
  270. raylib.addIncludePath(raylib_dep.path("src"));
  271. raylib.installHeader(raygui_dep.path("src/raygui.h"), "raygui.h");
  272. }
  273. pub const Options = struct {
  274. raudio: bool = true,
  275. rmodels: bool = true,
  276. rshapes: bool = true,
  277. rtext: bool = true,
  278. rtextures: bool = true,
  279. platform: PlatformBackend = .glfw,
  280. shared: bool = false,
  281. linux_display_backend: LinuxDisplayBackend = .Both,
  282. opengl_version: OpenglVersion = .auto,
  283. /// config should be a list of space-separated cflags, eg, "-DSUPPORT_CUSTOM_FRAME_CONTROL"
  284. config: []const u8 = &.{},
  285. const defaults = Options{};
  286. fn getOptions(b: *std.Build) Options {
  287. return .{
  288. .platform = b.option(PlatformBackend, "platform", "Choose the platform backedn for desktop target") orelse defaults.platform,
  289. .raudio = b.option(bool, "raudio", "Compile with audio support") orelse defaults.raudio,
  290. .rmodels = b.option(bool, "rmodels", "Compile with models support") orelse defaults.rmodels,
  291. .rtext = b.option(bool, "rtext", "Compile with text support") orelse defaults.rtext,
  292. .rtextures = b.option(bool, "rtextures", "Compile with textures support") orelse defaults.rtextures,
  293. .rshapes = b.option(bool, "rshapes", "Compile with shapes support") orelse defaults.rshapes,
  294. .shared = b.option(bool, "shared", "Compile as shared library") orelse defaults.shared,
  295. .linux_display_backend = b.option(LinuxDisplayBackend, "linux_display_backend", "Linux display backend to use") orelse defaults.linux_display_backend,
  296. .opengl_version = b.option(OpenglVersion, "opengl_version", "OpenGL version to use") orelse defaults.opengl_version,
  297. .config = b.option([]const u8, "config", "Compile with custom define macros overriding config.h") orelse &.{},
  298. };
  299. }
  300. };
  301. pub const OpenglVersion = enum {
  302. auto,
  303. gl_1_1,
  304. gl_2_1,
  305. gl_3_3,
  306. gl_4_3,
  307. gles_2,
  308. gles_3,
  309. pub fn toCMacroStr(self: @This()) []const u8 {
  310. switch (self) {
  311. .auto => @panic("OpenglVersion.auto cannot be turned into a C macro string"),
  312. .gl_1_1 => return "GRAPHICS_API_OPENGL_11",
  313. .gl_2_1 => return "GRAPHICS_API_OPENGL_21",
  314. .gl_3_3 => return "GRAPHICS_API_OPENGL_33",
  315. .gl_4_3 => return "GRAPHICS_API_OPENGL_43",
  316. .gles_2 => return "GRAPHICS_API_OPENGL_ES2",
  317. .gles_3 => return "GRAPHICS_API_OPENGL_ES3",
  318. }
  319. }
  320. };
  321. pub const LinuxDisplayBackend = enum {
  322. X11,
  323. Wayland,
  324. Both,
  325. };
  326. pub const PlatformBackend = enum {
  327. glfw,
  328. rgfw,
  329. sdl,
  330. drm,
  331. };
  332. pub fn build(b: *std.Build) !void {
  333. // Standard target options allows the person running `zig build` to choose
  334. // what target to build for. Here we do not override the defaults, which
  335. // means any target is allowed, and the default is native. Other options
  336. // for restricting supported target set are available.
  337. const target = b.standardTargetOptions(.{});
  338. // Standard optimization options allow the person running `zig build` to select
  339. // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
  340. // set a preferred release mode, allowing the user to decide how to optimize.
  341. const optimize = b.standardOptimizeOption(.{});
  342. const lib = try compileRaylib(b, target, optimize, Options.getOptions(b));
  343. lib.installHeader(b.path("src/raylib.h"), "raylib.h");
  344. lib.installHeader(b.path("src/raymath.h"), "raymath.h");
  345. lib.installHeader(b.path("src/rlgl.h"), "rlgl.h");
  346. b.installArtifact(lib);
  347. }
  348. fn waylandGenerate(
  349. b: *std.Build,
  350. raylib: *std.Build.Step.Compile,
  351. comptime protocol: []const u8,
  352. comptime basename: []const u8,
  353. ) void {
  354. const waylandDir = "src/external/glfw/deps/wayland";
  355. const protocolDir = b.pathJoin(&.{ waylandDir, protocol });
  356. const clientHeader = basename ++ ".h";
  357. const privateCode = basename ++ "-code.h";
  358. const client_step = b.addSystemCommand(&.{ "wayland-scanner", "client-header" });
  359. client_step.addFileArg(b.path(protocolDir));
  360. raylib.addIncludePath(client_step.addOutputFileArg(clientHeader).dirname());
  361. const private_step = b.addSystemCommand(&.{ "wayland-scanner", "private-code" });
  362. private_step.addFileArg(b.path(protocolDir));
  363. raylib.addIncludePath(private_step.addOutputFileArg(privateCode).dirname());
  364. raylib.step.dependOn(&client_step.step);
  365. raylib.step.dependOn(&private_step.step);
  366. }