sevenx_engine 0.2.11

Engine de jogos 2D/3D completa com suporte Android, física, áudio, partículas, tilemap, UI, eventos e sistema 3D avançado com PBR.
Documentation
pub mod achievements;
pub mod animation;
pub mod audio;
pub mod camera;
pub mod collision;
pub mod config;
pub mod dialogue;
pub mod events;
pub mod game_object;
pub mod game_state;
pub mod gamepad;
pub mod graphics;
pub mod input;
pub mod level;
pub mod networking;
pub mod particles;
pub mod physics;
pub mod primitives2d;
pub mod renderer;
pub mod resource_manager;
pub mod save_system;
pub mod custom_shader;
pub mod shader;
pub mod sprite;
pub mod sprite_advanced;
pub mod tilemap;
pub mod transform;
pub mod ui;
pub mod ui_advanced;
pub mod world;

// 🆕 v0.2.6 - Experimental 3D & Advanced Features
pub mod camera3d;
pub mod mesh3d;
pub mod model_loader;
pub mod renderer3d;
pub mod shader3d;
pub mod particles3d;
pub mod texture3d;
pub mod lighting;
pub mod pathfinding;
pub mod postprocessing;

// 🆕 v0.2.8 - Advanced 3D Features
pub mod frustum_culling;
pub mod skybox;
pub mod lod;
pub mod physics3d;
pub mod octree;
pub mod terrain;
pub mod billboard;

// 🆕 v0.2.8 - Game Systems
pub mod inventory;
pub mod animation_system;
pub mod quest;
pub mod platform;

// 🆕 v0.2.9 - Android Support
pub mod android;

// 🆕 v0.2.9 - Advanced 3D Rendering
pub mod pbr;
pub mod advanced_renderer3d;

pub use achievements::{Achievement, AchievementSystem};
pub use audio::AudioSystem;
pub use camera::Camera;
pub use collision::{Collider, Rect};
pub use config::EngineConfig;
pub use dialogue::{Dialogue, DialogueBuilder, DialogueSystem};
pub use events::{EventData, EventSystem, EventType};
pub use game_state::GameState;
pub use gamepad::{GamepadAxis, GamepadButton, GamepadManager, GamepadState};
pub use graphics::{GraphicsQuality, GraphicsSettings, OptimizationSettings, PerformanceMonitor};
pub use input::MouseBtn;
pub use level::{Level, LevelObject, LevelProperties};
pub use networking::{NetworkManager, NetworkMessage, PlayerInfo};
pub use particles::{BlendMode, Particle, ParticleConfig, ParticleSystem};
pub use physics::Physics;
pub use primitives2d::Primitives2D;
pub use resource_manager::ResourceManager;
pub use save_system::{GameProgress, GameSave, GameSettings, PlayerData};
pub use custom_shader::{CustomShader, ShaderBuilder, ShaderLibrary, ShaderUniform};
pub use shader::{Shader, ShaderManager, ShaderType};
pub use sprite_advanced::{BlendMode2D, EffectManager, EffectType, SpriteAdvanced, SpriteAnimation, VisualEffect};
pub use tilemap::{Tile, Tilemap};
pub use transform::Transform;
pub use ui::Button;
pub use ui_advanced::{
    Button as UIButton, Checkbox, Label, Panel, ProgressBar, Slider, UIEvent, UIManager, UITheme,
    WidgetState,
};
pub use winit::keyboard::KeyCode;

// 🆕 v0.2.6 Exports
pub use camera3d::Camera3D;
pub use mesh3d::{Mesh3D, MirrorAxis, Vec3, Vertex};
pub use model_loader::{ModelBuilder, ModelError, ModelLoader};
pub use renderer3d::Renderer3D;
pub use shader3d::{
    Light3D, Material, PhongShader, ToonShader, WireframeShader,
    FresnelShader, NormalMapShader, ReflectionShader, FogShader
};
pub use particles3d::{Particle3D, ParticleSystem3D};
pub use texture3d::{Material3D, Texture3D};
pub use lighting::{Light, LightType, LightingSystem};
pub use pathfinding::{GridPos, Pathfinder};
pub use postprocessing::{PostEffect, PostProcessor};

// 🆕 v0.2.8 Exports
pub use frustum_culling::{BoundingBox, BoundingSphere, CullingResult, CullingStats, Frustum, Plane};
pub use skybox::{ProceduralSky, Skybox, SkyboxTextures};
pub use lod::{LODLevel, LODMesh, LODQuality, LODStats};
pub use physics3d::{Collider3D, ColliderShape, Collision3D, Physics3D, RaycastHit, RigidBody3D};
pub use octree::{Octree, OctreeStats};
pub use terrain::{Terrain, TerrainConfig};
pub use billboard::{Billboard, BillboardBatch, BillboardType};
pub use inventory::{Inventory, Item, ItemRarity, ItemStack, ItemType};
pub use animation_system::{Animation as AnimationTween, AnimationBuilder, AnimationSystem, AnimationValue, EasingFunction, Keyframe, LoopMode};
pub use quest::{ObjectiveType, Quest, QuestObjective, QuestRewards, QuestStatus, QuestSystem};
pub use platform::{Architecture, Platform, PlatformInfo};

