Skip to content

Preparing Alpha Branch #4147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/kbve/kbve.com/src/content/docs/application/rust.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,15 @@ This crate is a user-friendly, easy-to-integrate, immediate-mode GUI library des

---

## Q

Q is a powerful Godot Helper Crate designed for Rust developers using the GDExtension API.
It provides a robust set of tools to streamline game development, including a versatile Game Manager for handling core game logic, a Music Manager for seamless audio integration, and a Bevy ECS implementation for efficient entity-component-system architecture.
Additionally, Q leverages Tokio for high-performance multi-threading, enabling smooth and scalable concurrency in your Godot projects.
Whether you're building complex systems or optimizing performance, Q is your go-to crate for enhancing Rust-based Godot development.

---

## KBVE

---
Expand Down
10 changes: 7 additions & 3 deletions packages/rust/q/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
[package]
name = "q"
authors = ["kbve", "h0lybyte"]
version = "0.1.0"
version = "0.1.1"
edition = "2021"
license = "MIT"
description = "Q is a Godot Helper Crate."
homepage = "https://kbve.com/"
description = "Q is a Rust GDExtension crate for Godot, offering a Game Manager, Music Manager, Bevy ECS, and Tokio-powered multi-threading. It simplifies and enhances game development with efficient tools and scalable performance."
homepage = "https://kbve.com/application/rust/"
repository = "https://github.com/KBVE/kbve/tree/main/packages/erust"
readme = "README.md"
rust-version = "1.75"
exclude = [
"release/*",
"docs/*",
]

[lib]
crate-type = ["cdylib"]
Expand Down
13 changes: 13 additions & 0 deletions packages/rust/q/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@
"options": {
"target-dir": "dist/target/q"
}
},

"build-mac": {
"executor": "nx:run-commands",
"options": {
"cwd": "packages/rust/q",
"commands": [
"cargo +nightly build -Z build-std=std,panic_abort -Z unstable-options --target aarch64-apple-darwin --artifact-dir dist/macos --release",
"mkdir -p release/addons/q/macos",
"cp dist/macos/*.dylib release/addons/q/macos/"
],
"parallel": false
}
}
},
"tags": []
Expand Down
110 changes: 110 additions & 0 deletions packages/rust/q/src/data/abstract_data_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use godot::prelude::*;
use godot::classes::file_access::ModeFlags;
use godot::tools::GFile;
use papaya::HashMap;
use serde::{ Serialize, Deserialize };
use serde_json::Value;

pub trait AbstractDataMap: Serialize + for<'de> Deserialize<'de> + Sized {
fn to_variant_map(&self) -> HashMap<String, Variant> {
let map = HashMap::new();
{
let pinned_map = map.pin();
if
let Value::Object(obj) = serde_json
::to_value(self)
.unwrap_or_else(|_| Value::Object(Default::default()))
{
for (key, value) in obj {
let variant = match value {
Value::String(s) => Variant::from(s),
Value::Number(n) => {
if let Some(f) = n.as_f64() {
Variant::from(f as f32)
} else {
Variant::from(n.as_i64().unwrap_or(0))
}
}
Value::Bool(b) => Variant::from(b),
_ => Variant::from(""),
};
pinned_map.insert(key, variant);
}
}
}

map
}

fn from_variant_map(map: &HashMap<String, Variant>) -> Option<Self> {
let mut json_map = serde_json::Map::new();
{
let pinned_map = map.pin();
for (key, value) in pinned_map.iter() {
let json_value = if let Ok(s) = value.try_to::<String>() {
Value::String(s)
} else if let Ok(f) = value.try_to::<f32>() {
Value::Number(serde_json::Number::from_f64(f as f64).unwrap())
} else if let Ok(i) = value.try_to::<i64>() {
Value::Number(serde_json::Number::from(i))
} else if let Ok(b) = value.try_to::<bool>() {
Value::Bool(b)
} else if value.is_nil() {
Value::Null
} else {
Value::Null
};
json_map.insert(key.clone(), json_value);
}
}

serde_json::from_value(Value::Object(json_map)).ok()
}

fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
}

fn from_json(json: &str) -> Option<Self> {
serde_json::from_str(json).ok()
}

fn to_save_gfile_json(&self, file_path: &str) -> bool {
let json_string = self.to_json();
if let Ok(mut file) = GFile::open(file_path, ModeFlags::WRITE) {
let _ = file.write_gstring_line(&GString::from(json_string));
true
} else {
godot_error!("Failed to save data to file: {}", file_path);
false
}
}

