From c563119c7781338213098b912b840177d6fe1dfd Mon Sep 17 00:00:00 2001 From: Caznix Date: Sat, 11 Jan 2025 15:12:18 -0500 Subject: [PATCH 1/5] remove categories --- engine/src/core/repl/handler.rs | 37 --------------------------------- engine/src/core/repl/mod.rs | 11 +++------- engine/src/core/repl/zlua.rs | 3 +-- 3 files changed, 4 insertions(+), 47 deletions(-) diff --git a/engine/src/core/repl/handler.rs b/engine/src/core/repl/handler.rs index d3892f7..e285c6c 100644 --- a/engine/src/core/repl/handler.rs +++ b/engine/src/core/repl/handler.rs @@ -92,7 +92,6 @@ fn check_similarity(target: &str) -> Option { pub struct CommandManager { pub commands: HashMap>, pub aliases: HashMap, - pub categories: HashMap, } impl CommandManager { @@ -100,14 +99,9 @@ impl CommandManager { CommandManager { commands: HashMap::new(), aliases: HashMap::new(), - categories: HashMap::new(), } } - pub fn add_category(&mut self, category: Category) { - self.categories.insert(category.name.clone(), category); - } - pub fn get_commands(&self) -> std::collections::hash_map::Iter<'_, String, Box> { self.commands.iter() } @@ -146,16 +140,6 @@ impl CommandManager { .insert(command.get_name().to_lowercase(), command); } - pub fn add_command_with_category(&mut self, command: Box, category: Category) { - if self.categories.contains_key(&category.name) { - let mut cmd_name = command.get_name().to_lowercase(); - cmd_name.insert_str(0, &format!("{}_", &&category.uid.to_lowercase())); - println!("{}", cmd_name); - self.commands.insert(cmd_name, command); - } else { - panic!("Category {} does not exist", category.name); - } - } pub fn add_alias(&mut self, alias: &str, command: &str) { self.aliases.insert( @@ -164,28 +148,7 @@ impl CommandManager { ); } } -#[derive(Debug, Clone)] -pub struct Category { - // eg: Zenyx -> Z - // eg: core -> cr - // eg: exitcmd -> cr_exit - // eg: echo -> z_echo - pub uid: String, - // eg: Zenyx - pub name: String, - // eg: Zenyx internal commands - pub description: String, -} -impl Category { - pub fn new(uid: &str, name: &str, description: &str) -> Self { - Self { - uid: uid.to_string(), - name: name.to_string(), - description: description.to_string(), - } - } -} pub trait Command: Send + Sync { fn execute(&self, args: Option>) -> Result<(), anyhow::Error>; diff --git a/engine/src/core/repl/mod.rs b/engine/src/core/repl/mod.rs index d41fe90..e3f1119 100644 --- a/engine/src/core/repl/mod.rs +++ b/engine/src/core/repl/mod.rs @@ -1,8 +1,6 @@ use commands::{ - ClearCommand, CounterCommand, ExecFile, ExitCommand, HelpCommand, PanicCommmand + ClearCommand, CounterCommand, ExitCommand, HelpCommand, PanicCommmand,ExecFile }; -use handler::{COMMAND_MANAGER, Category}; -use zlua::ZLua; use crate::commands; @@ -14,15 +12,12 @@ pub mod zlua; pub fn setup() { commands!( HelpCommand, + ExecFile, + ClearCommand, ExitCommand, CounterCommand, PanicCommmand, zlua::ZLua ); - let cat = Category::new("cr", "Core", "Core commands"); - COMMAND_MANAGER.write().add_category(cat.clone()); - COMMAND_MANAGER - .write() - .add_command_with_category(Box::new(ExecFile), cat.clone()); } diff --git a/engine/src/core/repl/zlua.rs b/engine/src/core/repl/zlua.rs index 90203c5..9936db0 100644 --- a/engine/src/core/repl/zlua.rs +++ b/engine/src/core/repl/zlua.rs @@ -84,8 +84,7 @@ impl Command for ZLua { .. }) => { // continue reading input and append it to `line` - line.push_str("\n"); // separate input lines - prompt = prompt; + line.push('\n'); // separate input lines } Err(e) => { From 487897cdb91d1dad5e14b8e68145d9d94f56d312 Mon Sep 17 00:00:00 2001 From: Caznix Date: Sat, 11 Jan 2025 15:28:01 -0500 Subject: [PATCH 2/5] finally fix workflow i hope --- .github/workflows/rust.yml | 182 +++++++++++++++---------------- engine/Cargo.toml | 3 +- engine/src/core/repl/commands.rs | 5 +- engine/src/core/repl/handler.rs | 2 - engine/src/core/repl/mod.rs | 5 +- engine/src/core/repl/zlua.rs | 27 +++-- engine/src/core/splash.rs | 7 +- subcrates/zen_core/src/lib.rs | 8 +- 8 files changed, 113 insertions(+), 126 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 3febcbc..20ebcf4 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,115 +1,111 @@ name: Build Zenyx โšก - on: push: - branches: [ "main", "master" ] - pull_request: - branches: [ "main", "master" ] - + tags: ["v*"] env: CARGO_TERM_COLOR: always - jobs: - # Credit to https://github.com/Far-Beyond-Dev/Horizon/blob/main/.github/workflows/main.yml - check-version: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 2 - - name: Get binary name - id: binary - run: | - BINARY_NAME=$(cargo metadata --format-version 1 | jq -r '.packages[0].targets[] | select(.kind[] | contains("bin")) | .name') - echo "name=$BINARY_NAME" >> "$GITHUB_OUTPUT" - - name: Check version change - id: version - run: | - git fetch - OLD_VERSION=$(git show HEAD^:Cargo.toml | grep -m 1 '^version = ' | cut -d '"' -f 2) - NEW_VERSION=$(grep -m 1 '^version = ' Cargo.toml | cut -d '"' -f 2) - if [ "$OLD_VERSION" != "$NEW_VERSION" ]; then - echo "changed=true" >> "$GITHUB_OUTPUT" - echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT" - fi - - name: Create Release - if: steps.version.outputs.changed == 'true' - uses: softprops/action-gh-release@v1 - with: - tag_name: v${{ steps.version.outputs.version }} - name: Release v${{ steps.version.outputs.version }} - files: target/release/${{ steps.binary.outputs.name }} - generate_release_notes: true - draft: false - prerelease: false build: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest, macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] arch: [x86_64, aarch64] include: - arch: x86_64 target: x86_64-unknown-linux-gnu - - os: macos-latest - arch: x86_64 - target: x86_64-apple-darwin + binary_name: zenyx-linux-x86_64.zip + file_extension: "" - arch: aarch64 target: aarch64-unknown-linux-gnu - - os: macos-latest - arch: aarch64 - target: aarch64-apple-darwin + binary_name: zenyx-linux-aarch64.zip + file_extension: "" - os: windows-latest arch: x86_64 target: x86_64-pc-windows-msvc - - os: windows-latest + binary_name: zenyx-windows-x86_64.zip + file_extension: ".exe" + - os: macos-latest + arch: x86_64 + target: x86_64-apple-darwin + binary_name: zenyx-macos-x86_64.zip + file_extension: "" + - os: macos-latest arch: aarch64 - target: aarch64-pc-windows-msvc + target: aarch64-apple-darwin + binary_name: zenyx-macos-aarch64.zip + file_extension: "" runs-on: ${{ matrix.os }} - steps: - - name: ๐Ÿ“ฅ Clone repository - uses: actions/checkout@v3 - - - name: ๐Ÿ› ๏ธ Install cross-compilation dependencies (Ubuntu) - if: runner.os == 'Linux' - run: | - sudo apt-get update - sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu qemu-user - - - name: ๐Ÿ› ๏ธ Install cross-compilation dependencies (macOS๐ŸŽ) - if: runner.os == 'macOS' - run: | - brew install FiloSottile/musl-cross/musl-cross - - - name: ๐Ÿ”ง Install Rust - uses: actions-rs/toolchain@v1 - with: - toolchain: nightly - override: true - target: ${{ matrix.target }} - profile: minimal - - - name: ๐Ÿ—๏ธ Build - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --target ${{ matrix.target }} - env: - CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc - - - name: ๐Ÿงช Run tests - if: matrix.target != 'aarch64-pc-windows-msvc' - uses: actions-rs/cargo@v1 - with: - command: test - args: --target ${{ matrix.target }} - env: - CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc - QEMU_LD_PREFIX: /usr/aarch64-linux-gnu - - - name: ๐Ÿ“ฆ Upload artifacts - uses: actions/upload-artifact@v3 - with: - name: Zenyx-${{ runner.os }}-${{ matrix.arch }}-bin - path: target/${{ matrix.target }}/release/zenyx* \ No newline at end of file + - name: ๐Ÿ“ฅ Clone repository + uses: actions/checkout@v4 + - name: ๐Ÿ› ๏ธ Install cross-compilation dependencies (Ubuntu AMD) + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu qemu-user + - name: ๐Ÿ› ๏ธ Install cross-compilation dependencies (macOS๐ŸŽ) + if: runner.os == 'macOS' + run: | + brew install FiloSottile/musl-cross/musl-cross + - name: ๐Ÿ”ง Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + target: ${{ matrix.target }} + profile: minimal + - name: ๐Ÿ—๏ธ Build + uses: actions-rs/cargo@v1 + with: + command: build + args: --release --target ${{ matrix.target }} + env: + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc + - name: ๐Ÿ“ฆ Prepare binary and checksum + run: | + # Create temp directory for zip contents + mkdir -p temp_release + # Copy binary to temp directory + cp target/${{ matrix.target }}/release/zenyx${{ matrix.file_extension }} temp_release/zenyx${{ matrix.file_extension }} + chmod +x temp_release/zenyx${{ matrix.file_extension }} + # Create SHA256 checksum + cd temp_release + if [[ "${{ runner.os }}" == "Windows" ]]; then + certutil -hashfile zenyx${{ matrix.file_extension }} SHA256 > zenyx.sha256 + # Remove certutil's extra output, keeping only the hash + sed -i '1d' zenyx.sha256 + sed -i '2d' zenyx.sha256 + else + shasum -a 256 zenyx${{ matrix.file_extension }} > zenyx.sha256 + fi + # Create zip with both files at root level + mkdir -p ../release + zip ../release/${{ matrix.binary_name }} zenyx${{ matrix.file_extension }} zenyx.sha256 + cd .. + rm -rf temp_release + - name: Upload artifacts + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.binary_name }} + path: release/${{ matrix.binary_name }} + release: + runs-on: ubuntu-latest + needs: build + steps: + - uses: actions/checkout@v4 + - name: Download artifacts + uses: actions/download-artifact@v4 + with: + path: release + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + files: release/*/*.zip + name: Release ${{ github.ref_name }} + body: | + This is the release for version ${{ github.ref_name }}. + draft: false + prerelease: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/engine/Cargo.toml b/engine/Cargo.toml index c370b3c..446f7c0 100644 --- a/engine/Cargo.toml +++ b/engine/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "engine" +name = "zenyx" version = "0.1.0" edition = "2024" repository = "https://github.com/Zenyx-Engine/Zenyx" @@ -8,7 +8,6 @@ anyhow = "1.0.94" backtrace = "0.3.74" chrono = "0.4.39" colored = "2.2.0" -crashreport = "1.0.1" dirs-next = "2.0.0" lazy_static.workspace = true diff --git a/engine/src/core/repl/commands.rs b/engine/src/core/repl/commands.rs index 55b6447..861785d 100644 --- a/engine/src/core/repl/commands.rs +++ b/engine/src/core/repl/commands.rs @@ -1,11 +1,12 @@ use std::{fs, path::PathBuf, str::FromStr}; + +use anyhow::anyhow; use colored::Colorize; use mlua::prelude::*; -use anyhow::anyhow; use mlua::{Lua, MultiValue}; use parking_lot::RwLock; use regex::Regex; -use rustyline::{error::ReadlineError, DefaultEditor}; +use rustyline::{DefaultEditor, error::ReadlineError}; use super::{handler::Command, input::tokenize}; use crate::core::repl::handler::COMMAND_MANAGER; diff --git a/engine/src/core/repl/handler.rs b/engine/src/core/repl/handler.rs index e285c6c..3a02f5c 100644 --- a/engine/src/core/repl/handler.rs +++ b/engine/src/core/repl/handler.rs @@ -140,7 +140,6 @@ impl CommandManager { .insert(command.get_name().to_lowercase(), command); } - pub fn add_alias(&mut self, alias: &str, command: &str) { self.aliases.insert( alias.to_string().to_lowercase(), @@ -149,7 +148,6 @@ impl CommandManager { } } - pub trait Command: Send + Sync { fn execute(&self, args: Option>) -> Result<(), anyhow::Error>; fn undo(&self); diff --git a/engine/src/core/repl/mod.rs b/engine/src/core/repl/mod.rs index e3f1119..3e029fa 100644 --- a/engine/src/core/repl/mod.rs +++ b/engine/src/core/repl/mod.rs @@ -1,6 +1,4 @@ -use commands::{ - ClearCommand, CounterCommand, ExitCommand, HelpCommand, PanicCommmand,ExecFile -}; +use commands::{ClearCommand, CounterCommand, ExecFile, ExitCommand, HelpCommand, PanicCommmand}; use crate::commands; @@ -13,7 +11,6 @@ pub fn setup() { commands!( HelpCommand, ExecFile, - ClearCommand, ExitCommand, CounterCommand, diff --git a/engine/src/core/repl/zlua.rs b/engine/src/core/repl/zlua.rs index 9936db0..e895d85 100644 --- a/engine/src/core/repl/zlua.rs +++ b/engine/src/core/repl/zlua.rs @@ -1,5 +1,6 @@ -use mlua::{Function, Lua, LuaOptions, MultiValue, Number, Value::Nil}; -use rustyline::{error::ReadlineError, DefaultEditor}; +use mlua::{Lua, LuaOptions, MultiValue}; +use rustyline::{DefaultEditor, error::ReadlineError}; + use crate::core::repl::handler::Command; #[derive(Default)] @@ -9,13 +10,10 @@ impl Command for ZLua { fn execute(&self, _args: Option>) -> Result<(), anyhow::Error> { let time = chrono::Local::now().format("%H:%M:%S.%3f").to_string(); let prompt = format!("[{}/{}] {}", time, "ZLUA", ">>\t"); - let lua = Lua::new_with( - mlua::StdLib::ALL_SAFE, - LuaOptions::default() - )?; + let lua = Lua::new_with(mlua::StdLib::ALL_SAFE, LuaOptions::default())?; let globals = lua.globals(); //This just adds 2 numbers together - let add = lua.create_function(|_, (number1,number2):(i32,i32)|{ + let add = lua.create_function(|_, (number1, number2): (i32, i32)| { let result = number1 + number2; println!("{result}"); Ok(()) @@ -24,23 +22,25 @@ impl Command for ZLua { let is_equal = lua.create_function(|_, (list1, list2): (i32, i32)| { if list1 == 0 || list2 == 0 { - return Err(mlua::Error::RuntimeError("Zero values not allowed".to_string())); + return Err(mlua::Error::RuntimeError( + "Zero values not allowed".to_string(), + )); } Ok(list1 == list2) })?; globals.set("isEqual", is_equal)?; let log = lua.create_function(|_, (msg,): (String,)| { - println!("{}", msg); - Ok(()) + println!("{}", msg); + Ok(()) })?; globals.set("log", log)?; - let fail_safe = lua.create_function(|_,()|{ + let fail_safe = lua.create_function(|_, ()| { println!("Failed"); Ok(()) })?; - globals.set("failSafe",fail_safe)?; + globals.set("failSafe", fail_safe)?; let mut editor = DefaultEditor::new().expect("Failed to create editor"); loop { @@ -65,7 +65,7 @@ impl Command for ZLua { mlua::Value::Number(n) => println!("Got number: {}", n), mlua::Value::String(s) => println!("Got string: {}", s.to_str()?), mlua::Value::Boolean(b) => println!("Got boolean: {}", b), - _ => eprintln!("Got unexpected type: {:#?}", value) + _ => eprintln!("Got unexpected type: {:#?}", value), } } editor.add_history_entry(line).unwrap(); @@ -92,7 +92,6 @@ impl Command for ZLua { eprintln!("Input that caused error: {}", line); break; } - } } } diff --git a/engine/src/core/splash.rs b/engine/src/core/splash.rs index d882c87..1a920b3 100644 --- a/engine/src/core/splash.rs +++ b/engine/src/core/splash.rs @@ -1,10 +1,11 @@ use colored::Colorize; pub fn print_splash() { - println! -("# # + println!( + "# # # Welcome to the Zenyx terminal # -# #"); +# #" + ); println!( "{}", format!( diff --git a/subcrates/zen_core/src/lib.rs b/subcrates/zen_core/src/lib.rs index 1293081..1f26fe7 100644 --- a/subcrates/zen_core/src/lib.rs +++ b/subcrates/zen_core/src/lib.rs @@ -1,11 +1,7 @@ - - use thiserror::Error; -#[derive(Debug,Error)] +#[derive(Debug, Error)] enum ZError { #[error(transparent)] - Unknown(#[from] anyhow::Error) - + Unknown(#[from] anyhow::Error), } - From 5ae67d01627f7fbd5988a337589f1b10f3406900 Mon Sep 17 00:00:00 2001 From: Caznix Date: Sat, 11 Jan 2025 15:30:35 -0500 Subject: [PATCH 3/5] update workflow to use nightly --- .github/workflows/rust.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 20ebcf4..07a8cd3 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -51,7 +51,7 @@ jobs: - name: ๐Ÿ”ง Install Rust uses: actions-rs/toolchain@v1 with: - toolchain: stable + toolchain: nightly override: true target: ${{ matrix.target }} profile: minimal From 593b9ef119b259af7a07f1d518490ea6c9e3a074 Mon Sep 17 00:00:00 2001 From: Caznix Date: Thu, 23 Jan 2025 17:56:46 -0500 Subject: [PATCH 4/5] remove welcome message to save terminal space --- .github/workflows/rust.yml | 3 ++- engine/src/core/splash.rs | 5 ----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 07a8cd3..ab00ef5 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -63,6 +63,7 @@ jobs: env: CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc - name: ๐Ÿ“ฆ Prepare binary and checksum + shell: bash run: | # Create temp directory for zip contents mkdir -p temp_release @@ -71,7 +72,7 @@ jobs: chmod +x temp_release/zenyx${{ matrix.file_extension }} # Create SHA256 checksum cd temp_release - if [[ "${{ runner.os }}" == "Windows" ]]; then + if [ "$RUNNER_OS" == "Windows" ]; then certutil -hashfile zenyx${{ matrix.file_extension }} SHA256 > zenyx.sha256 # Remove certutil's extra output, keeping only the hash sed -i '1d' zenyx.sha256 diff --git a/engine/src/core/splash.rs b/engine/src/core/splash.rs index 1a920b3..94f4b5b 100644 --- a/engine/src/core/splash.rs +++ b/engine/src/core/splash.rs @@ -1,11 +1,6 @@ use colored::Colorize; pub fn print_splash() { - println!( - "# # -# Welcome to the Zenyx terminal # -# #" - ); println!( "{}", format!( From 32a5c46f8c5eb2e750c0b5c200d0b454832b64d4 Mon Sep 17 00:00:00 2001 From: Caznix Date: Tue, 4 Feb 2025 05:10:53 -0500 Subject: [PATCH 5/5] cube --- engine/Cargo.toml | 7 +- engine/src/core/ecs/mod.rs | 18 +- engine/src/core/mod.rs | 2 + engine/src/core/render/ctx.rs | 316 +++++++++++++++++++++++++++++ engine/src/core/render/mod.rs | 72 +++++++ engine/src/core/repl/Re-exports.rs | 9 - engine/src/main.rs | 22 +- 7 files changed, 430 insertions(+), 16 deletions(-) create mode 100644 engine/src/core/render/ctx.rs create mode 100644 engine/src/core/render/mod.rs delete mode 100644 engine/src/core/repl/Re-exports.rs diff --git a/engine/Cargo.toml b/engine/Cargo.toml index 446f7c0..ce5fc4a 100644 --- a/engine/Cargo.toml +++ b/engine/Cargo.toml @@ -17,7 +17,12 @@ once_cell = "1.20.2" parking_lot.workspace = true regex = "1.11.1" rustyline = { version = "15.0.0", features = ["derive", "rustyline-derive"] } -tokio = { version = "1.42.0", features = ["macros", "parking_lot", "rt", "rt-multi-thread"] } +thiserror = "2.0.11" +tokio = { version = "1.42.0", features = ["macros", "parking_lot","rt-multi-thread"] } +wgpu = "24.0.1" +winit = "0.30.8" +bytemuck = "1.21.0" +futures = "0.3.31" [profile.dev] diff --git a/engine/src/core/ecs/mod.rs b/engine/src/core/ecs/mod.rs index f810534..e2701ac 100644 --- a/engine/src/core/ecs/mod.rs +++ b/engine/src/core/ecs/mod.rs @@ -1,3 +1,15 @@ -// struct ComponentRegistry { -// components -// } + + +pub trait Component: Sized + 'static { + fn update(&mut self, delta_time: f32); + fn serialize(&self) -> Vec; + fn deserialize(data: &[u8;6]) -> Self; +} + +pub trait Entity: Sized { + fn add_component(&mut self, component: C); + fn remove_component(&mut self); + fn get_component(&self) -> Option<&C>; + fn serialize(&self) -> Vec; + fn deserialize(data: &[u8;6]) -> Self; +} \ No newline at end of file diff --git a/engine/src/core/mod.rs b/engine/src/core/mod.rs index 7d8a407..e2fe202 100644 --- a/engine/src/core/mod.rs +++ b/engine/src/core/mod.rs @@ -4,3 +4,5 @@ pub mod panic; pub mod repl; pub mod splash; pub mod workspace; + +pub mod render; \ No newline at end of file diff --git a/engine/src/core/render/ctx.rs b/engine/src/core/render/ctx.rs new file mode 100644 index 0000000..de8f8df --- /dev/null +++ b/engine/src/core/render/ctx.rs @@ -0,0 +1,316 @@ +๏ปฟ +use std::borrow::Cow; +use std::sync::Arc; +use std::time::Instant; +use thiserror::Error; +use winit::window::Window; +use futures::executor::block_on; +#[derive(Debug, Error)] +pub enum ContextError { + #[error("Failed to create WGPU surface: {0}")] + SurfaceCreationFailure(#[from] wgpu::CreateSurfaceError), +} + +/// This WGSL shader generates a cube procedurally and rotates it around the Y axis. +/// A uniform (u.time) is used as the rotation angle. After rotation, a simple +/// perspective projection is applied (dividing x,y by z) to produce clip-space coordinates. +const CUBE_SHADER: &str = r#" +struct Uniforms { + time: f32, + // pad to 16 bytes (uniforms require 16-byte alignment) + padding0: f32, + padding1: f32, + padding2: f32, +}; + +@group(0) @binding(0) +var u: Uniforms; + +// Returns a rotation matrix about the Y axis. +fn rotationY(angle: f32) -> mat3x3 { + let c = cos(angle); + let s = sin(angle); + return mat3x3( + vec3( c, 0.0, s), + vec3(0.0, 1.0, 0.0), + vec3(-s, 0.0, c) + ); +} + +@vertex +fn vs_main(@builtin(vertex_index) vid: u32) -> @builtin(position) vec4 { + // We generate 36 vertices (6 faces * 6 vertices per face) + let face: u32 = vid / 6u; // which face (0..5) + let corner: u32 = vid % 6u; // which corner within that face + + // Offsets for the two triangles that make up a face: + // (these are in a 2D space, later used to compute positions on the face) + var offsets = array, 6>( + vec2(-1.0, -1.0), + vec2( 1.0, -1.0), + vec2( 1.0, 1.0), + vec2( 1.0, 1.0), + vec2(-1.0, 1.0), + vec2(-1.0, -1.0) + ); + + var center: vec3; + var uvec: vec3; + var vvec: vec3; + + // Define each face of the cube (cube of side length 1 centered at origin) + if (face == 0u) { + // Front face (z = +0.5) + center = vec3(0.0, 0.0, 0.5); + uvec = vec3(0.5, 0.0, 0.0); + vvec = vec3(0.0, 0.5, 0.0); + } else if (face == 1u) { + // Back face (z = -0.5) + center = vec3(0.0, 0.0, -0.5); + uvec = vec3(-0.5, 0.0, 0.0); + vvec = vec3(0.0, 0.5, 0.0); + } else if (face == 2u) { + // Right face (x = +0.5) + center = vec3(0.5, 0.0, 0.0); + uvec = vec3(0.0, 0.0, -0.5); + vvec = vec3(0.0, 0.5, 0.0); + } else if (face == 3u) { + // Left face (x = -0.5) + center = vec3(-0.5, 0.0, 0.0); + uvec = vec3(0.0, 0.0, 0.5); + vvec = vec3(0.0, 0.5, 0.0); + } else if (face == 4u) { + // Top face (y = +0.5) + center = vec3(0.0, 0.5, 0.0); + uvec = vec3(0.5, 0.0, 0.0); + vvec = vec3(0.0, 0.0, -0.5); + } else { + // Bottom face (y = -0.5) + center = vec3(0.0, -0.5, 0.0); + uvec = vec3(0.5, 0.0, 0.0); + vvec = vec3(0.0, 0.0, 0.5); + } + + let off = offsets[corner]; + var pos = center + off.x * uvec + off.y * vvec; + + // Apply a rotation about the Y axis using the uniform time. + let rot = rotationY(u.time); + pos = rot * pos; + + // Translate the cube so it is in front of the camera. + pos = pos + vec3(0.0, 0.0, 2.0); + + // Simple perspective projection: divide x and y by z. + let projected = vec2(pos.x / pos.z, pos.y / pos.z); + return vec4(projected, 0.0, 1.0); +} + +@fragment +fn fs_main() -> @location(0) vec4 { + // Output a fixed color. + return vec4(0.7, 0.7, 0.9, 1.0); +} +"#; + +pub struct WgpuCtx<'window> { + device: wgpu::Device, + queue: wgpu::Queue, + surface: wgpu::Surface<'window>, + surface_config: wgpu::SurfaceConfiguration, + adapter: wgpu::Adapter, + render_pipeline: wgpu::RenderPipeline, + uniform_buffer: wgpu::Buffer, + start_time: Instant, +} + +impl<'window> WgpuCtx<'window> { + pub async fn new(window: Arc) -> Result, ContextError> { + let instance = wgpu::Instance::default(); + let surface = instance.create_surface(Arc::clone(&window))?; + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + force_fallback_adapter: false, + compatible_surface: Some(&surface), + }) + .await + .expect("Failed to obtain render adapter"); + let (device, queue) = adapter + .request_device( + &wgpu::DeviceDescriptor { + label: None, + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::downlevel_webgl2_defaults() + .using_resolution(adapter.limits()), + memory_hints: wgpu::MemoryHints::Performance, + }, + None, + ) + .await + .expect("Failed to create rendering device"); + + let size = window.inner_size(); + let width = size.width.max(1); + let height = size.height.max(1); + let surface_config = surface.get_default_config(&adapter, width, height).unwrap(); + surface.configure(&device, &surface_config); + + // Create a uniform buffer (16 bytes to satisfy alignment requirements) + let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Uniform Buffer"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + // Create the shader module from the inline WGSL shader. + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Cube Shader"), + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(CUBE_SHADER)), + }); + + // Create a bind group layout for the uniform. + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Uniform Bind Group Layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(16), + }, + count: None, + }], + }); + + // Create the pipeline layout. + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Cube Pipeline Layout"), + bind_group_layouts: &[&bind_group_layout], + push_constant_ranges: &[], + }); + + // TODO: add proper vertex buffer + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Cube Render Pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format: surface_config.format, + blend: Some(wgpu::BlendState::REPLACE), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: None, + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: None, + multisample: wgpu::MultisampleState { + count: 1, + mask: !0, + alpha_to_coverage_enabled: false, + }, + multiview: None, + cache: None, + }); + + Ok(WgpuCtx { + device, + queue, + surface, + surface_config, + adapter, + render_pipeline, + uniform_buffer, + start_time: Instant::now(), + }) + } + + pub fn new_blocking(window: Arc) -> Result, ContextError> { + block_on(Self::new(window)) + } + + pub fn resize(&mut self, new_size: (u32, u32)) { + let (width, height) = new_size; + self.surface_config.width = width.max(1); + self.surface_config.height = height.max(1); + self.surface.configure(&self.device, &self.surface_config); + } + + pub fn draw(&mut self) { + // Update the uniform buffer with the elapsed time. + let elapsed = self.start_time.elapsed().as_secs_f32(); + // Pack into 4 floats (pad to 16 bytes) + let time_data = [elapsed, 0.0, 0.0, 0.0]; + self.queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&time_data)); + + let surface_texture = self + .surface + .get_current_texture() + .expect("Failed to get surface texture"); + let view = surface_texture + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + + let mut encoder = + self.device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Cube Command Encoder"), + }); + + { + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Cube Render Pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.1, + g: 0.2, + b: 0.3, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + }); + render_pass.set_pipeline(&self.render_pipeline); + // Create a bind group on the fly for the uniform. + let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Uniform Bind Group (per draw)"), + layout: &self.render_pipeline.get_bind_group_layout(0), + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: self.uniform_buffer.as_entire_binding(), + }], + }); + render_pass.set_bind_group(0, &bind_group, &[]); + // Draw 36 vertices (6 faces ร— 6 vertices) + render_pass.draw(0..36, 0..1); + } + + self.queue.submit(Some(encoder.finish())); + surface_texture.present(); + } +} diff --git a/engine/src/core/render/mod.rs b/engine/src/core/render/mod.rs new file mode 100644 index 0000000..223fb88 --- /dev/null +++ b/engine/src/core/render/mod.rs @@ -0,0 +1,72 @@ +๏ปฟuse std::sync::Arc; + +use ctx::WgpuCtx; +use winit::application::ApplicationHandler; +use winit::event::WindowEvent; +use log::{debug,trace}; +use winit::event_loop::{ActiveEventLoop, EventLoop}; +use winit::event_loop::ControlFlow; + +use winit::window::{Window, WindowId}; +pub mod ctx; + + +#[derive(Default)] +pub struct App<'window> { + window: Option>, + ctx: Option>, +} + + +impl ApplicationHandler for App<'_> { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_none() { + let win_attr = Window::default_attributes().with_title("Zenyx"); + let window = Arc::new(event_loop + .create_window(win_attr) + .expect("create window err.")); + self.window = Some(window.clone()); + let wgpu_ctx = WgpuCtx::new_blocking(window.clone()).unwrap(); + self.ctx = Some(wgpu_ctx) + } + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + match event { + WindowEvent::CloseRequested => { + event_loop.exit(); + debug!("Window closed, exiting"); + std::process::exit(0) + } + WindowEvent::RedrawRequested => { + if let Some(ctx) = &mut self.ctx { + ctx.draw(); + } + if let Some(window) = &self.window { + window.request_redraw(); + } + } + WindowEvent::Resized(size) => { + if let (Some(wgpu_ctx),Some(window)) = (&mut self.ctx, &self.window) { + wgpu_ctx.resize(size.into()); + window.request_redraw(); + let size_str: String = size.height.to_string() + "x" + &size.width.to_string(); + //self.window.as_ref().unwrap().set_title(&format!("you reszed the window to {size_str}")); + debug!("Window resized to {:?}", size_str); + } + } + _ => trace!("Unhandled window event"), + } + } +} + +pub fn init_renderer(event_loop: EventLoop<()>) { + event_loop.set_control_flow(ControlFlow::Poll); + let mut app = App::default(); + event_loop.run_app(&mut app).unwrap(); +} \ No newline at end of file diff --git a/engine/src/core/repl/Re-exports.rs b/engine/src/core/repl/Re-exports.rs deleted file mode 100644 index 8d7f394..0000000 --- a/engine/src/core/repl/Re-exports.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub use renderer::*; -pub use window::*; -pub use crate::core::*; -pub use material::*; -pub use effect::*; -pub use light::*; -pub use geometry::*; -pub use object::*; -pub use control::*; \ No newline at end of file diff --git a/engine/src/main.rs b/engine/src/main.rs index 80dbecd..bdf5873 100644 --- a/engine/src/main.rs +++ b/engine/src/main.rs @@ -6,8 +6,11 @@ use core::{ }; use colored::Colorize; +use log::info; use mlua::Lua; +use parking_lot::Mutex; use tokio::runtime; +use winit::event_loop::EventLoop; pub mod core; @@ -23,9 +26,22 @@ fn main() -> anyhow::Result<()> { runtime.block_on(async { setup(); splash::print_splash(); - COMMAND_MANAGER.read().execute("help", None)?; - let t = tokio::spawn(core::repl::input::handle_repl()); - t.await??; + info!("Type 'help' for a list of commands."); + + let repl_handle = tokio::spawn(core::repl::input::handle_repl()); + let event_loop = EventLoop::new().unwrap(); + + core::render::init_renderer(event_loop); + + + // Await the REPL + if let Err(e) = repl_handle.await { + eprintln!("REPL error: {:?}", e); + } + + // Wait for the renderer to finish (if needed) + + Ok::<(), anyhow::Error>(()) })?;