From 47936cc7f936903fdf4194030447614192c5012f Mon Sep 17 00:00:00 2001 From: Stephen Gutekanst Date: Sat, 8 Jul 2023 14:34:59 -0700 Subject: [PATCH] core: move to github.com/hexops/mach-core Signed-off-by: Stephen Gutekanst --- libs/core/.gitattributes | 2 - libs/core/.github/FUNDING.yml | 1 - libs/core/.github/pull_request_template.md | 5 - libs/core/.github/workflows/ci.yml | 79 -- libs/core/.gitignore | 18 - libs/core/LICENSE | 13 - libs/core/LICENSE-APACHE | 202 ----- libs/core/LICENSE-MIT | 25 - libs/core/README.md | 54 -- libs/core/build.zig | 273 ------ libs/core/build.zig.zon | 38 - libs/core/include/libmachcore.h | 37 - libs/core/libs/mach-glfw | 1 - libs/core/libs/mach-gpu | 1 - libs/core/libs/mach-gpu-dawn | 1 - libs/core/src/Core.zig | 418 --------- libs/core/src/Timer.zig | 38 - libs/core/src/entry.zig | 43 - libs/core/src/main.zig | 11 - libs/core/src/platform.zig | 63 -- libs/core/src/platform/libmachcore.zig | 82 -- libs/core/src/platform/libmachcore_app.zig | 1 - libs/core/src/platform/native.zig | 4 - libs/core/src/platform/native/Core.zig | 811 ------------------ libs/core/src/platform/native/entry.zig | 35 - .../core/src/platform/native/objc_message.zig | 7 - libs/core/src/platform/native/util.zig | 187 ---- libs/core/src/platform/wasm.zig | 2 - libs/core/src/platform/wasm/Core.zig | 307 ------- libs/core/src/platform/wasm/Timer.zig | 25 - libs/core/src/platform/wasm/entry.zig | 64 -- libs/core/src/platform/wasm/js.zig | 40 - libs/core/src/platform/wasm/mach.js | 515 ----------- 33 files changed, 3403 deletions(-) delete mode 100644 libs/core/.gitattributes delete mode 100644 libs/core/.github/FUNDING.yml delete mode 100644 libs/core/.github/pull_request_template.md delete mode 100644 libs/core/.github/workflows/ci.yml delete mode 100644 libs/core/.gitignore delete mode 100644 libs/core/LICENSE delete mode 100644 libs/core/LICENSE-APACHE delete mode 100644 libs/core/LICENSE-MIT delete mode 100644 libs/core/README.md delete mode 100644 libs/core/build.zig delete mode 100644 libs/core/build.zig.zon delete mode 100644 libs/core/include/libmachcore.h delete mode 120000 libs/core/libs/mach-glfw delete mode 120000 libs/core/libs/mach-gpu delete mode 120000 libs/core/libs/mach-gpu-dawn delete mode 100644 libs/core/src/Core.zig delete mode 100644 libs/core/src/Timer.zig delete mode 100644 libs/core/src/entry.zig delete mode 100644 libs/core/src/main.zig delete mode 100644 libs/core/src/platform.zig delete mode 100644 libs/core/src/platform/libmachcore.zig delete mode 100644 libs/core/src/platform/libmachcore_app.zig delete mode 100644 libs/core/src/platform/native.zig delete mode 100644 libs/core/src/platform/native/Core.zig delete mode 100644 libs/core/src/platform/native/entry.zig delete mode 100644 libs/core/src/platform/native/objc_message.zig delete mode 100644 libs/core/src/platform/native/util.zig delete mode 100644 libs/core/src/platform/wasm.zig delete mode 100644 libs/core/src/platform/wasm/Core.zig delete mode 100644 libs/core/src/platform/wasm/Timer.zig delete mode 100644 libs/core/src/platform/wasm/entry.zig delete mode 100644 libs/core/src/platform/wasm/js.zig delete mode 100644 libs/core/src/platform/wasm/mach.js diff --git a/libs/core/.gitattributes b/libs/core/.gitattributes deleted file mode 100644 index ba1273bd..00000000 --- a/libs/core/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -* text=auto eol=lf -upstream/** linguist-vendored diff --git a/libs/core/.github/FUNDING.yml b/libs/core/.github/FUNDING.yml deleted file mode 100644 index 99fd1066..00000000 --- a/libs/core/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -github: slimsag diff --git a/libs/core/.github/pull_request_template.md b/libs/core/.github/pull_request_template.md deleted file mode 100644 index 006cfaa4..00000000 --- a/libs/core/.github/pull_request_template.md +++ /dev/null @@ -1,5 +0,0 @@ -Please send your change to [the main repository](https://github.com/hexops/mach/tree/main/libs/core) instead, sorry for the trouble! - -This helps us avoid some complex merge conflicts we run into when changes are made to both repositories and history needs to be reconciled. Keeping PRs in just that repository enables us to use `git subtree` to trivially keep the two repositories in sync. - -Once your PR is merged over there, it'll automatically sync to this repository. diff --git a/libs/core/.github/workflows/ci.yml b/libs/core/.github/workflows/ci.yml deleted file mode 100644 index 7a6a013b..00000000 --- a/libs/core/.github/workflows/ci.yml +++ /dev/null @@ -1,79 +0,0 @@ -name: CI -on: - - push - - pull_request -jobs: - x86_64-linux: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - with: - submodules: 'true' - - name: Setup Zig - run: | - sudo apt install xz-utils - sudo sh -c 'wget -c https://ziglang.org/builds/zig-linux-x86_64-0.11.0-dev.3883+7166407d8.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin' - - name: build - run: | - rm -rf libs/mach-glfw - rm -rf libs/mach-gpu - rm -rf libs/mach-gpu-dawn - git clone --recursive https://github.com/hexops/mach-glfw libs/mach-glfw - git clone https://github.com/hexops/mach-gpu libs/mach-gpu - git clone --recursive https://github.com/hexops/mach-gpu-dawn libs/mach-gpu-dawn - zig build - - name: launch xvfb - run: Xvfb :99 -screen 0 1680x720x24 > /dev/null 2>&1 & - - name: test - run: | - sudo add-apt-repository -y ppa:kisak/kisak-mesa - sudo apt-get update - sudo apt-get install mesa-utils mesa-utils-extra mesa-va-drivers mesa-vdpau-drivers mesa-vulkan-drivers xvfb - x86_64-windows: - runs-on: windows-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - with: - submodules: 'true' - - name: Setup Zig - run: | - $ProgressPreference = 'SilentlyContinue' - Invoke-WebRequest -Uri "https://ziglang.org/builds/zig-windows-x86_64-0.11.0-dev.3883+7166407d8.zip" -OutFile "C:\zig.zip" - cd C:\ - 7z x zig.zip - Add-Content $env:GITHUB_PATH "C:\zig-windows-x86_64-0.11.0-dev.3883+7166407d8\" - - name: build - run: | - Remove-Item -Recurse -Force libs/mach-glfw - Remove-Item -Recurse -Force libs/mach-gpu - Remove-Item -Recurse -Force libs/mach-gpu-dawn - git clone --recursive https://github.com/hexops/mach-glfw libs/mach-glfw - git clone https://github.com/hexops/mach-gpu libs/mach-gpu - git clone --recursive https://github.com/hexops/mach-gpu-dawn libs/mach-gpu-dawn - zig build - - name: test - run: zig build test - x86_64-macos: - runs-on: macos-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - with: - submodules: 'true' - - name: Setup Zig - run: | - brew install xz - sudo sh -c 'wget -c https://ziglang.org/builds/zig-macos-x86_64-0.11.0-dev.3883+7166407d8.tar.xz -O - | tar -xJ --strip-components=1 -C /usr/local/bin' - - name: build - run: | - rm -rf libs/mach-glfw - rm -rf libs/mach-gpu - rm -rf libs/mach-gpu-dawn - git clone --recursive https://github.com/hexops/mach-glfw libs/mach-glfw - git clone https://github.com/hexops/mach-gpu libs/mach-gpu - git clone --recursive https://github.com/hexops/mach-gpu-dawn libs/mach-gpu-dawn - zig build - - name: test - run: zig build test diff --git a/libs/core/.gitignore b/libs/core/.gitignore deleted file mode 100644 index feda423c..00000000 --- a/libs/core/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -# This file is for zig-specific build artifacts. -# If you have OS-specific or editor-specific files to ignore, -# such as *.swp or .DS_Store, put those in your global -# ~/.gitignore and put this in your ~/.gitconfig: -# -# [core] -# excludesfile = ~/.gitignore -# -# Cheers! -# -andrewrk - -zig-cache/ -zig-out/ -/release/ -/debug/ -/build/ -/build-*/ -/docgen_tmp/ diff --git a/libs/core/LICENSE b/libs/core/LICENSE deleted file mode 100644 index ba6099da..00000000 --- a/libs/core/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2021, Hexops Contributors (given via the Git commit history). - -All documentation, image, sound, font, and 2D/3D model files are CC-BY-4.0 licensed unless -otherwise noted. You may get a copy of this license at https://creativecommons.org/licenses/by/4.0 - -Files in a directory with a separate LICENSE file may contain files under different license terms, -described within that LICENSE file. - -All other files are licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) -or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at your option. - -All files in the project without exclusions may not be copied, modified, or distributed except -according to the terms above. \ No newline at end of file diff --git a/libs/core/LICENSE-APACHE b/libs/core/LICENSE-APACHE deleted file mode 100644 index d6456956..00000000 --- a/libs/core/LICENSE-APACHE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/libs/core/LICENSE-MIT b/libs/core/LICENSE-MIT deleted file mode 100644 index 14cd7973..00000000 --- a/libs/core/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2021 Hexops Contributors (given via the Git commit history). - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/libs/core/README.md b/libs/core/README.md deleted file mode 100644 index 08971ccd..00000000 --- a/libs/core/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# mach/core: a modern alternative to SDL/etc - -This repository is a separate copy of the same library in the [main Mach repository](https://github.com/hexops/mach), and is automatically kept in sync, so that anyone can use this library in their own project if they like! - -## Experimental - -This is an _experimental_ Mach library, according to our [stability guarantees](https://machengine.org/next/docs/libs/): - -> Experimental libraries may have their APIs change without much notice, and you may have to look at recent changes in order to update your code. - -[Why this library is not declared stable yet](https://machengine.org/next/docs/libs/experimental/#core) - -## Window+Input+GPU, nothing else. - -mach/core provides the power of Vulkan, DirectX, Metal, and modern OpenGL in a single concise graphics API - by compiling Google Chrome's WebGPU implementation natively via Zig (no cmake/ninja/gn/etc) into a single static library. - -Supports Windows, Linux, and macOS today. WebAssembly and Mobile will also be supported under the same API in the near future. - -Learn more: https://machengine.org/docs/core - -## Getting started - -### Adding dependency - -In a `libs` subdirectory of the root of your project: - -```sh -git clone https://github.com/hexops/mach-core -``` - -Then in your `build.zig` add: - -```zig -... -const core = @import("libs/mach-core/build.zig"); - -pub fn build(b: *Build) void { - ... - exe.addModule("core", core.module(b)); - core.link(b, exe, .{}); -} -``` - -## Join the community - -Join the Mach community [on Discord](https://discord.gg/XNG3NZgCqp) to discuss this project, ask questions, get help, etc. - -## Issues - -Issues are tracked in the [main Mach repository](https://github.com/hexops/mach/issues?q=is%3Aissue+is%3Aopen+label%3Acore). - -## Contributing - -Contributions are very welcome. Pull requests must be sent to [the main repository](https://github.com/hexops/mach/tree/main/libs/core) to avoid some complex merge conflicts we'd get by accepting contributions in both repositories. Once the changes are merged there, they'll get sync'd to this repository automatically. diff --git a/libs/core/build.zig b/libs/core/build.zig deleted file mode 100644 index 316e8ab8..00000000 --- a/libs/core/build.zig +++ /dev/null @@ -1,273 +0,0 @@ -const std = @import("std"); -const builtin = @import("builtin"); -const glfw = @import("mach_glfw"); -const gpu_dawn = @import("libs/mach-gpu-dawn/build.zig"); -const gpu = @import("libs/mach-gpu/build.zig").Sdk(.{ - .gpu_dawn = gpu_dawn, -}); -const core = @import("build.zig").Sdk(.{ - .gpu = gpu, - .gpu_dawn = gpu_dawn, - .glfw = glfw, -}); - -pub fn build(b: *std.Build) !void { - const optimize = b.standardOptimizeOption(.{}); - const target = b.standardTargetOptions(.{}); - - const gpu_dawn_options = gpu_dawn.Options{ - .from_source = b.option(bool, "dawn-from-source", "Build Dawn from source") orelse false, - .debug = b.option(bool, "dawn-debug", "Use a debug build of Dawn") orelse false, - }; - const options = core.Options{ .gpu_dawn_options = gpu_dawn_options }; - - if (target.getCpuArch() != .wasm32) { - const all_tests_step = b.step("test", "Run library tests"); - const glfw_test_step = b.step("test-glfw", "Run GLFW library tests"); - const gpu_test_step = b.step("test-gpu", "Run GPU library tests"); - const core_test_step = b.step("test-core", "Run Mach Core library tests"); - - glfw_test_step.dependOn(&(try glfw.testStep(b, optimize, target)).step); - gpu_test_step.dependOn(&(try gpu.testStep(b, optimize, target, options.gpuOptions())).step); - core_test_step.dependOn(&(try core.testStep(b, optimize, target)).step); - - all_tests_step.dependOn(glfw_test_step); - all_tests_step.dependOn(gpu_test_step); - all_tests_step.dependOn(core_test_step); - - // Compiles the `libmachcore` shared library - const shared_lib = try core.buildSharedLib(b, optimize, target, options); - - b.installArtifact(shared_lib); - } - - const compile_all = b.step("compile-all", "Compile Mach"); - compile_all.dependOn(b.getInstallStep()); -} - -fn sdkPath(comptime suffix: []const u8) []const u8 { - if (suffix[0] != '/') @compileError("suffix must be an absolute path"); - return comptime blk: { - const root_dir = std.fs.path.dirname(@src().file) orelse "."; - break :blk root_dir ++ suffix; - }; -} - -pub fn Sdk(comptime deps: anytype) type { - return struct { - pub const Options = struct { - glfw_options: deps.glfw.Options = .{}, - gpu_dawn_options: deps.gpu_dawn.Options = .{}, - - pub fn gpuOptions(options: Options) deps.gpu.Options { - return .{ - .gpu_dawn_options = options.gpu_dawn_options, - }; - } - }; - - var _module: ?*std.build.Module = null; - - pub fn module(b: *std.Build) *std.build.Module { - if (_module) |m| return m; - - const gamemode_dep = b.dependency("mach_gamemode", .{}); - - _module = b.createModule(.{ - .source_file = .{ .path = sdkPath("/src/main.zig") }, - .dependencies = &.{ - .{ .name = "gpu", .module = deps.gpu.module(b) }, - .{ .name = "glfw", .module = deps.glfw.module(b) }, - .{ .name = "gamemode", .module = gamemode_dep.module("mach-gamemode") }, - }, - }); - return _module.?; - } - - pub fn testStep(b: *std.Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget) !*std.build.RunStep { - const main_tests = b.addTest(.{ - .name = "core-tests", - .root_source_file = .{ .path = sdkPath("/src/main.zig") }, - .target = target, - .optimize = optimize, - }); - var iter = module(b).dependencies.iterator(); - while (iter.next()) |e| { - main_tests.addModule(e.key_ptr.*, e.value_ptr.*); - } - main_tests.addModule("glfw", deps.glfw.module(b)); - try deps.glfw.link(b, main_tests, .{}); - if (target.isLinux()) { - const gamemode_dep = b.dependency("mach_gamemode", .{}); - main_tests.addModule("gamemode", gamemode_dep.module("mach-gamemode")); - } - main_tests.addIncludePath(sdkPath("/include")); - b.installArtifact(main_tests); - return b.addRunArtifact(main_tests); - } - - pub fn buildSharedLib(b: *std.Build, optimize: std.builtin.OptimizeMode, target: std.zig.CrossTarget, options: Options) !*std.build.CompileStep { - // TODO(build): this should use the App abstraction instead of being built manually - const lib = b.addSharedLibrary(.{ .name = "machcore", .root_source_file = .{ .path = "src/platform/libmachcore.zig" }, .target = target, .optimize = optimize }); - lib.main_pkg_path = "src/"; - const app_module = b.createModule(.{ - .source_file = .{ .path = "src/platform/libmachcore_app.zig" }, - }); - lib.addModule("app", app_module); - lib.addModule("glfw", deps.glfw.module(b)); - lib.addModule("gpu", deps.gpu.module(b)); - if (target.isLinux()) { - const gamemode_dep = b.dependency("mach_gamemode", .{}); - lib.addModule("gamemode", gamemode_dep.module("mach-gamemode")); - } - try deps.glfw.link(b, lib, options.glfw_options); - try deps.gpu.link(b, lib, options.gpuOptions()); - return lib; - } - - pub const App = struct { - b: *std.Build, - name: []const u8, - step: *std.build.CompileStep, - platform: Platform, - res_dirs: ?[]const []const u8, - watch_paths: ?[]const []const u8, - sysjs_dep: ?*std.Build.Dependency, - - const web_install_dir = std.build.InstallDir{ .custom = "www" }; - - pub const Platform = enum { - native, - web, - - pub fn fromTarget(target: std.Target) Platform { - if (target.cpu.arch == .wasm32) return .web; - return .native; - } - }; - - pub fn init( - b: *std.Build, - options: struct { - name: []const u8, - src: []const u8, - target: std.zig.CrossTarget, - optimize: std.builtin.OptimizeMode, - deps: ?[]const std.build.ModuleDependency = null, - res_dirs: ?[]const []const u8 = null, - watch_paths: ?[]const []const u8 = null, - }, - ) !App { - const target = (try std.zig.system.NativeTargetInfo.detect(options.target)).target; - const platform = Platform.fromTarget(target); - - var dependencies = std.ArrayList(std.build.ModuleDependency).init(b.allocator); - try dependencies.append(.{ .name = "core", .module = module(b) }); - if (options.deps) |app_deps| try dependencies.appendSlice(app_deps); - - const app_module = b.createModule(.{ - .source_file = .{ .path = options.src }, - .dependencies = try dependencies.toOwnedSlice(), - }); - - const sysjs_dep = if (platform == .web) b.dependency("mach_sysjs", .{ - .target = options.target, - .optimize = options.optimize, - }) else null; - - const step = blk: { - if (platform == .web) { - const lib = b.addSharedLibrary(.{ - .name = options.name, - .root_source_file = .{ .path = sdkPath("/src/entry.zig") }, - .target = options.target, - .optimize = options.optimize, - }); - lib.rdynamic = true; - lib.addModule("sysjs", sysjs_dep.?.module("mach-sysjs")); - break :blk lib; - } else { - const exe = b.addExecutable(.{ - .name = options.name, - .root_source_file = .{ .path = sdkPath("/src/entry.zig") }, - .target = options.target, - .optimize = options.optimize, - }); - // TODO(core): figure out why we need to disable LTO: https://github.com/hexops/mach/issues/597 - exe.want_lto = false; - exe.addModule("glfw", deps.glfw.module(b)); - - if (target.os.tag == .linux) { - const gamemode_dep = b.dependency("mach_gamemode", .{}); - exe.addModule("gamemode", gamemode_dep.module("mach-gamemode")); - } - - break :blk exe; - } - }; - - step.main_pkg_path = sdkPath("/src"); - step.addModule("core", module(b)); - step.addModule("app", app_module); - - return .{ - .b = b, - .step = step, - .name = options.name, - .platform = platform, - .res_dirs = options.res_dirs, - .watch_paths = options.watch_paths, - .sysjs_dep = sysjs_dep, - }; - } - - pub fn link(app: *const App, options: Options) !void { - if (app.platform != .web) { - try deps.glfw.link(app.b, app.step, options.glfw_options); - deps.gpu.link(app.b, app.step, options.gpuOptions()) catch return error.FailedToLinkGPU; - } - } - - pub fn install(app: *const App) void { - app.b.installArtifact(app.step); - - // Install additional files (mach.js and mach-sysjs.js) - // in case of wasm - if (app.platform == .web) { - // Set install directory to '{prefix}/www' - app.getInstallStep().?.dest_dir = web_install_dir; - - inline for (.{ sdkPath("/src/platform/wasm/mach.js"), @import("mach_sysjs").getJSPath() }) |js| { - const install_js = app.b.addInstallFileWithDir( - .{ .path = js }, - web_install_dir, - std.fs.path.basename(js), - ); - app.getInstallStep().?.step.dependOn(&install_js.step); - } - } - - // Install resources - if (app.res_dirs) |res_dirs| { - for (res_dirs) |res| { - const install_res = app.b.addInstallDirectory(.{ - .source_dir = .{ .path = res }, - .install_dir = app.getInstallStep().?.dest_dir, - .install_subdir = std.fs.path.basename(res), - .exclude_extensions = &.{}, - }); - app.getInstallStep().?.step.dependOn(&install_res.step); - } - } - } - - pub fn addRunArtifact(app: *const App) *std.build.RunStep { - return app.b.addRunArtifact(app.step); - } - - pub fn getInstallStep(app: *const App) ?*std.build.InstallArtifactStep { - return app.b.addInstallArtifact(app.step); - } - }; - }; -} diff --git a/libs/core/build.zig.zon b/libs/core/build.zig.zon deleted file mode 100644 index 41c1467c..00000000 --- a/libs/core/build.zig.zon +++ /dev/null @@ -1,38 +0,0 @@ -.{ - .name = "mach-core", - .version = "0.2.0", - .dependencies = .{ - .mach_sysjs = .{ - .url = "https://github.com/hexops/mach-sysjs/archive/b71eb0531f337fcca5a2b245f595355260109a34.tar.gz", - .hash = "12208b30f1d9c229d1e64483354610207c9aa06350a46558560b818d597800ed86e0", - }, - .mach_gamemode = .{ - .url = "https://github.com/hexops/mach-gamemode/archive/6e71d19d7eecbf0230e5c445dbe9281e45393245.tar.gz", - .hash = "1220ff812193615e03375a342a7c8a52f368eab219bceab3039de1915f9c945f2a66", - }, - .mach_glfw = .{ - .url = "https://github.com/hexops/mach-glfw/archive/b119c63dd77764eeafe758d54accd0329821a729.tar.gz", - .hash = "1220fb0fb65621a4fc7406e4f74a87a0c60208f8a257cd7ca4e20da0925f875e70d0", - }, - .glfw = .{ - .url = "https://github.com/hexops/glfw/archive/49c21c3d2fcaf9799b593f5320ce8e598a692c74.tar.gz", - .hash = "12200a907165afc4c099d4d19e2f7ce9923a72116006d8f5f5af3a9a071fa66171d2", - }, - .direct3d_headers = .{ - .url = "https://github.com/hexops/direct3d-headers/archive/773dce3f079eecdccc7c71d1318a0741649d568b.tar.gz", - .hash = "12200d2155216c5eb5f111282cd355b5433cad6a68fd040294e695149cba329f7c12", - }, - .vulkan_headers = .{ - .url = "https://github.com/hexops/vulkan-headers/archive/e1b061ff624531e82a7daea5dbd56c07e08bf0be.tar.gz", - .hash = "12204967f9d07fda3af6a21d6ab71fb832da2186176c530a7a14aa96043537399e6b", - }, - .wayland_headers = .{ - .url = "https://github.com/hexops/wayland-headers/archive/7bf46f3d60edab2171643ff85770c392ef62704d.tar.gz", - .hash = "1220689912c40c0880b094f748199c490810d4fa4c58ce1ef9058ce97f46ee28496a", - }, - .x11_headers = .{ - .url = "https://github.com/hexops/x11-headers/archive/99af89c7bfdc7db503f3a7003571f8e81bcd09f3.tar.gz", - .hash = "1220e6bd3186841c1da38d862d52ba88dec9633d24f409eda27627321937419a0ddb", - }, - }, -} diff --git a/libs/core/include/libmachcore.h b/libs/core/include/libmachcore.h deleted file mode 100644 index 42178af3..00000000 --- a/libs/core/include/libmachcore.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef MACHCORE_H_ -#define MACHCORE_H_ - -#if defined(MACHCORE_SHARED_LIBRARY) -# if defined(_WIN32) -# if defined(MACHCORE_IMPLEMENTATION) -# define MACHCORE_EXPORT __declspec(dllexport) -# else -# define MACHCORE_EXPORT __declspec(dllimport) -# endif -# else // defined(_WIN32) -# if defined(MACHCORE_IMPLEMENTATION) -# define MACHCORE_EXPORT __attribute__((visibility("default"))) -# else -# define MACHCORE_EXPORT -# endif -# endif // defined(_WIN32) -#else // defined(MACHCORE_SHARED_LIBRARY) -# define MACHCORE_EXPORT -#endif // defined(MACHCORE_SHARED_LIBRARY) - -#include -#include -#include - -typedef struct MachCoreInstanceImpl MachCoreInstance; - -typedef struct MachCoreEventIteratorImpl { - unsigned char _data[8]; -} MachCoreEventIterator; - -MachCoreInstance* mach_core_init(); -void mach_core_deinit(MachCoreInstance* core); -MachCoreEventIterator mach_core_poll_events(MachCoreInstance* core); - - -#endif // MACHCORE_H_ \ No newline at end of file diff --git a/libs/core/libs/mach-glfw b/libs/core/libs/mach-glfw deleted file mode 120000 index 0d47f286..00000000 --- a/libs/core/libs/mach-glfw +++ /dev/null @@ -1 +0,0 @@ -../../glfw \ No newline at end of file diff --git a/libs/core/libs/mach-gpu b/libs/core/libs/mach-gpu deleted file mode 120000 index 142fb575..00000000 --- a/libs/core/libs/mach-gpu +++ /dev/null @@ -1 +0,0 @@ -../../gpu \ No newline at end of file diff --git a/libs/core/libs/mach-gpu-dawn b/libs/core/libs/mach-gpu-dawn deleted file mode 120000 index c033c781..00000000 --- a/libs/core/libs/mach-gpu-dawn +++ /dev/null @@ -1 +0,0 @@ -../../gpu-dawn \ No newline at end of file diff --git a/libs/core/src/Core.zig b/libs/core/src/Core.zig deleted file mode 100644 index df749c04..00000000 --- a/libs/core/src/Core.zig +++ /dev/null @@ -1,418 +0,0 @@ -const builtin = @import("builtin"); -const std = @import("std"); -const gpu = @import("gpu"); -const platform = @import("platform.zig"); - -pub const Core = @This(); - -internal: platform.Core, - -pub const Options = struct { - is_app: bool = false, - is_headless: bool = false, - title: [*:0]const u8 = "Mach Engine", - size: Size = .{ .width = 1920 / 2, .height = 1080 / 2 }, - power_preference: gpu.PowerPreference = .undefined, - required_features: ?[]const gpu.FeatureName = null, - required_limits: ?gpu.Limits = null, -}; - -pub fn init(core: *Core, allocator: std.mem.Allocator, options: Options) !void { - try platform.Core.init(&core.internal, allocator, options); -} - -pub fn deinit(core: *Core) void { - return core.internal.deinit(); -} - -pub const EventIterator = struct { - internal: platform.Core.EventIterator, - - pub inline fn next(self: *EventIterator) ?Event { - return self.internal.next(); - } -}; - -pub inline fn pollEvents(core: *Core) EventIterator { - return .{ .internal = core.internal.pollEvents() }; -} - -/// Returns the framebuffer size, in subpixel units. -pub fn framebufferSize(core: *Core) Size { - return core.internal.framebufferSize(); -} - -/// Sets seconds to wait for an event with timeout when calling `Core.update()` -/// again. -/// -/// timeout is in seconds (<= `0.0` disables waiting) -/// - pass `std.math.inf(f64)` to wait with no timeout -/// -/// `Core.update()` will return earlier than timeout if an event happens (key press, -/// mouse motion, etc.) -/// -/// `Core.update()` can return a bit later than timeout due to timer precision and -/// process scheduling. -pub fn setWaitTimeout(core: *Core, timeout: f64) void { - return core.internal.setWaitTimeout(timeout); -} - -/// Set the window title -pub fn setTitle(core: *Core, title: [:0]const u8) void { - return core.internal.setTitle(title); -} - -/// Set the window mode -pub fn setDisplayMode(core: *Core, mode: DisplayMode, monitor: ?usize) void { - return core.internal.setDisplayMode(mode, monitor); -} - -/// Returns the window mode -pub fn displayMode(core: *Core) DisplayMode { - return core.internal.displayMode(); -} - -pub fn setBorder(core: *Core, value: bool) void { - return core.internal.setBorder(value); -} - -pub fn border(core: *Core) bool { - return core.internal.border(); -} - -pub fn setHeadless(core: *Core, value: bool) void { - return core.internal.setHeadless(value); -} - -pub fn headless(core: *Core) bool { - return core.internal.headless(); -} - -pub const VSyncMode = enum { - /// Potential screen tearing. - /// No synchronization with monitor, render frames as fast as possible. - /// - /// Not available on WASM, fallback to double - none, - - /// No tearing, synchronizes rendering with monitor refresh rate, rendering frames when ready. - /// - /// Tries to stay one frame ahead of the monitor, so when it's ready for the next frame it is - /// already prepared. - double, - - /// No tearing, synchronizes rendering with monitor refresh rate, rendering frames when ready. - /// - /// Tries to stay two frames ahead of the monitor, so when it's ready for the next frame it is - /// already prepared. - /// - /// Not available on WASM, fallback to double - triple, -}; - -/// Set monitor synchronization mode. -pub fn setVSync(core: *Core, mode: VSyncMode) void { - return core.internal.setVSync(mode); -} - -/// Returns monitor synchronization mode. -pub fn vsync(core: *Core) VSyncMode { - return core.internal.vsync(); -} - -/// Set the window size, in subpixel units. -pub fn setSize(core: *Core, value: Size) void { - return core.internal.setSize(value); -} - -/// Returns the window size, in subpixel units. -pub fn size(core: *Core) Size { - return core.internal.size(); -} - -/// Set the minimum and maximum allowed size for the window. -pub fn setSizeLimit(core: *Core, size_limit: SizeLimit) void { - return core.internal.setSizeLimit(size_limit); -} - -/// Returns the minimum and maximum allowed size for the window. -pub fn sizeLimit(core: *Core) SizeLimit { - return core.internal.sizeLimit(); -} - -pub fn setCursorMode(core: *Core, mode: CursorMode) void { - return core.internal.setCursorMode(mode); -} - -pub fn cursorMode(core: *Core) CursorMode { - return core.internal.cursorMode(); -} - -pub fn setCursorShape(core: *Core, cursor: CursorShape) void { - return core.internal.setCursorShape(cursor); -} - -pub fn cursorShape(core: *Core) CursorShape { - return core.internal.cursorShape(); -} - -pub fn adapter(core: *Core) *gpu.Adapter { - return core.internal.adapter(); -} - -pub fn device(core: *Core) *gpu.Device { - return core.internal.device(); -} - -pub fn swapChain(core: *Core) *gpu.SwapChain { - return core.internal.swapChain(); -} - -pub fn descriptor(core: *Core) gpu.SwapChain.Descriptor { - return core.internal.descriptor(); -} - -pub const Size = struct { - width: u32, - height: u32, -}; - -pub const SizeOptional = struct { - width: ?u32, - height: ?u32, -}; - -pub const SizeLimit = struct { - min: SizeOptional, - max: SizeOptional, -}; - -pub const Position = struct { - x: f64, - y: f64, -}; - -pub const Event = union(enum) { - key_press: KeyEvent, - key_repeat: KeyEvent, - key_release: KeyEvent, - char_input: struct { - codepoint: u21, - }, - mouse_motion: struct { - pos: Position, - }, - mouse_press: MouseButtonEvent, - mouse_release: MouseButtonEvent, - mouse_scroll: struct { - xoffset: f32, - yoffset: f32, - }, - framebuffer_resize: Size, - focus_gained, - focus_lost, - close, -}; - -pub const KeyEvent = struct { - key: Key, - mods: KeyMods, -}; - -pub const MouseButtonEvent = struct { - button: MouseButton, - pos: Position, - mods: KeyMods, -}; - -pub const MouseButton = enum { - left, - right, - middle, - four, - five, - six, - seven, - eight, -}; - -pub const Key = enum { - a, - b, - c, - d, - e, - f, - g, - h, - i, - j, - k, - l, - m, - n, - o, - p, - q, - r, - s, - t, - u, - v, - w, - x, - y, - z, - - zero, - one, - two, - three, - four, - five, - six, - seven, - eight, - nine, - - f1, - f2, - f3, - f4, - f5, - f6, - f7, - f8, - f9, - f10, - f11, - f12, - f13, - f14, - f15, - f16, - f17, - f18, - f19, - f20, - f21, - f22, - f23, - f24, - f25, - - kp_divide, - kp_multiply, - kp_subtract, - kp_add, - kp_0, - kp_1, - kp_2, - kp_3, - kp_4, - kp_5, - kp_6, - kp_7, - kp_8, - kp_9, - kp_decimal, - kp_equal, - kp_enter, - - enter, - escape, - tab, - left_shift, - right_shift, - left_control, - right_control, - left_alt, - right_alt, - left_super, - right_super, - menu, - num_lock, - caps_lock, - print, - scroll_lock, - pause, - delete, - home, - end, - page_up, - page_down, - insert, - left, - right, - up, - down, - backspace, - space, - minus, - equal, - left_bracket, - right_bracket, - backslash, - semicolon, - apostrophe, - comma, - period, - slash, - grave, - - unknown, -}; - -pub const KeyMods = packed struct(u8) { - shift: bool, - control: bool, - alt: bool, - super: bool, - caps_lock: bool, - num_lock: bool, - _padding: u2 = 0, -}; - -pub const DisplayMode = enum { - /// Windowed mode. - windowed, - - /// Fullscreen mode, using this option may change the display's video mode. - fullscreen, - - /// Borderless fullscreen window. - /// - /// Beware that true .fullscreen is also a hint to the OS that is used in various contexts, e.g. - /// - /// * macOS: Moving to a virtual space dedicated to fullscreen windows as the user expects - /// * macOS: .borderless windows cannot prevent the system menu bar from being displayed - /// - /// Always allow users to choose their preferred display mode. - borderless, -}; - -pub const CursorMode = enum { - /// Makes the cursor visible and behaving normally. - normal, - - /// Makes the cursor invisible when it is over the content area of the window but does not - /// restrict it from leaving. - hidden, - - /// Hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful - /// for implementing for example 3D camera controls. - disabled, -}; - -pub const CursorShape = enum { - arrow, - ibeam, - crosshair, - pointing_hand, - resize_ew, - resize_ns, - resize_nwse, - resize_nesw, - resize_all, - not_allowed, -}; diff --git a/libs/core/src/Timer.zig b/libs/core/src/Timer.zig deleted file mode 100644 index c84b9f30..00000000 --- a/libs/core/src/Timer.zig +++ /dev/null @@ -1,38 +0,0 @@ -const std = @import("std"); -const platform = @import("platform.zig"); - -pub const Timer = @This(); - -internal: platform.Timer, - -/// Initialize the timer. -pub fn start() !Timer { - return Timer{ - .internal = try platform.Timer.start(), - }; -} - -/// Reads the timer value since start or the last reset in nanoseconds. -pub inline fn readPrecise(timer: *Timer) u64 { - return timer.internal.read(); -} - -/// Reads the timer value since start or the last reset in seconds. -pub inline fn read(timer: *Timer) f32 { - return @as(f32, @floatFromInt(timer.readPrecise())) / @as(f32, @floatFromInt(std.time.ns_per_s)); -} - -/// Resets the timer value to 0/now. -pub inline fn reset(timer: *Timer) void { - timer.internal.reset(); -} - -/// Returns the current value of the timer in nanoseconds, then resets it. -pub inline fn lapPrecise(timer: *Timer) u64 { - return timer.internal.lap(); -} - -/// Returns the current value of the timer in seconds, then resets it. -pub inline fn lap(timer: *Timer) f32 { - return @as(f32, @floatFromInt(timer.lapPrecise())) / @as(f32, @floatFromInt(std.time.ns_per_s)); -} diff --git a/libs/core/src/entry.zig b/libs/core/src/entry.zig deleted file mode 100644 index d7e4cea1..00000000 --- a/libs/core/src/entry.zig +++ /dev/null @@ -1,43 +0,0 @@ -const builtin = @import("builtin"); - -pub usingnamespace if (builtin.cpu.arch == .wasm32) - @import("platform/wasm/entry.zig") -else - @import("platform/native/entry.zig"); - -comptime { - if (!builtin.is_test) { - if (!@hasDecl(@import("app"), "App")) { - @compileError("expected e.g. `pub const App = mach.App(modules, init)' (App definition missing in your main Zig file)"); - } - - const App = @import("app").App; - if (@typeInfo(App) != .Struct) { - @compileError("App must be a struct type. Found:" ++ @typeName(App)); - } - - if (@hasDecl(App, "init")) { - const InitFn = @TypeOf(@field(App, "init")); - if (InitFn != fn (*App) @typeInfo(@typeInfo(InitFn).Fn.return_type.?).ErrorUnion.error_set!void) - @compileError("expected 'pub fn init(app: *App) !void' found '" ++ @typeName(InitFn) ++ "'"); - } else { - @compileError("App must export 'pub fn init(app: *App) !void'"); - } - - if (@hasDecl(App, "update")) { - const UpdateFn = @TypeOf(@field(App, "update")); - if (UpdateFn != fn (app: *App) @typeInfo(@typeInfo(UpdateFn).Fn.return_type.?).ErrorUnion.error_set!bool) - @compileError("expected 'pub fn update(app: *App) !bool' found '" ++ @typeName(UpdateFn) ++ "'"); - } else { - @compileError("App must export 'pub fn update(app: *App) !bool'"); - } - - if (@hasDecl(App, "deinit")) { - const DeinitFn = @TypeOf(@field(App, "deinit")); - if (DeinitFn != fn (app: *App) void) - @compileError("expected 'pub fn deinit(app: *App) void' found '" ++ @typeName(DeinitFn) ++ "'"); - } else { - @compileError("App must export 'pub fn deinit(app: *App) void'"); - } - } -} diff --git a/libs/core/src/main.zig b/libs/core/src/main.zig deleted file mode 100644 index bbf89ce9..00000000 --- a/libs/core/src/main.zig +++ /dev/null @@ -1,11 +0,0 @@ -pub const Core = @import("Core.zig"); -pub const Timer = @import("Timer.zig"); -pub const gpu = @import("gpu"); -pub const sysjs = @import("sysjs"); -const builtin = @import("builtin"); -pub const platform_util = if (builtin.cpu.arch == .wasm32) {} else @import("platform/native/util.zig"); - -test { - _ = @import("platform/libmachcore.zig"); - _ = @import("platform/libmachcore_app.zig"); -} diff --git a/libs/core/src/platform.zig b/libs/core/src/platform.zig deleted file mode 100644 index 43bf5630..00000000 --- a/libs/core/src/platform.zig +++ /dev/null @@ -1,63 +0,0 @@ -const builtin = @import("builtin"); - -const platform = if (builtin.cpu.arch == .wasm32) - @import("platform/wasm.zig") -else - @import("platform/native.zig"); - -pub const Core = platform.Core; -pub const Timer = platform.Timer; - -// Verifies that a platform implementation exposes the expected function declarations. -comptime { - assertHasDecl(@This(), "Core"); - assertHasDecl(@This(), "Timer"); - - // Core - assertHasDecl(@This().Core, "init"); - assertHasDecl(@This().Core, "deinit"); - assertHasDecl(@This().Core, "pollEvents"); - assertHasDecl(@This().Core, "framebufferSize"); - - assertHasDecl(@This().Core, "setWaitTimeout"); - assertHasDecl(@This().Core, "setTitle"); - - assertHasDecl(@This().Core, "setDisplayMode"); - assertHasDecl(@This().Core, "displayMode"); - - assertHasDecl(@This().Core, "setBorder"); - assertHasDecl(@This().Core, "border"); - - assertHasDecl(@This().Core, "setHeadless"); - assertHasDecl(@This().Core, "headless"); - - assertHasDecl(@This().Core, "setVSync"); - assertHasDecl(@This().Core, "vsync"); - - assertHasDecl(@This().Core, "setSize"); - assertHasDecl(@This().Core, "size"); - - assertHasDecl(@This().Core, "setSizeLimit"); - assertHasDecl(@This().Core, "sizeLimit"); - - assertHasDecl(@This().Core, "setCursorMode"); - assertHasDecl(@This().Core, "cursorMode"); - - assertHasDecl(@This().Core, "setCursorShape"); - assertHasDecl(@This().Core, "cursorShape"); - - assertHasDecl(@This().Core, "adapter"); - assertHasDecl(@This().Core, "device"); - assertHasDecl(@This().Core, "swapChain"); - assertHasDecl(@This().Core, "descriptor"); - - // Timer - assertHasDecl(@This().Timer, "start"); - assertHasDecl(@This().Timer, "read"); - assertHasDecl(@This().Timer, "reset"); - assertHasDecl(@This().Timer, "lap"); -} - -fn assertHasDecl(comptime T: anytype, comptime name: []const u8) void { - if (!@hasDecl(T, name)) @compileError("Core missing declaration: " ++ name); -} diff --git a/libs/core/src/platform/libmachcore.zig b/libs/core/src/platform/libmachcore.zig deleted file mode 100644 index cdbe8b6c..00000000 --- a/libs/core/src/platform/libmachcore.zig +++ /dev/null @@ -1,82 +0,0 @@ -const std = @import("std"); -const testing = std.testing; -const gpu = @import("gpu"); -const ecs = @import("ecs"); -const glfw = @import("glfw"); -const Core = @import("../Core.zig"); -const native = @import("native.zig"); - -pub const GPUInterface = gpu.dawn.Interface; - -const _ = gpu.Export(GPUInterface); - -// Current Limitations: -// 1. Currently, ecs seems to be using some weird compile-time type trickery, so I'm not exactly sure how -// `engine` should be integrated into the C API -// 2. Core might need to expose more state so more API functions can be exposed (for example, the WebGPU API) -// 3. Be very careful about arguments, types, memory, etc - any mismatch will result in undefined behavior - -var gpa = std.heap.GeneralPurposeAllocator(.{}){}; -const allocator = gpa.allocator(); - -pub const MachCoreInstance = anyopaque; - -// Returns a pointer to a newly allocated Core -// Will return a null pointer if an error occurred while initializing Core -pub export fn mach_core_init() ?*MachCoreInstance { - if (!@import("builtin").is_test) gpu.Impl.init(); - - // TODO(libmach): eliminate this allocation - var core = allocator.create(native.Core) catch { - return null; - }; - // TODO(libmach): allow passing init options - core.init(allocator, .{}) catch { - // TODO(libmach): better error handling - return null; - }; - return core; -} - -pub export fn mach_core_deinit(_core: *MachCoreInstance) void { - var core = @as(*native.Core, @ptrCast(@alignCast(_core))); - native.Core.deinit(core); -} - -pub const MachCoreEventIterator = extern struct { - _data: [8]u8, -}; - -pub const MachCoreEvent = Core.Event; - -pub export fn mach_core_poll_events(_core: *MachCoreInstance) MachCoreEventIterator { - var core = @as(*native.Core, @ptrCast(@alignCast(_core))); - var iter = native.Core.pollEvents(core); - return @as(*MachCoreEventIterator, @ptrCast(&iter)).*; -} - -pub export fn mach_core_event_iterator_next(_iter: *MachCoreEventIterator, event: *MachCoreEvent) bool { - var iter = @as(*native.Core.EventIterator, @ptrCast(@alignCast(_iter))); - var value = iter.next() orelse return false; - event.* = value; - return true; -} - -const MachStatus = enum(c_int) { - Success = 0x00000000, - Error = 0x00000001, -}; - -test "C sizes" { - const c_header = @cImport({ - @cInclude("libmachcore.h"); - }); - - // Core.EventIterator can have different sizes depending on the platform, - // so we ensure we always use the maximum size in our C API. - if (@sizeOf(Core.EventIterator) > @sizeOf(MachCoreEventIterator)) { - try testing.expectEqual(@sizeOf(Core.EventIterator), @sizeOf(MachCoreEventIterator)); - } - - try testing.expectEqual(@sizeOf(c_header.MachCoreEventIterator), @sizeOf(MachCoreEventIterator)); -} diff --git a/libs/core/src/platform/libmachcore_app.zig b/libs/core/src/platform/libmachcore_app.zig deleted file mode 100644 index b9cb753a..00000000 --- a/libs/core/src/platform/libmachcore_app.zig +++ /dev/null @@ -1 +0,0 @@ -pub const App = @This(); diff --git a/libs/core/src/platform/native.zig b/libs/core/src/platform/native.zig deleted file mode 100644 index 825041c5..00000000 --- a/libs/core/src/platform/native.zig +++ /dev/null @@ -1,4 +0,0 @@ -const std = @import("std"); - -pub const Core = @import("native/Core.zig"); -pub const Timer = std.time.Timer; diff --git a/libs/core/src/platform/native/Core.zig b/libs/core/src/platform/native/Core.zig deleted file mode 100644 index ab90d4ca..00000000 --- a/libs/core/src/platform/native/Core.zig +++ /dev/null @@ -1,811 +0,0 @@ -const builtin = @import("builtin"); -const std = @import("std"); -const gpu = @import("gpu"); -const glfw = @import("glfw"); -const util = @import("util.zig"); -const Options = @import("../../Core.zig").Options; -const Event = @import("../../Core.zig").Event; -const KeyEvent = @import("../../Core.zig").KeyEvent; -const MouseButtonEvent = @import("../../Core.zig").MouseButtonEvent; -const MouseButton = @import("../../Core.zig").MouseButton; -const Size = @import("../../Core.zig").Size; -const DisplayMode = @import("../../Core.zig").DisplayMode; -const SizeLimit = @import("../../Core.zig").SizeLimit; -const CursorShape = @import("../../Core.zig").CursorShape; -const VSyncMode = @import("../../Core.zig").VSyncMode; -const CursorMode = @import("../../Core.zig").CursorMode; -const Key = @import("../../Core.zig").Key; -const KeyMods = @import("../../Core.zig").KeyMods; - -const log = std.log.scoped(.mach); - -pub const Core = @This(); - -allocator: std.mem.Allocator, -window: glfw.Window, -backend_type: gpu.BackendType, -user_ptr: UserPtr, - -instance: *gpu.Instance, -surface: *gpu.Surface, -gpu_adapter: *gpu.Adapter, -gpu_device: *gpu.Device, -swap_chain: *gpu.SwapChain, -swap_chain_desc: gpu.SwapChain.Descriptor, - -events: EventQueue, -wait_timeout: f64, - -last_size: glfw.Window.Size, -last_pos: glfw.Window.Pos, -size_limit: SizeLimit, -frame_buffer_resized: bool, -display_mode: DisplayMode, -border: bool, - -current_cursor: CursorShape, -cursors: [@typeInfo(CursorShape).Enum.fields.len]?glfw.Cursor, -cursors_tried: [@typeInfo(CursorShape).Enum.fields.len]bool, - -linux_gamemode: ?bool, - -const EventQueue = std.fifo.LinearFifo(Event, .Dynamic); - -pub const EventIterator = struct { - queue: *EventQueue, - - pub inline fn next(self: *EventIterator) ?Event { - return self.queue.readItem(); - } -}; - -const UserPtr = struct { - self: *Core, -}; - -// TODO(core): expose device loss to users, this can happen especially in the web and on mobile -// devices. Users will need to re-upload all assets to the GPU in this event. -fn deviceLostCallback(reason: gpu.Device.LostReason, msg: [*:0]const u8, userdata: ?*anyopaque) callconv(.C) void { - _ = userdata; - _ = reason; - log.err("mach: device lost: {s}", .{msg}); - @panic("mach: device lost"); -} - -pub fn init(core: *Core, allocator: std.mem.Allocator, options: Options) !void { - const backend_type = try util.detectBackendType(allocator); - - glfw.setErrorCallback(errorCallback); - if (!glfw.init(.{})) - glfw.getErrorCode() catch |err| switch (err) { - error.PlatformError, - error.PlatformUnavailable, - => return err, - else => unreachable, - }; - - // Create the test window and discover adapters using it (esp. for OpenGL) - var hints = util.glfwWindowHintsForBackend(backend_type); - hints.cocoa_retina_framebuffer = true; - if (options.is_headless) { - hints.visible = false; // Hiding window before creation otherwise you get the window showing up for a little bit then hiding. - } - - const window = glfw.Window.create( - options.size.width, - options.size.height, - options.title, - null, - null, - hints, - ) orelse switch (glfw.mustGetErrorCode()) { - error.InvalidEnum, - error.InvalidValue, - error.FormatUnavailable, - => unreachable, - error.APIUnavailable, - error.VersionUnavailable, - error.PlatformError, - => |err| return err, - else => unreachable, - }; - - switch (backend_type) { - .opengl, .opengles => { - glfw.makeContextCurrent(window); - glfw.getErrorCode() catch |err| switch (err) { - error.PlatformError => return err, - else => unreachable, - }; - }, - else => {}, - } - - const instance = gpu.createInstance(null) orelse { - log.err("failed to create GPU instance", .{}); - std.process.exit(1); - }; - const surface = util.createSurfaceForWindow(instance, window, comptime util.detectGLFWOptions()); - - var response: util.RequestAdapterResponse = undefined; - instance.requestAdapter(&gpu.RequestAdapterOptions{ - .compatible_surface = surface, - .power_preference = options.power_preference, - .force_fallback_adapter = false, - }, &response, util.requestAdapterCallback); - if (response.status != .success) { - log.err("failed to create GPU adapter: {?s}", .{response.message}); - log.info("-> maybe try MACH_GPU_BACKEND=opengl ?", .{}); - std.process.exit(1); - } - - // Print which adapter we are going to use. - var props = std.mem.zeroes(gpu.Adapter.Properties); - response.adapter.getProperties(&props); - if (props.backend_type == .null) { - log.err("no backend found for {s} adapter", .{props.adapter_type.name()}); - std.process.exit(1); - } - log.info("found {s} backend on {s} adapter: {s}, {s}\n", .{ - props.backend_type.name(), - props.adapter_type.name(), - props.name, - props.driver_description, - }); - - // Create a device with default limits/features. - const gpu_device = response.adapter.createDevice(&.{ - .required_features_count = if (options.required_features) |v| @as(u32, @intCast(v.len)) else 0, - .required_features = if (options.required_features) |v| @as(?[*]const gpu.FeatureName, v.ptr) else null, - .required_limits = if (options.required_limits) |limits| @as(?*const gpu.RequiredLimits, &gpu.RequiredLimits{ - .limits = limits, - }) else null, - .device_lost_callback = &deviceLostCallback, - .device_lost_userdata = null, - }) orelse { - log.err("failed to create GPU device\n", .{}); - std.process.exit(1); - }; - gpu_device.setUncapturedErrorCallback({}, util.printUnhandledErrorCallback); - - const framebuffer_size = window.getFramebufferSize(); - const swap_chain_desc = gpu.SwapChain.Descriptor{ - .label = "main swap chain", - .usage = .{ .render_attachment = true }, - .format = .bgra8_unorm, - .width = framebuffer_size.width, - .height = framebuffer_size.height, - .present_mode = .fifo, - }; - const swap_chain = gpu_device.createSwapChain(surface, &swap_chain_desc); - - // The initial capacity we choose for the event queue is 2x our maximum expected event rate per - // frame. Specifically, 1000hz mouse updates are likely the maximum event rate we will encounter - // so we anticipate 2x that. If the event rate is higher than this per frame, it will grow to - // that maximum (we never shrink the event queue capacity in order to avoid allocations causing - // any stutter.) - var events = EventQueue.init(allocator); - try events.ensureTotalCapacity(2048); - - core.* = .{ - .allocator = allocator, - .window = window, - .backend_type = backend_type, - .user_ptr = undefined, - - .instance = instance, - .surface = surface, - .gpu_adapter = response.adapter, - .gpu_device = gpu_device, - .swap_chain = swap_chain, - .swap_chain_desc = swap_chain_desc, - - .events = events, - .wait_timeout = 0.0, - - .last_size = window.getSize(), - .last_pos = window.getPos(), - .size_limit = .{ - .min = .{ .width = 350, .height = 350 }, - .max = .{ .width = null, .height = null }, - }, - .frame_buffer_resized = false, - .display_mode = .windowed, - .border = true, - - .current_cursor = .arrow, - .cursors = std.mem.zeroes([@typeInfo(CursorShape).Enum.fields.len]?glfw.Cursor), - .cursors_tried = std.mem.zeroes([@typeInfo(CursorShape).Enum.fields.len]bool), - - .linux_gamemode = null, - }; - - core.setSizeLimit(core.size_limit); - - core.initCallbacks(); - if (builtin.os.tag == .linux and !options.is_app and - core.linux_gamemode == null and try wantGamemode(core.allocator)) - core.linux_gamemode = initLinuxGamemode(); -} - -fn initCallbacks(self: *Core) void { - self.user_ptr = UserPtr{ .self = self }; - - self.window.setUserPointer(&self.user_ptr); - - const key_callback = struct { - fn callback(window: glfw.Window, key: glfw.Key, scancode: i32, action: glfw.Action, mods: glfw.Mods) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - const key_event = KeyEvent{ - .key = toMachKey(key), - .mods = toMachMods(mods), - }; - switch (action) { - .press => pf.pushEvent(.{ .key_press = key_event }), - .repeat => pf.pushEvent(.{ .key_repeat = key_event }), - .release => pf.pushEvent(.{ .key_release = key_event }), - } - _ = scancode; - } - }.callback; - self.window.setKeyCallback(key_callback); - - const char_callback = struct { - fn callback(window: glfw.Window, codepoint: u21) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - pf.pushEvent(.{ - .char_input = .{ - .codepoint = codepoint, - }, - }); - } - }.callback; - self.window.setCharCallback(char_callback); - - const mouse_motion_callback = struct { - fn callback(window: glfw.Window, xpos: f64, ypos: f64) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - pf.pushEvent(.{ - .mouse_motion = .{ - .pos = .{ - .x = xpos, - .y = ypos, - }, - }, - }); - } - }.callback; - self.window.setCursorPosCallback(mouse_motion_callback); - - const mouse_button_callback = struct { - fn callback(window: glfw.Window, button: glfw.mouse_button.MouseButton, action: glfw.Action, mods: glfw.Mods) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - const cursor_pos = pf.window.getCursorPos(); - const mouse_button_event = MouseButtonEvent{ - .button = toMachButton(button), - .pos = .{ .x = cursor_pos.xpos, .y = cursor_pos.ypos }, - .mods = toMachMods(mods), - }; - switch (action) { - .press => pf.pushEvent(.{ .mouse_press = mouse_button_event }), - .release => pf.pushEvent(.{ - .mouse_release = mouse_button_event, - }), - else => {}, - } - } - }.callback; - self.window.setMouseButtonCallback(mouse_button_callback); - - const scroll_callback = struct { - fn callback(window: glfw.Window, xoffset: f64, yoffset: f64) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - pf.pushEvent(.{ - .mouse_scroll = .{ - .xoffset = @as(f32, @floatCast(xoffset)), - .yoffset = @as(f32, @floatCast(yoffset)), - }, - }); - } - }.callback; - self.window.setScrollCallback(scroll_callback); - - const focus_callback = struct { - fn callback(window: glfw.Window, focused: bool) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - pf.pushEvent(if (focused) .focus_gained else .focus_lost); - } - }.callback; - self.window.setFocusCallback(focus_callback); - - const framebuffer_size_callback = struct { - fn callback(window: glfw.Window, _: u32, _: u32) void { - const pf = (window.getUserPointer(UserPtr) orelse unreachable).self; - pf.frame_buffer_resized = true; - } - }.callback; - self.window.setFramebufferSizeCallback(framebuffer_size_callback); -} - -fn pushEvent(self: *Core, event: Event) void { - // TODO(core): handle OOM via error flag - self.events.writeItem(event) catch unreachable; -} - -pub fn deinit(self: *Core) void { - for (self.cursors) |glfw_cursor| { - if (glfw_cursor) |cur| { - cur.destroy(); - } - } - self.events.deinit(); - - if (builtin.os.tag == .linux and - self.linux_gamemode != null and - self.linux_gamemode.?) - deinitLinuxGamemode(); -} - -pub inline fn pollEvents(self: *Core) EventIterator { - if (self.wait_timeout > 0.0) { - if (self.wait_timeout == std.math.inf(f64)) { - // Wait for an event - glfw.waitEvents(); - } else { - // Wait for an event with a timeout - glfw.waitEventsTimeout(self.wait_timeout); - } - } else { - // Don't wait for events - glfw.pollEvents(); - } - - glfw.getErrorCode() catch |err| switch (err) { - error.PlatformError => log.err("glfw: failed to poll events", .{}), - error.InvalidValue => unreachable, - else => unreachable, - }; - - if (self.frame_buffer_resized) blk: { - self.frame_buffer_resized = false; - - const framebuffer_size = self.window.getFramebufferSize(); - glfw.getErrorCode() catch break :blk; - - if (framebuffer_size.width != 0 and framebuffer_size.height != 0) { - self.swap_chain_desc.width = framebuffer_size.width; - self.swap_chain_desc.height = framebuffer_size.height; - self.swap_chain = self.gpu_device.createSwapChain(self.surface, &self.swap_chain_desc); - self.pushEvent(.{ - .framebuffer_resize = .{ - .width = framebuffer_size.width, - .height = framebuffer_size.height, - }, - }); - } - } - - if (self.window.shouldClose()) { - self.pushEvent(.close); - } - - return EventIterator{ .queue = &self.events }; -} - -pub fn shouldClose(self: *Core) bool { - return self.window.shouldClose(); -} - -pub fn framebufferSize(self: *Core) Size { - const framebuffer_size = self.window.getFramebufferSize(); - return .{ - .width = framebuffer_size.width, - .height = framebuffer_size.height, - }; -} - -pub fn setWaitTimeout(self: *Core, timeout: f64) void { - self.wait_timeout = timeout; -} - -pub fn setTitle(self: *Core, title: [:0]const u8) void { - self.window.setTitle(title); -} - -pub fn setDisplayMode(self: *Core, mode: DisplayMode, monitor_index: ?usize) void { - switch (mode) { - .windowed => { - self.window.setAttrib(.decorated, self.border); - self.window.setAttrib(.floating, false); - self.window.setMonitor( - null, - @as(i32, @intCast(self.last_pos.x)), - @as(i32, @intCast(self.last_pos.y)), - self.last_size.width, - self.last_size.height, - null, - ); - }, - .fullscreen => { - if (self.display_mode == .windowed) { - self.last_size = self.window.getSize(); - self.last_pos = self.window.getPos(); - } - - const monitor = blk: { - if (monitor_index) |i| { - // TODO(core): handle OOM via error flag - const monitor_list = glfw.Monitor.getAll(self.allocator) catch unreachable; - defer self.allocator.free(monitor_list); - break :blk monitor_list[i]; - } - break :blk glfw.Monitor.getPrimary(); - }; - if (monitor) |m| { - const video_mode = m.getVideoMode(); - if (video_mode) |v| { - self.window.setMonitor(m, 0, 0, v.getWidth(), v.getHeight(), null); - } - } - }, - .borderless => { - if (self.display_mode == .windowed) { - self.last_size = self.window.getSize(); - self.last_pos = self.window.getPos(); - } - - const monitor = blk: { - if (monitor_index) |i| { - // TODO(core): handle OOM via error flag - const monitor_list = glfw.Monitor.getAll(self.allocator) catch unreachable; - defer self.allocator.free(monitor_list); - break :blk monitor_list[i]; - } - break :blk glfw.Monitor.getPrimary(); - }; - if (monitor) |m| { - const video_mode = m.getVideoMode(); - if (video_mode) |v| { - self.window.setAttrib(.decorated, false); - self.window.setAttrib(.floating, true); - self.window.setMonitor(null, 0, 0, v.getWidth(), v.getHeight(), null); - } - } - }, - } - self.display_mode = mode; -} - -pub fn displayMode(self: *Core) DisplayMode { - return self.display_mode; -} - -pub fn setBorder(self: *Core, value: bool) void { - if (self.border != value) { - self.border = value; - if (self.display_mode != .borderless) self.window.setAttrib(.decorated, value); - } -} - -pub fn border(self: *Core) bool { - return self.border; -} - -pub fn setHeadless(self: *Core, value: bool) void { - if (value) { - self.window.hide(); - } else { - self.window.show(); - } -} - -pub fn headless(self: *Core) bool { - const visible = self.window.getAttrib(.visible); - return visible == 0; -} - -pub fn setVSync(self: *Core, mode: VSyncMode) void { - const framebuffer_size = self.framebufferSize(); - self.swap_chain_desc.present_mode = switch (mode) { - .none => .immediate, - .double => .fifo, - .triple => .mailbox, - }; - self.swap_chain_desc.width = framebuffer_size.width; - self.swap_chain_desc.height = framebuffer_size.height; - self.swap_chain = self.gpu_device.createSwapChain(self.surface, &self.swap_chain_desc); -} - -pub fn vsync(self: *Core) VSyncMode { - return switch (self.swap_chain_desc.present_mode) { - .immediate => .none, - .fifo => .double, - .mailbox => .triple, - }; -} - -pub fn setSize(self: *Core, value: Size) void { - self.window.setSize(.{ - .width = value.width, - .height = value.height, - }); -} - -pub fn size(self: *Core) Size { - const window_size = self.window.getSize(); - return .{ .width = window_size.width, .height = window_size.height }; -} - -pub fn setSizeLimit(self: *Core, limit: SizeLimit) void { - self.window.setSizeLimits( - .{ .width = limit.min.width, .height = limit.min.height }, - .{ .width = limit.max.width, .height = limit.max.height }, - ); - self.size_limit = limit; -} - -pub fn sizeLimit(self: *Core) SizeLimit { - return self.size_limit; -} - -pub fn setCursorMode(self: *Core, mode: CursorMode) void { - const glfw_mode: glfw.Window.InputModeCursor = switch (mode) { - .normal => .normal, - .hidden => .hidden, - .disabled => .disabled, - }; - self.window.setInputModeCursor(glfw_mode); -} - -pub fn cursorMode(self: *Core) CursorMode { - const glfw_mode = self.window.getInputModeCursor(); - return switch (glfw_mode) { - .normal => .normal, - .hidden => .hidden, - .disabled => .disabled, - }; -} - -pub fn setCursorShape(self: *Core, cursor: CursorShape) void { - // Try to create glfw standard cursor, but could fail. In the future - // we hope to provide custom backup images for these. - // See https://github.com/hexops/mach/pull/352 for more info - - const enum_int = @intFromEnum(cursor); - const tried = self.cursors_tried[enum_int]; - if (!tried) { - self.cursors_tried[enum_int] = true; - self.cursors[enum_int] = switch (cursor) { - .arrow => glfw.Cursor.createStandard(.arrow) catch null, - .ibeam => glfw.Cursor.createStandard(.ibeam) catch null, - .crosshair => glfw.Cursor.createStandard(.crosshair) catch null, - .pointing_hand => glfw.Cursor.createStandard(.pointing_hand) catch null, - .resize_ew => glfw.Cursor.createStandard(.resize_ew) catch null, - .resize_ns => glfw.Cursor.createStandard(.resize_ns) catch null, - .resize_nwse => glfw.Cursor.createStandard(.resize_nwse) catch null, - .resize_nesw => glfw.Cursor.createStandard(.resize_nesw) catch null, - .resize_all => glfw.Cursor.createStandard(.resize_all) catch null, - .not_allowed => glfw.Cursor.createStandard(.not_allowed) catch null, - }; - } - - if (self.cursors[enum_int]) |cur| { - self.window.setCursor(cur); - } else { - // TODO: In the future we shouldn't hit this because we'll provide backup - // custom cursors. - // See https://github.com/hexops/mach/pull/352 for more info - log.warn("setCursorShape: {s} not yet supported\n", .{@tagName(cursor)}); - } - - self.current_cursor = cursor; -} - -pub fn cursorShape(self: *Core) CursorShape { - return self.current_cursor; -} - -pub fn adapter(self: *Core) *gpu.Adapter { - return self.gpu_adapter; -} - -pub fn device(self: *Core) *gpu.Device { - return self.gpu_device; -} - -pub fn swapChain(self: *Core) *gpu.SwapChain { - return self.swap_chain; -} - -pub fn descriptor(self: *Core) gpu.SwapChain.Descriptor { - return self.swap_chain_desc; -} - -fn toMachButton(button: glfw.mouse_button.MouseButton) MouseButton { - return switch (button) { - .left => .left, - .right => .right, - .middle => .middle, - .four => .four, - .five => .five, - .six => .six, - .seven => .seven, - .eight => .eight, - }; -} - -fn toMachKey(key: glfw.Key) Key { - return switch (key) { - .a => .a, - .b => .b, - .c => .c, - .d => .d, - .e => .e, - .f => .f, - .g => .g, - .h => .h, - .i => .i, - .j => .j, - .k => .k, - .l => .l, - .m => .m, - .n => .n, - .o => .o, - .p => .p, - .q => .q, - .r => .r, - .s => .s, - .t => .t, - .u => .u, - .v => .v, - .w => .w, - .x => .x, - .y => .y, - .z => .z, - - .zero => .zero, - .one => .one, - .two => .two, - .three => .three, - .four => .four, - .five => .five, - .six => .six, - .seven => .seven, - .eight => .eight, - .nine => .nine, - - .F1 => .f1, - .F2 => .f2, - .F3 => .f3, - .F4 => .f4, - .F5 => .f5, - .F6 => .f6, - .F7 => .f7, - .F8 => .f8, - .F9 => .f9, - .F10 => .f10, - .F11 => .f11, - .F12 => .f12, - .F13 => .f13, - .F14 => .f14, - .F15 => .f15, - .F16 => .f16, - .F17 => .f17, - .F18 => .f18, - .F19 => .f19, - .F20 => .f20, - .F21 => .f21, - .F22 => .f22, - .F23 => .f23, - .F24 => .f24, - .F25 => .f25, - - .kp_divide => .kp_divide, - .kp_multiply => .kp_multiply, - .kp_subtract => .kp_subtract, - .kp_add => .kp_add, - .kp_0 => .kp_0, - .kp_1 => .kp_1, - .kp_2 => .kp_2, - .kp_3 => .kp_3, - .kp_4 => .kp_4, - .kp_5 => .kp_5, - .kp_6 => .kp_6, - .kp_7 => .kp_7, - .kp_8 => .kp_8, - .kp_9 => .kp_9, - .kp_decimal => .kp_decimal, - .kp_equal => .kp_equal, - .kp_enter => .kp_enter, - - .enter => .enter, - .escape => .escape, - .tab => .tab, - .left_shift => .left_shift, - .right_shift => .right_shift, - .left_control => .left_control, - .right_control => .right_control, - .left_alt => .left_alt, - .right_alt => .right_alt, - .left_super => .left_super, - .right_super => .right_super, - .menu => .menu, - .num_lock => .num_lock, - .caps_lock => .caps_lock, - .print_screen => .print, - .scroll_lock => .scroll_lock, - .pause => .pause, - .delete => .delete, - .home => .home, - .end => .end, - .page_up => .page_up, - .page_down => .page_down, - .insert => .insert, - .left => .left, - .right => .right, - .up => .up, - .down => .down, - .backspace => .backspace, - .space => .space, - .minus => .minus, - .equal => .equal, - .left_bracket => .left_bracket, - .right_bracket => .right_bracket, - .backslash => .backslash, - .semicolon => .semicolon, - .apostrophe => .apostrophe, - .comma => .comma, - .period => .period, - .slash => .slash, - .grave_accent => .grave, - - .world_1 => .unknown, - .world_2 => .unknown, - .unknown => .unknown, - }; -} - -fn toMachMods(mods: glfw.Mods) KeyMods { - return .{ - .shift = mods.shift, - .control = mods.control, - .alt = mods.alt, - .super = mods.super, - .caps_lock = mods.caps_lock, - .num_lock = mods.num_lock, - }; -} - -/// Default GLFW error handling callback -fn errorCallback(error_code: glfw.ErrorCode, description: [:0]const u8) void { - log.err("glfw: {}: {s}\n", .{ error_code, description }); -} - -fn getEnvVarOwned(allocator: std.mem.Allocator, key: []const u8) error{ OutOfMemory, InvalidUtf8 }!?[]u8 { - return std.process.getEnvVarOwned(allocator, key) catch |err| switch (err) { - error.EnvironmentVariableNotFound => @as(?[]u8, null), - else => |e| e, - }; -} - -/// Check if gamemode should be activated -fn wantGamemode(allocator: std.mem.Allocator) error{ OutOfMemory, InvalidUtf8 }!bool { - if (try getEnvVarOwned(allocator, "MACH_USE_GAMEMODE")) |env| { - defer allocator.free(env); - return !(std.ascii.eqlIgnoreCase(env, "off") or std.ascii.eqlIgnoreCase(env, "false")); - } - return true; -} - -fn initLinuxGamemode() bool { - const gamemode = @import("gamemode"); - gamemode.start(); - if (!gamemode.isActive()) return false; - log.info("gamemode: activated", .{}); - return true; -} - -fn deinitLinuxGamemode() void { - const gamemode = @import("gamemode"); - gamemode.stop(); -} diff --git a/libs/core/src/platform/native/entry.zig b/libs/core/src/platform/native/entry.zig deleted file mode 100644 index 912ef374..00000000 --- a/libs/core/src/platform/native/entry.zig +++ /dev/null @@ -1,35 +0,0 @@ -const std = @import("std"); -const App = @import("app").App; -const core = @import("core"); -const gpu = core.gpu; - -pub const GPUInterface = gpu.dawn.Interface; - -const app_std_options = if (@hasDecl(App, "std_options")) App.std_options else struct {}; - -pub const std_options = struct { - pub const log_level = if (@hasDecl(app_std_options, "log_level")) - app_std_options.log_level - else - std.log.default_level; - - pub const log_scope_levels = if (@hasDecl(App, "log_scope_levels")) - app_std_options.log_scope_levels - else - &[0]std.log.ScopeLevel{}; -}; - -pub fn main() !void { - gpu.Impl.init(); - _ = gpu.Export(GPUInterface); - - var app: App = undefined; - try app.init(); - defer app.deinit(); - - while (true) { - const pool = try core.platform_util.AutoReleasePool.init(); - defer core.platform_util.AutoReleasePool.release(pool); - if (try app.update()) return; - } -} diff --git a/libs/core/src/platform/native/objc_message.zig b/libs/core/src/platform/native/objc_message.zig deleted file mode 100644 index e039b4a9..00000000 --- a/libs/core/src/platform/native/objc_message.zig +++ /dev/null @@ -1,7 +0,0 @@ -// Extracted from `zig translate-c tmp.c` with `#include ` in the file. -pub const SEL = opaque {}; -pub const Class = opaque {}; - -pub extern fn sel_getUid(str: [*c]const u8) ?*SEL; -pub extern fn objc_getClass(name: [*c]const u8) ?*Class; -pub extern fn objc_msgSend() void; diff --git a/libs/core/src/platform/native/util.zig b/libs/core/src/platform/native/util.zig deleted file mode 100644 index 314f26ad..00000000 --- a/libs/core/src/platform/native/util.zig +++ /dev/null @@ -1,187 +0,0 @@ -const std = @import("std"); - -const glfw = @import("glfw"); -const gpu = @import("gpu"); -const objc = @import("objc_message.zig"); - -pub inline fn printUnhandledErrorCallback(_: void, typ: gpu.ErrorType, message: [*:0]const u8) void { - switch (typ) { - .validation => std.log.err("gpu: validation error: {s}\n", .{message}), - .out_of_memory => std.log.err("gpu: out of memory: {s}\n", .{message}), - .device_lost => std.log.err("gpu: device lost: {s}\n", .{message}), - .unknown => std.log.err("gpu: unknown error: {s}\n", .{message}), - else => unreachable, - } - std.os.exit(1); -} - -fn getEnvVarOwned(allocator: std.mem.Allocator, key: []const u8) error{ OutOfMemory, InvalidUtf8 }!?[]u8 { - return std.process.getEnvVarOwned(allocator, key) catch |err| switch (err) { - error.EnvironmentVariableNotFound => @as(?[]u8, null), - else => |e| e, - }; -} - -pub fn detectBackendType(allocator: std.mem.Allocator) !gpu.BackendType { - const MACH_GPU_BACKEND = try getEnvVarOwned(allocator, "MACH_GPU_BACKEND"); - if (MACH_GPU_BACKEND) |backend| { - defer allocator.free(backend); - if (std.ascii.eqlIgnoreCase(backend, "null")) return .null; - if (std.ascii.eqlIgnoreCase(backend, "d3d11")) return .d3d11; - if (std.ascii.eqlIgnoreCase(backend, "d3d12")) return .d3d12; - if (std.ascii.eqlIgnoreCase(backend, "metal")) return .metal; - if (std.ascii.eqlIgnoreCase(backend, "vulkan")) return .vulkan; - if (std.ascii.eqlIgnoreCase(backend, "opengl")) return .opengl; - if (std.ascii.eqlIgnoreCase(backend, "opengles")) return .opengles; - @panic("unknown MACH_GPU_BACKEND type"); - } - - const target = @import("builtin").target; - if (target.isDarwin()) return .metal; - if (target.os.tag == .windows) return .d3d12; - return .vulkan; -} - -pub const RequestAdapterResponse = struct { - status: gpu.RequestAdapterStatus, - adapter: *gpu.Adapter, - message: ?[*:0]const u8, -}; - -pub inline fn requestAdapterCallback( - context: *RequestAdapterResponse, - status: gpu.RequestAdapterStatus, - adapter: *gpu.Adapter, - message: ?[*:0]const u8, -) void { - context.* = RequestAdapterResponse{ - .status = status, - .adapter = adapter, - .message = message, - }; -} - -pub fn glfwWindowHintsForBackend(backend: gpu.BackendType) glfw.Window.Hints { - return switch (backend) { - .opengl => .{ - // Ask for OpenGL 4.4 which is what the GL backend requires for compute shaders and - // texture views. - .context_version_major = 4, - .context_version_minor = 4, - .opengl_forward_compat = true, - .opengl_profile = .opengl_core_profile, - }, - .opengles => .{ - .context_version_major = 3, - .context_version_minor = 1, - .client_api = .opengl_es_api, - .context_creation_api = .egl_context_api, - }, - else => .{ - // Without this GLFW will initialize a GL context on the window, which prevents using - // the window with other APIs (by crashing in weird ways). - .client_api = .no_api, - }, - }; -} - -pub fn detectGLFWOptions() glfw.BackendOptions { - const target = @import("builtin").target; - if (target.isDarwin()) return .{ .cocoa = true }; - return switch (target.os.tag) { - .windows => .{ .win32 = true }, - .linux => .{ .x11 = true, .wayland = true }, - else => .{}, - }; -} - -pub fn createSurfaceForWindow( - instance: *gpu.Instance, - window: glfw.Window, - comptime glfw_options: glfw.BackendOptions, -) *gpu.Surface { - const glfw_native = glfw.Native(glfw_options); - const extension = if (glfw_options.win32) gpu.Surface.Descriptor.NextInChain{ - .from_windows_hwnd = &.{ - .hinstance = std.os.windows.kernel32.GetModuleHandleW(null).?, - .hwnd = glfw_native.getWin32Window(window), - }, - } else if (glfw_options.x11) gpu.Surface.Descriptor.NextInChain{ - .from_xlib_window = &.{ - .display = glfw_native.getX11Display(), - .window = glfw_native.getX11Window(window), - }, - } else if (glfw_options.wayland) gpu.Surface.Descriptor.NextInChain{ - .from_wayland_surface = &.{ - .display = glfw_native.getWaylandDisplay(), - .surface = glfw_native.getWaylandWindow(window), - }, - } else if (glfw_options.cocoa) blk: { - const ns_window = glfw_native.getCocoaWindow(window); - const ns_view = msgSend(ns_window, "contentView", .{}, *anyopaque); // [nsWindow contentView] - - // Create a CAMetalLayer that covers the whole window that will be passed to CreateSurface. - msgSend(ns_view, "setWantsLayer:", .{true}, void); // [view setWantsLayer:YES] - const layer = msgSend(objc.objc_getClass("CAMetalLayer"), "layer", .{}, ?*anyopaque); // [CAMetalLayer layer] - if (layer == null) @panic("failed to create Metal layer"); - msgSend(ns_view, "setLayer:", .{layer.?}, void); // [view setLayer:layer] - - // Use retina if the window was created with retina support. - const scale_factor = msgSend(ns_window, "backingScaleFactor", .{}, f64); // [ns_window backingScaleFactor] - msgSend(layer.?, "setContentsScale:", .{scale_factor}, void); // [layer setContentsScale:scale_factor] - - break :blk gpu.Surface.Descriptor.NextInChain{ .from_metal_layer = &.{ .layer = layer.? } }; - } else unreachable; - - return instance.createSurface(&gpu.Surface.Descriptor{ - .next_in_chain = extension, - }); -} - -pub const AutoReleasePool = if (!@import("builtin").target.isDarwin()) opaque { - pub fn init() error{OutOfMemory}!?*AutoReleasePool { - return null; - } - - pub fn release(pool: ?*AutoReleasePool) void { - _ = pool; - return; - } -} else opaque { - pub fn init() error{OutOfMemory}!?*AutoReleasePool { - // pool = [NSAutoreleasePool alloc]; - var pool = msgSend(objc.objc_getClass("NSAutoreleasePool"), "alloc", .{}, ?*AutoReleasePool); - if (pool == null) return error.OutOfMemory; - - // pool = [pool init]; - pool = msgSend(pool, "init", .{}, ?*AutoReleasePool); - if (pool == null) unreachable; - - return pool; - } - - pub fn release(pool: ?*AutoReleasePool) void { - // [pool release]; - msgSend(pool, "release", .{}, void); - } -}; - -// Borrowed from https://github.com/hazeycode/zig-objcrt -pub fn msgSend(obj: anytype, sel_name: [:0]const u8, args: anytype, comptime ReturnType: type) ReturnType { - const args_meta = @typeInfo(@TypeOf(args)).Struct.fields; - - const FnType = switch (args_meta.len) { - 0 => *const fn (@TypeOf(obj), ?*objc.SEL) callconv(.C) ReturnType, - 1 => *const fn (@TypeOf(obj), ?*objc.SEL, args_meta[0].type) callconv(.C) ReturnType, - 2 => *const fn (@TypeOf(obj), ?*objc.SEL, args_meta[0].type, args_meta[1].type) callconv(.C) ReturnType, - 3 => *const fn (@TypeOf(obj), ?*objc.SEL, args_meta[0].type, args_meta[1].type, args_meta[2].type) callconv(.C) ReturnType, - 4 => *const fn (@TypeOf(obj), ?*objc.SEL, args_meta[0].type, args_meta[1].type, args_meta[2].type, args_meta[3].type) callconv(.C) ReturnType, - else => @compileError("Unsupported number of args"), - }; - - // NOTE: func is a var because making it const causes a compile error which I believe is a compiler bug - var func = @as(FnType, @ptrCast(&objc.objc_msgSend)); - const sel = objc.sel_getUid(@as([*c]const u8, @ptrCast(sel_name))); - - return @call(.auto, func, .{ obj, sel } ++ args); -} diff --git a/libs/core/src/platform/wasm.zig b/libs/core/src/platform/wasm.zig deleted file mode 100644 index 79f799f9..00000000 --- a/libs/core/src/platform/wasm.zig +++ /dev/null @@ -1,2 +0,0 @@ -pub const Core = @import("wasm/Core.zig"); -pub const Timer = @import("wasm/Timer.zig"); diff --git a/libs/core/src/platform/wasm/Core.zig b/libs/core/src/platform/wasm/Core.zig deleted file mode 100644 index ccc4f67a..00000000 --- a/libs/core/src/platform/wasm/Core.zig +++ /dev/null @@ -1,307 +0,0 @@ -const std = @import("std"); -const gpu = @import("gpu"); -const js = @import("js.zig"); -const Timer = @import("Timer.zig"); -const Options = @import("../../Core.zig").Options; -const Event = @import("../../Core.zig").Event; -const KeyEvent = @import("../../Core.zig").KeyEvent; -const MouseButtonEvent = @import("../../Core.zig").MouseButtonEvent; -const MouseButton = @import("../../Core.zig").MouseButton; -const Size = @import("../../Core.zig").Size; -const Position = @import("../../Core.zig").Position; -const DisplayMode = @import("../../Core.zig").DisplayMode; -const SizeLimit = @import("../../Core.zig").SizeLimit; -const CursorShape = @import("../../Core.zig").CursorShape; -const VSyncMode = @import("../../Core.zig").VSyncMode; -const CursorMode = @import("../../Core.zig").CursorMode; -const Key = @import("../../Core.zig").Key; -const KeyMods = @import("../../Core.zig").KeyMods; - -pub const Core = @This(); - -allocator: std.mem.Allocator, -id: js.CanvasId, - -pub const EventIterator = struct { - key_mods: KeyMods, - last_cursor_position: Position, - - pub inline fn next(self: *EventIterator) ?Event { - while (true) { - const event_int = js.machEventShift(); - if (event_int == -1) return null; - - const event_type = @as(std.meta.Tag(Event), @enumFromInt(event_int)); - return switch (event_type) { - .key_press, .key_repeat => blk: { - const key = @as(Key, @enumFromInt(js.machEventShift())); - switch (key) { - .left_shift, .right_shift => self.key_mods.shift = true, - .left_control, .right_control => self.key_mods.control = true, - .left_alt, .right_alt => self.key_mods.alt = true, - .left_super, .right_super => self.key_mods.super = true, - .caps_lock => self.key_mods.caps_lock = true, - .num_lock => self.key_mods.num_lock = true, - else => { - break :blk switch (event_type) { - .key_press => Event{ - .key_press = .{ - .key = key, - .mods = self.key_mods, - }, - }, - .key_repeat => Event{ - .key_repeat = .{ - .key = key, - .mods = self.key_mods, - }, - }, - else => unreachable, - }; - }, - } - continue; - }, - .key_release => blk: { - const key = @as(Key, @enumFromInt(js.machEventShift())); - switch (key) { - .left_shift, .right_shift => self.key_mods.shift = false, - .left_control, .right_control => self.key_mods.control = false, - .left_alt, .right_alt => self.key_mods.alt = false, - .left_super, .right_super => self.key_mods.super = false, - .caps_lock => self.key_mods.caps_lock = false, - .num_lock => self.key_mods.num_lock = false, - else => { - break :blk Event{ - .key_release = .{ - .key = key, - .mods = self.key_mods, - }, - }; - }, - } - continue; - }, - .mouse_motion => blk: { - const x = @as(f64, @floatFromInt(js.machEventShift())); - const y = @as(f64, @floatFromInt(js.machEventShift())); - self.last_cursor_position = .{ - .x = x, - .y = y, - }; - break :blk Event{ - .mouse_motion = .{ - .pos = .{ - .x = x, - .y = y, - }, - }, - }; - }, - .mouse_press => Event{ - .mouse_press = .{ - .button = toMachButton(js.machEventShift()), - .pos = self.last_cursor_position, - .mods = self.key_mods, - }, - }, - .mouse_release => Event{ - .mouse_release = .{ - .button = toMachButton(js.machEventShift()), - .pos = self.last_cursor_position, - .mods = self.key_mods, - }, - }, - .mouse_scroll => Event{ - .mouse_scroll = .{ - .xoffset = @as(f32, @floatCast(std.math.sign(js.machEventShiftFloat()))), - .yoffset = @as(f32, @floatCast(std.math.sign(js.machEventShiftFloat()))), - }, - }, - .framebuffer_resize => blk: { - const width = @as(u32, @intCast(js.machEventShift())); - const height = @as(u32, @intCast(js.machEventShift())); - const pixel_ratio = @as(u32, @intCast(js.machEventShift())); - break :blk Event{ - .framebuffer_resize = .{ - .width = width * pixel_ratio, - .height = height * pixel_ratio, - }, - }; - }, - .focus_gained => Event.focus_gained, - .focus_lost => Event.focus_lost, - else => null, - }; - } - } -}; - -pub fn init(core: *Core, allocator: std.mem.Allocator, options: Options) !void { - _ = options; - var selector = [1]u8{0} ** 15; - const id = js.machCanvasInit(&selector[0]); - - core.* = Core{ - .allocator = allocator, - .id = id, - }; -} - -pub fn deinit(self: *Core) void { - js.machCanvasDeinit(self.id); -} - -pub inline fn pollEvents(self: *Core) EventIterator { - _ = self; - return EventIterator{ - .key_mods = .{ - .shift = false, - .control = false, - .alt = false, - .super = false, - .caps_lock = false, - .num_lock = false, - }, - .last_cursor_position = .{ - .x = 0, - .y = 0, - }, - }; -} - -pub fn framebufferSize(self: *Core) Size { - return .{ - .width = js.machCanvasFramebufferWidth(self.id), - .height = js.machCanvasFramebufferHeight(self.id), - }; -} - -pub fn setWaitTimeout(_: *Core, timeout: f64) void { - js.machSetWaitTimeout(timeout); -} - -pub fn setTitle(self: *Core, title: [:0]const u8) void { - js.machCanvasSetTitle(self.id, title.ptr, title.len); -} - -pub fn setDisplayMode(self: *Core, mode: DisplayMode, monitor: ?usize) void { - _ = monitor; - if (mode == .borderless) { - // borderless fullscreen window has no meaning in web - mode = .fullscreen; - } - js.machCanvasSetDisplayMode(self.id, @intFromEnum(mode)); -} - -pub fn displayMode(self: *Core) DisplayMode { - return @as(DisplayMode, @enumFromInt(js.machDisplayMode(self.id))); -} - -pub fn setBorder(self: *Core, value: bool) void { - _ = self; - _ = value; -} - -pub fn border(self: *Core) bool { - _ = self; - return false; -} - -pub fn setHeadless(self: *Core, value: bool) void { - _ = self; - _ = value; -} - -pub fn headless(self: *Core) bool { - _ = self; - return false; -} - -pub fn setVSync(self: *Core, mode: VSyncMode) void { - _ = self; - _ = mode; -} - -// TODO: https://github.com/gpuweb/gpuweb/issues/1224 -pub fn vsync(self: *Core) VSyncMode { - _ = self; - return .double; -} - -pub fn setSize(self: *Core, value: Size) void { - js.machCanvasSetSize(self.id, value.width, value.height); -} - -pub fn size(self: *Core) Size { - return .{ - .width = js.machCanvasWidth(self.id), - .height = js.machCanvasHeight(self.id), - }; -} - -pub fn setSizeLimit(self: *Core, limit: SizeLimit) void { - js.machCanvasSetSizeLimit( - self.id, - if (limit.min.width) |val| @as(i32, @intCast(val)) else -1, - if (limit.min.height) |val| @as(i32, @intCast(val)) else -1, - if (limit.max.width) |val| @as(i32, @intCast(val)) else -1, - if (limit.max.height) |val| @as(i32, @intCast(val)) else -1, - ); -} - -pub fn sizeLimit(self: *Core) SizeLimit { - return .{ - .min = .{ - .width = js.machCanvasMinWidth(self.id), - .height = js.machCanvasMinHeight(self.id), - }, - .max = .{ - .width = js.machCanvasMaxWidth(self.id), - .height = js.machCanvasMaxHeight(self.id), - }, - }; -} - -pub fn setCursorMode(self: *Core, mode: CursorMode) void { - js.machSetCursorMode(self.id, @intFromEnum(mode)); -} - -pub fn cursorMode(self: *Core) CursorMode { - return @as(CursorMode, @enumFromInt(js.machCursorMode(self.id))); -} - -pub fn setCursorShape(self: *Core, shape: CursorShape) void { - js.machSetCursorShape(self.id, @intFromEnum(shape)); -} - -pub fn cursorShape(self: *Core) CursorShape { - return @as(CursorShape, @enumFromInt(js.machCursorShape(self.id))); -} - -pub fn adapter(_: *Core) *gpu.Adapter { - unreachable; -} - -pub fn device(_: *Core) *gpu.Device { - unreachable; -} - -pub fn swapChain(_: *Core) *gpu.SwapChain { - unreachable; -} - -pub fn descriptor(_: *Core) gpu.SwapChain.Descriptor { - unreachable; -} - -fn toMachButton(button: i32) MouseButton { - return switch (button) { - 0 => .left, - 1 => .middle, - 2 => .right, - 3 => .four, - 4 => .five, - else => unreachable, - }; -} diff --git a/libs/core/src/platform/wasm/Timer.zig b/libs/core/src/platform/wasm/Timer.zig deleted file mode 100644 index dd9e293e..00000000 --- a/libs/core/src/platform/wasm/Timer.zig +++ /dev/null @@ -1,25 +0,0 @@ -const std = @import("std"); -const js = @import("js.zig"); - -pub const Timer = @This(); - -initial: f64 = undefined, - -pub fn start() !Timer { - return Timer{ .initial = js.machPerfNow() }; -} - -pub fn read(timer: *Timer) u64 { - return (js.machPerfNow() - timer.initial) * std.time.ns_per_ms; -} - -pub fn reset(timer: *Timer) void { - timer.initial = js.machPerfNow(); -} - -pub fn lap(timer: *Timer) u64 { - const now = js.machPerfNow(); - const initial = timer.initial; - timer.initial = now; - return @as(u64, @intFromFloat(now - initial)) * std.time.ns_per_ms; -} diff --git a/libs/core/src/platform/wasm/entry.zig b/libs/core/src/platform/wasm/entry.zig deleted file mode 100644 index e2735b1a..00000000 --- a/libs/core/src/platform/wasm/entry.zig +++ /dev/null @@ -1,64 +0,0 @@ -const std = @import("std"); -const core = @import("core"); -const gpu = core.gpu; -const App = @import("app").App; - -pub extern "mach" fn machLogWrite(str: [*]const u8, len: u32) void; -pub extern "mach" fn machLogFlush() void; -pub extern "mach" fn machPanic(str: [*]const u8, len: u32) void; - -pub const GPUInterface = gpu.StubInterface; -const app_std_options = if (@hasDecl(App, "std_options")) App.std_options else struct {}; - -var app: App = undefined; -export fn wasmInit() void { - app.init() catch unreachable; -} - -export fn wasmUpdate() bool { - return app.update() catch unreachable; -} - -export fn wasmDeinit() void { - app.deinit(); -} - -const LogError = error{}; -const LogWriter = std.io.Writer(void, LogError, writeLog); - -fn writeLog(_: void, msg: []const u8) LogError!usize { - machLogWrite(msg.ptr, msg.len); - return msg.len; -} - -pub const std_options = struct { - pub fn logFn( - comptime message_level: std.log.Level, - comptime scope: @Type(.EnumLiteral), - comptime format: []const u8, - args: anytype, - ) void { - const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; - const writer = LogWriter{ .context = {} }; - - writer.print(message_level.asText() ++ prefix ++ format ++ "\n", args) catch return; - machLogFlush(); - } - - pub const log_level = if (@hasDecl(app_std_options, "log_level")) - app_std_options.log_level - else - std.log.default_level; - - pub const log_scope_levels = if (@hasDecl(app_std_options, "log_scope_levels")) - app_std_options.log_scope_levels - else - &[0]std.log.ScopeLevel{}; -}; - -pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn { - _ = error_return_trace; - _ = ret_addr; - machPanic(msg.ptr, msg.len); - unreachable; -} diff --git a/libs/core/src/platform/wasm/js.zig b/libs/core/src/platform/wasm/js.zig deleted file mode 100644 index 0971485c..00000000 --- a/libs/core/src/platform/wasm/js.zig +++ /dev/null @@ -1,40 +0,0 @@ -pub const CanvasId = u32; - -pub extern "mach" fn machLogWrite(str: [*]const u8, len: u32) void; -pub extern "mach" fn machLogFlush() void; -pub extern "mach" fn machPanic(str: [*]const u8, len: u32) void; - -pub extern "mach" fn machCanvasInit(selector_id: *u8) CanvasId; -pub extern "mach" fn machCanvasDeinit(canvas: CanvasId) void; -pub extern "mach" fn machCanvasFramebufferWidth(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasFramebufferHeight(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasSetTitle(canvas: CanvasId, title: [*]const u8, len: u32) void; -pub extern "mach" fn machCanvasSetDisplayMode(canvas: CanvasId, mode: u32) void; -pub extern "mach" fn machCanvasDisplayMode(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasSetBorder(canvas: CanvasId, value: bool) void; -pub extern "mach" fn machCanvasBorder(canvas: CanvasId) bool; -pub extern "mach" fn machCanvasSetHeadless(canvas: CanvasId, value: bool) void; -pub extern "mach" fn machCanvasHeadless(canvas: CanvasId) bool; -pub extern "mach" fn machCanvasSetVsync(canvas: CanvasId, mode: u32) void; -pub extern "mach" fn machCanvasVsync(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasSetSize(canvas: CanvasId, width: u32, height: u32) void; -pub extern "mach" fn machCanvasWidth(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasHeight(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasSetSizeLimit(canvas: CanvasId, min_width: i32, min_height: i32, max_width: i32, max_height: i32) void; -pub extern "mach" fn machCanvasMinWidth(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasMinHeight(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasMaxWidth(canvas: CanvasId) u32; -pub extern "mach" fn machCanvasMaxHeight(canvas: CanvasId) u32; -pub extern "mach" fn machSetCursorMode(canvas: CanvasId, mode: u32) void; -pub extern "mach" fn machCursorMode(canvas: CanvasId) u32; -pub extern "mach" fn machSetCursorShape(canvas: CanvasId, shape: u32) void; -pub extern "mach" fn machCursorShape(canvas: CanvasId) u32; - -pub extern "mach" fn machShouldClose() bool; -pub extern "mach" fn machHasEvent() bool; -pub extern "mach" fn machSetWaitTimeout(timeout: f64) void; -pub extern "mach" fn machEventShift() i32; -pub extern "mach" fn machEventShiftFloat() f64; -pub extern "mach" fn machChangeShift() u32; - -pub extern "mach" fn machPerfNow() f64; diff --git a/libs/core/src/platform/wasm/mach.js b/libs/core/src/platform/wasm/mach.js deleted file mode 100644 index ca87dcd5..00000000 --- a/libs/core/src/platform/wasm/mach.js +++ /dev/null @@ -1,515 +0,0 @@ -const text_decoder = new TextDecoder(); -const text_encoder = new TextEncoder(); - -const mach = { - canvases: [], - wasm: undefined, - observer: undefined, - events: [], - changes: [], - wait_timeout: 0, - log_buf: "", - - init(wasm) { - mach.wasm = wasm; - mach.observer = new MutationObserver((mutables) => { - mutables.forEach((mutable) => { - mach.canvases.forEach((canvas) => { - if (mutable.target == canvas) { - if (mutable.attributeName === "width" || - mutable.attributeName === "height" || - mutable.attributeName === "style") { - mutable.target.dispatchEvent(new Event("mach-canvas-resize")); - } - } - }); - }) - }) - }, - - getString(str, len) { - const memory = mach.wasm.exports.memory.buffer; - return text_decoder.decode(new Uint8Array(memory, str, len)); - }, - - setString(str, buf) { - const memory = mach.wasm.exports.memory.buffer; - const strbuf = text_encoder.encode(str); - const outbuf = new Uint8Array(memory, buf, strbuf.length); - for (let i = 0; i < strbuf.length; i += 1) { - outbuf[i] = strbuf[i]; - } - }, - - machLogWrite(str, len) { - mach.log_buf += mach.getString(str, len); - }, - - machLogFlush() { - console.log(log_buf); - mach.log_buf = ""; - }, - - machPanic(str, len) { - throw Error(mach.getString(str, len)); - }, - - machCanvasInit(id) { - let canvas = document.createElement("canvas"); - canvas.id = "#mach-canvas-" + mach.canvases.length; - canvas.style.border = "1px solid"; - canvas.style.position = "absolute"; - canvas.style.display = "block"; - canvas.tabIndex = 1; - - mach.observer.observe(canvas, { attributes: true }); - - mach.setString(canvas.id, id); - - canvas.addEventListener("contextmenu", (ev) => ev.preventDefault()); - - canvas.addEventListener("keydown", (ev) => { - if (ev.repeat) { - mach.events.push(...[EventCode.key_repeat, convertKeyCode(ev.code)]); - } else { - mach.events.push(...[EventCode.key_press, convertKeyCode(ev.code)]); - } - }); - - canvas.addEventListener("keyup", (ev) => { - mach.events.push(...[EventCode.key_release, convertKeyCode(ev.code)]); - }); - - canvas.addEventListener("mousemove", (ev) => { - mach.events.push(...[EventCode.mouse_motion, ev.clientX, ev.clientY]); - }); - - canvas.addEventListener("mousedown", (ev) => { - mach.events.push(...[EventCode.mouse_press, ev.button]); - }); - - canvas.addEventListener("mouseup", (ev) => { - mach.events.push(...[EventCode.mouse_release, ev.button]); - }); - - canvas.addEventListener("wheel", (ev) => { - mach.events.push(...[EventCode.mouse_scroll, ev.deltaX, ev.deltaY]); - }); - - canvas.addEventListener("mach-canvas-resize", (ev) => { - const cv_index = mach.canvases.findIndex((el) => el === ev.currentTarget); - const cv = mach.canvases[cv_index]; - mach.events.push(...[EventCode.framebuffer_resize, cv.width, cv.height, window.devicePixelRatio]); - }); - - canvas.addEventListener("focus", (ev) => { - mach.events.push(...[EventCode.focus_gained]); - }); - - canvas.addEventListener("blur", (ev) => { - mach.events.push(...[EventCode.focus_lost]); - }); - - document.body.appendChild(canvas); - return mach.canvases.push(canvas) - 1; - }, - - machCanvasDeinit(canvas) { - if (mach.canvases[canvas] != undefined) { - mach.canvases.splice(canvas, 1); - } - }, - - machCanvasFramebufferWidth(canvas) { - const cv = mach.canvases[canvas]; - return cv.width; - }, - - machCanvasFramebufferHeight(canvas) { - const cv = mach.canvases[canvas]; - return cv.height; - }, - - machCanvasSetTitle(canvas, title, len) { - // TODO - }, - - machCanvasSetDisplayMode(canvas, mode) { - const cv = mach.canvases[canvas]; - switch (mode) { - case DisplayMode.windowed: - document.exitFullscreen(); - break; - case DisplayMode.fullscreen: - cv.requestFullscreen(); - break; - } - }, - - machCanvasDisplayMode(canvas) { - if (mach.canvases[canvas].fullscreenElement == null) { - return DisplayMode.windowed; - } else { - return DisplayMode.fullscreen; - } - }, - - machCanvasSetBorder(canvas, value) { - // TODO - }, - - machCanvasBorder(canvas) { - // TODO - }, - - machCanvasSetHeadless(canvas, value) { - // TODO - }, - - machCanvasHeadless(canvas) { - // TODO - }, - - machCanvasSetVSync(canvas, mode) { - // TODO - }, - - machCanvasVSync(canvas) { - // TODO - }, - - machCanvasSetSize(canvas, width, height) { - const cv = mach.canvases[canvas]; - if (width > 0 && height > 0) { - cv.style.width = width + "px"; - cv.style.height = height + "px"; - cv.width = Math.floor(width * window.devicePixelRatio); - cv.height = Math.floor(height * window.devicePixelRatio); - } - }, - - machCanvasWidth(canvas) { - const cv = mach.canvases[canvas]; - return cv.width / window.devicePixelRatio; - }, - - machCanvasHeight(canvas) { - const cv = mach.canvases[canvas]; - return cv.height / window.devicePixelRatio; - }, - - machCanvasSetSizeLimit(canvas, min_width, min_height, max_width, max_height) { - const cv = mach.canvases[canvas]; - if (min_width == -1) { - cv.style.minWidth = "inherit" - } else { - cv.style.minWidth = min_width + "px"; - } - if (min_width == -1) { - cv.style.minHeight = "inherit" - } else { - cv.style.minHeight = min_height + "px"; - } - if (min_width == -1) { - cv.style.maxWidth = "inherit" - } else { - cv.style.maxWidth = max_width + "px"; - } - if (min_width == -1) { - cv.style.maxHeight = "inherit" - } else { - cv.style.maxHeight = max_height + "px"; - } - }, - - machCanvasMinWidth(canvas) { - const cv = mach.canvases[canvas]; - return cv.style.minWidth; - }, - - machCanvasMinHeight(canvas) { - const cv = mach.canvases[canvas]; - return cv.style.minHeight; - }, - - machCanvasMaxWidth(canvas) { - const cv = mach.canvases[canvas]; - return cv.style.maxWidth; - }, - - machCanvasMaxHeight(canvas) { - const cv = mach.canvases[canvas]; - return cv.style.maxHeight; - }, - - machSetCursorMode(canvas, mode) { - const cv = mach.canvases[canvas]; - switch (mode) { - case CursorMode.normal: - cv.style.cursor = 'default'; - break; - case CursorMode.hidden: - cv.style.cursor = 'none'; - break; - case CursorMode.hidden: - cv.style.cursor = 'none'; - break; - } - }, - - machCursorMode(canvas) { - switch (mach.canvases[canvas].style.cursor) { - case 'none': return CursorMode.hidden; - default: return CursorMode.normal; - } - }, - - machSetCursorShape(canvas, shape) { - const cv = mach.canvases[canvas]; - switch (shape) { - case CursorShape.arrow: - cv.style.cursor = 'default'; - break; - case CursorShape.ibeam: - cv.style.cursor = 'text'; - break; - case CursorShape.crosshair: - cv.style.cursor = 'crosshair'; - break; - case CursorShape.pointing_hand: - cv.style.cursor = 'pointer'; - break; - case CursorShape.resize_ew: - cv.style.cursor = 'ew-resize'; - break; - case CursorShape.resize_ns: - cv.style.cursor = 'ns-resize'; - break; - case CursorShape.resize_nwse: - cv.style.cursor = 'nwse-resize'; - break; - case CursorShape.resize_nesw: - cv.style.cursor = 'nesw-resize'; - break; - case CursorShape.resize_all: - cv.style.cursor = 'move'; - break; - case CursorShape.not_allowed: - cv.style.cursor = 'not-allowed'; - break; - } - }, - - machCursorShape(canvas) { - switch (mach.canvases[canvas].style.cursor) { - case 'default': return CursorShape.arrow; - case 'text': return CursorShape.ibeam; - case 'crosshair': return CursorShape.crosshair; - case 'pointer': return CursorShape.pointing_hand; - case 'ew-resize': return CursorShape.resize_ew; - case 'ns-resize': return CursorShape.resize_ns; - case 'nwse-resize': return CursorShape.resize_nwse; - case 'nesw-resize': return CursorShape.resize_nesw; - case 'move': return CursorShape.resize_all; - case 'not-allowed': return CursorShape.not_allowed; - } - }, - - machSetWaitTimeout(timeout) { - mach.wait_timeout = timeout; - }, - - machHasEvent() { - return mach.events.length > 0; - }, - - machEventShift() { - if (mach.machHasEvent()) - return mach.events.shift(); - - return -1; - }, - - machEventShiftFloat() { - return mach.machEventShift(); - }, - - machPerfNow() { - return performance.now(); - }, -}; - -function convertKeyCode(code) { - const k = Key[code]; - if (k != undefined) - return k; - return 118; // Unknown -} - -const EventCode = { - key_press: 0, - key_repeat: 1, - key_release: 2, - char_input: 3, - mouse_motion: 4, - mouse_press: 5, - mouse_release: 6, - mouse_scroll: 7, - framebuffer_resize: 8, - focus_gained: 9, - focus_lost: 10, - close: 11, -}; - -const Key = { - KeyA: 0, - KeyB: 1, - KeyC: 2, - KeyD: 3, - KeyE: 4, - KeyF: 5, - KeyG: 6, - KeyH: 7, - KeyI: 8, - KeyJ: 9, - KeyK: 10, - KeyL: 11, - KeyM: 12, - KeyN: 13, - KeyO: 14, - KeyP: 15, - KeyQ: 16, - KeyR: 17, - KeyS: 18, - KeyT: 19, - KeyU: 20, - KeyV: 21, - KeyW: 22, - KeyX: 23, - KeyY: 24, - KeyZ: 25, - - Digit0: 26, - Digit1: 27, - Digit2: 28, - Digit3: 29, - Digit4: 30, - Digit5: 31, - Digit6: 32, - Digit7: 33, - Digit8: 34, - Digit9: 35, - - F1: 36, - F2: 37, - F3: 38, - F4: 39, - F5: 40, - F6: 41, - F7: 42, - F8: 43, - F9: 44, - F10: 45, - F11: 46, - F12: 47, - F13: 48, - F14: 49, - F15: 50, - F16: 51, - F17: 52, - F18: 53, - F19: 54, - F20: 55, - F21: 56, - F22: 57, - F23: 58, - F24: 59, - F25: 60, - - NumpadDivide: 61, - NumpadMultiply: 62, - NumpadSubtract: 63, - NumpadAdd: 64, - Numpad0: 65, - Numpad1: 66, - Numpad2: 67, - Numpad3: 68, - Numpad4: 69, - Numpad5: 70, - Numpad6: 71, - Numpad7: 72, - Numpad8: 73, - Numpad9: 74, - NumpadDecimal: 75, - NumpadEqual: 76, - NumpadEnter: 77, - - Enter: 78, - Escape: 79, - Tab: 80, - ShiftLeft: 81, - ShiftRight: 82, - ControlLeft: 83, - ControlRight: 84, - AltLeft: 85, - AltRight: 86, - OSLeft: 87, - MetaLeft: 87, - OSRight: 88, - MetaRight: 88, - ContextMenu: 89, - NumLock: 90, - CapsLock: 91, - PrintScreen: 92, - ScrollLock: 93, - Pause: 94, - Delete: 95, - Home: 96, - End: 97, - PageUp: 98, - PageDown: 99, - Insert: 100, - ArrowLeft: 101, - ArrowRight: 102, - ArrowUp: 103, - ArrowDown: 104, - Backspace: 105, - Space: 106, - Minus: 107, - Equal: 108, - BracketLeft: 109, - BracketRight: 110, - Backslash: 111, - Semicolon: 112, - Quote: 113, - Comma: 114, - Period: 115, - Slash: 116, - Backquote: 117, -}; - -const DisplayMode = { - windowed: 0, - fullscreen: 1, -}; - -const CursorMode = { - normal: 0, - hidden: 1, - disabled: 2, -}; - -const CursorShape = { - arrow: 0, - ibeam: 1, - crosshair: 2, - pointing_hand: 3, - resize_ew: 4, - resize_ns: 5, - resize_nwse: 6, - resize_nesw: 7, - resize_all: 8, - not_allowed: 9, -}; - -export { mach };