fn from_load_gfile_json(file_path: &str) -> Option<Self> {
godot_print!("[AbstractDataMap] Attempting to open file: {}", file_path);

let file = GFile::open(file_path, ModeFlags::READ);

match file {
Ok(mut file) => {
godot_print!("[AbstractDataMap] File opened successfully.");

if let Ok(json_string) = file.read_gstring_line() {
godot_print!("[AbstractDataMap] Successfully read JSON file.");
return Self::from_json(&json_string.to_string());
} else {
godot_error!("[AbstractDataMap] ERROR: Failed to read JSON string.");
}
}
Err(e) => {
if e.to_string().contains("ERR_FILE_NOT_FOUND") {
godot_warn!("[AbstractDataMap] File not found, returning None.");
} else {
godot_error!("[AbstractDataMap] ERROR: Failed to open file {}: {:?}", file_path, e);
}
}
}

None
}
}
139 changes: 139 additions & 0 deletions packages/rust/q/src/data/cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
use godot::prelude::*;
use papaya::HashMap;
use godot::classes::{ Texture2D, CanvasLayer, Control, AudioStream };
use std::sync::Arc;
use std::marker::PhantomData;
use crate::data::shader_data::ShaderCache;

pub struct ResourceCache<T: GodotClass> {
map: HashMap<String, Gd<T>>,
_marker: PhantomData<T>,
}

impl<T: GodotClass> ResourceCache<T> {
pub fn new() -> Self {
Self {
map: HashMap::new(),
_marker: PhantomData,
}
}

pub fn insert(&self, key: &str, object: Gd<T>) {
self.map.pin().insert(key.to_string(), object);
}

pub fn get(&self, key: &str) -> Option<Gd<T>> {
self.map.pin().get(&key.to_string()).cloned()
}

pub fn get_arc(&self, key: &str) -> Option<Arc<Gd<T>>> {
self.map
.pin()
.get(&key.to_string())
.map(|gd| Arc::new(gd.clone()))
}

pub fn contains(&self, key: &str) -> bool {
self.map.pin().contains_key(&key.to_string())
}

pub fn insert_upcast<U>(&self, key: &str, object: Gd<U>) where U: Inherits<T> + GodotClass {
self.insert(key, object.upcast::<T>());
}

pub fn get_as<U>(&self, key: &str) -> Option<Gd<U>> where U: Inherits<T> + GodotClass {
self.get(key)?.try_cast::<U>().ok()
}

pub fn remove(&self, key: &str) -> Option<Gd<T>> {
self.map.pin().remove(&key.to_string()).cloned()
}
}

#[derive(GodotClass)]
#[class(base = Node)]
pub struct CacheManager {
base: Base<Node>,
texture_cache: ResourceCache<Texture2D>,
canvas_layer_cache: ResourceCache<CanvasLayer>,
ui_cache: ResourceCache<Control>,
audio_cache: ResourceCache<AudioStream>,
shader_cache: Gd<ShaderCache>,
}

#[godot_api]
impl INode for CacheManager {
fn init(base: Base<Self::Base>) -> Self {
let shader_cache = Gd::from_init_fn(|base| ShaderCache::init(base));

Self {
base,
texture_cache: ResourceCache::new(),
canvas_layer_cache: ResourceCache::new(),
ui_cache: ResourceCache::new(),
audio_cache: ResourceCache::new(),
shader_cache,
}
}

fn ready(&mut self) {
let shader_cache = self.shader_cache.clone();

{
let mut base = self.base_mut();
base.add_child(&shader_cache.upcast::<Node>());
}
}
}

#[godot_api]
impl CacheManager {
fn internal_canvas_layer_cache(&self) -> &ResourceCache<CanvasLayer> {
&self.canvas_layer_cache
}

fn internal_ui_cache(&self) -> &ResourceCache<Control> {
&self.ui_cache
}

fn internal_texture_cache(&self) -> &ResourceCache<Texture2D> {
&self.texture_cache
}

pub fn internal_audio_cache(&self) -> &ResourceCache<AudioStream> {
&self.audio_cache
}

fn internal_shader_cache(&self) -> &Gd<ShaderCache> {
&self.shader_cache
}

fn internal_shader_cache_as_node(&self) -> Gd<Node> {
self.shader_cache.clone().upcast::<Node>()
}

#[func]
fn get_from_canvas_layer_cache(&self, key: GString) -> Option<Gd<CanvasLayer>> {
self.canvas_layer_cache.get(key.to_string().as_str())
}

#[func]
fn get_from_ui_cache(&self, key: GString) -> Option<Gd<Control>> {
self.ui_cache.get(key.to_string().as_str())
}

#[func]
fn get_from_texture_cache(&self, key: GString) -> Option<Gd<Texture2D>> {
self.texture_cache.get(key.to_string().as_str())
}

#[func]
fn get_from_audio_cache(&self, key: GString) -> Option<Gd<AudioStream>> {
self.audio_cache.get(key.to_string().as_str())
}

#[func]
fn obtain_shader_cache(&self) -> Gd<ShaderCache> {
self.shader_cache.clone()
}
}
Empty file.
6 changes: 6 additions & 0 deletions packages/rust/q/src/data/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pub mod uxui_data;
pub mod gui_data;
pub mod user_data;
pub mod abstract_data_map;
pub mod shader_data;
pub mod cache;
Loading