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.

431 lines
18 KiB

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