// 🆕 v0.2.9 Exports
pub use android::{
    AccelerometerData, AndroidInput, AndroidManager, AndroidPerformance, AndroidVibration,
    BatteryInfo, GyroscopeData, TouchEvent, TouchPhase, TouchPoint, VibrationIntensity,
    VibrationPattern, VirtualJoystick,
    // Advanced features
    AdvancedAndroidManager, ConnectivityManager, Gesture, GestureRecognizer, GestureType,
    NetworkType, Notification, NotificationManager, OrientationManager, Permission,
    PermissionManager, PinchType, ScreenOrientation, ShareManager, StorageManager,
    SwipeDirection, VirtualKeyboard,
};

pub use pbr::{Bloom, HDRProcessor, PBRLight, PBRMaterial, PBRShader, ShadowMap, SSAO};
pub use advanced_renderer3d::{AdvancedRenderer3D, GBuffer, RenderMode, RenderQuality, RenderStats};

use crate::input::InputHandler;
use crate::renderer::Renderer;
use crate::world::World;
use pixels::{Error as PixelsError, Pixels, SurfaceTexture};
use std::sync::Arc;
use std::time::Instant;
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowId};



pub struct Engine {
    window: Option<Arc<Window>>,
    pixels: Option<Pixels<'static>>,
    input: InputHandler,
    world: World,
    last_update: Instant,
    game_state: Option<Box<dyn GameState>>,
    renderer: Renderer,
    config: EngineConfig,
}

impl Engine {
    pub fn new() -> Self {
        Self::with_config(EngineConfig::default())
    }

    pub fn with_config(config: EngineConfig) -> Self {
        let world = World::with_gravity(config.gravity);
        let renderer = Renderer::new(config.window_width, config.window_height)
            .with_clear_color(config.clear_color);

        Self {
            window: None,
            pixels: None,
            input: InputHandler::new(),
            world,
            last_update: Instant::now(),
            game_state: None,
            renderer,
            config,
        }
    }

    pub fn run<G: GameState + 'static>(mut self) {
        self.game_state = Some(Box::new(G::new()));
        let event_loop = EventLoop::new().unwrap();
        event_loop.set_control_flow(ControlFlow::Wait);
        let _ = event_loop.run_app(&mut self);
    }

    pub fn get_camera_mut(&mut self) -> &mut Camera {
        &mut self.renderer.camera
    }

    fn update(&mut self, dt: f32) {
        if let Some(game_state) = self.game_state.as_mut() {
            game_state.update(dt, &self.input, &mut self.world);
        }
        self.world.update(dt);
    }

    fn draw(&mut self) {
        if let Some(pixels) = self.pixels.as_mut() {
            let frame_buffer = pixels.frame_mut();
            
            // Renderiza o mundo (sprites, etc)
            self.renderer.draw(&self.world, frame_buffer);
            
            // Chama o draw customizado do GameState
            if let Some(game_state) = self.game_state.as_mut() {
                game_state.draw(&self.world, frame_buffer);
            }
        }
    }

    fn resize_surface(&mut self, width: u32, height: u32) -> Result<(), PixelsError> {
        if let Some(pixels) = self.pixels.as_mut() {
            pixels.resize_surface(width, height)?
        }
        Ok(())
    }
}

impl ApplicationHandler for Engine {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_none() {
            let window_attrs = Window::default_attributes()
                .with_title(&self.config.window_title)
                .with_inner_size(LogicalSize::new(
                    self.config.window_width,
                    self.config.window_height,
                ));
            let window = Arc::new(event_loop.create_window(window_attrs).unwrap());
            self.window = Some(window.clone());

            let window_ref: &'static Window = unsafe { std::mem::transmute(&*window) };

            let window_size = window.inner_size();
            let surface_texture =
                SurfaceTexture::new(window_size.width, window_size.height, window_ref);
            let pixels = Pixels::new(
                self.config.window_width,
                self.config.window_height,
                surface_texture,
            )
            .expect("Failed to create pixels");
            self.pixels = Some(pixels);
        }
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
        self.input.update(&event);
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(new_size) => {
                if new_size.width > 0 && new_size.height > 0 {
                    if let Err(err) = self.resize_surface(new_size.width, new_size.height) {
                        eprintln!("Error resizing surface: {}", err);
                        event_loop.exit();
                    }
                    self.renderer.camera.resize_viewport(new_size.width, new_size.height);
                }
            }
            WindowEvent::RedrawRequested => {
                let now = Instant::now();
                let dt = now.duration_since(self.last_update).as_secs_f32();
                self.last_update = now;

                self.update(dt);
                self.draw();

                if let (Some(pixels), Some(window)) = (self.pixels.as_mut(), self.window.as_ref()) {
                    if pixels.render().is_err() {
                        event_loop.exit();
                        return;
                    }
                    window.request_redraw();
                }
            }
            _ => (),
        }
    }
}