### Conf Example Configuration Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md An example demonstrating how to create a custom `Conf` struct with specific settings, overriding default values. ```rust Conf { window_title: "My Game".to_string(), window_width: 1280, window_height: 720, high_dpi: true, sample_count: 4, platform: Platform { linux_backend: LinuxBackend::X11WithWaylandFallback, apple_gfx_api: AppleGfxApi::Metal, ..Default::default() }, ..Default::default() } ``` -------------------------------- ### start() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Starts the Miniquad application event loop and initializes the application with a given configuration and a factory function for the event handler. This function blocks until the application quits. ```APIDOC ## start() ### Description Starts the Miniquad application event loop. This function blocks and runs the platform event loop until the application quits. The factory function `f` is called once at startup and should return an implementation of `EventHandler`. ### Method `start(conf: conf::Conf, f: F)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use miniquad::* fn main() { start( Conf { window_title: "My App".to_string(), window_width: 800, window_height: 600, ..Default::default() }, || Box::new(MyApp::new()), ); } struct MyApp { // application state } impl EventHandler for MyApp { fn update(&mut self) { /* ... */ } fn draw(&mut self) { /* ... */ } } ``` ### Response This function does not return a value as it blocks the event loop. ``` -------------------------------- ### Complete Triangle Rendering Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md A full example demonstrating how to set up and render a simple triangle using miniquad. This includes shader, buffer, and pipeline creation, along with the main event loop. ```rust use miniquad::* fn main() { start(Conf::default(), || Box::new(Stage::new())); } struct Stage { ctx: Box, pipeline: Pipeline, bindings: Bindings, } impl Stage { fn new() -> Self { let mut ctx = window::new_rendering_backend(); // Create shader let shader = ctx.new_shader( ShaderSource::Glsl { vertex: r#"#version 100 attribute vec3 in_pos; void main() { gl_Position = vec4(in_pos, 1.0); }"#, fragment: r#"#version 100 void main() { gl_FragColor = vec4(1.0); }"#, }, ShaderMeta { uniforms: UniformBlockLayout { uniforms: vec![] }, images: vec![], }, ).unwrap(); // Create vertex buffer let verts = vec![[0.0, 0.5, 0.0], [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0]]; let vb = ctx.new_buffer( BufferType::VertexBuffer, BufferUsage::Immutable, BufferSource::slice(&verts), ); // Create index buffer let indices = vec![0u16, 1, 2]; let ib = ctx.new_buffer( BufferType::IndexBuffer, BufferUsage::Immutable, BufferSource::slice(&indices), ); // Create pipeline let pipeline = ctx.new_pipeline( &[BufferLayout::default()], &[VertexAttribute::new("in_pos", VertexFormat::Float3)], shader, PipelineParams::default(), ); let bindings = Bindings { vertex_buffers: vec![vb], index_buffer: ib, images: vec![], }; Stage { ctx, pipeline, bindings } } } impl EventHandler for Stage { fn update(&mut self) {} fn draw(&mut self) { self.ctx.begin_default_pass(PassAction::clear_color(0.0, 0.0, 0.0, 1.0)); self.ctx.apply_pipeline(&self.pipeline); self.ctx.apply_bindings(&self.bindings); self.ctx.draw(0, 3, 1); self.ctx.end_render_pass(); self.ctx.commit_frame(); } } ``` -------------------------------- ### ShaderMeta Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Provides an example of initializing a ShaderMeta struct with uniform descriptions and image names. ```rust ShaderMeta { uniforms: UniformBlockLayout { uniforms: vec![ UniformDesc::new("mvp", UniformType::Mat4), UniformDesc::new("time", UniformType::Float1), ], }, images: vec!["u_texture".to_string()], } ``` -------------------------------- ### Entry Point Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md The entry point for starting the miniquad application and its event loop. ```APIDOC ## Entry Point ### Description Starts the event loop for the miniquad application. ### Method `miniquad::start(conf, factory)` ### Parameters - **conf** (Configuration) - The configuration for the application. - **factory** (Factory) - The factory function to create the application instance. ``` -------------------------------- ### Minimal Desktop Configuration Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md The most basic configuration for starting a miniquad application on desktop. ```rust miniquad::start(Conf::default(), || Box::new(MyApp::new())); ``` -------------------------------- ### Initialization and Window Control Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Functions for starting the miniquad application and controlling the window. ```APIDOC ## miniquad::start() ### Description Initializes the miniquad application and sets up the window. ### Method `start` ### Parameters - `conf` (Conf): Configuration for the window and application. - `event_loop` (FnMut(Event)): Callback function to handle events. ### Request Example ```rust miniquad::start(conf, |e| match e { miniquad::Event::Key { key, .. } => println!("{:?}", key), _ => (), }); ``` ## Window Module Functions ### Description Provides functions for window control and queries. ### Functions - `set_cursor_grab(locked: bool)` - `set_cursor_visible(visible: bool)` - `cursor_position() -> (f32, f32)` - `set_fullscreen(fullscreen: bool)` - `fullscreen() -> bool` - `set_window_size(width: f32, height: f32)` - `window_size() -> (f32, f32)` - `set_window_title(title: &str)` - `dpi_scale() -> f32` - `gl_context_version() -> (u32, u32)` - `request_user_attention()` - `show_keyboard(visible: bool)` - `keyboard_shown() -> bool` - `touch_subsystem() -> bool` - `set_ime_position(x: f32, y: f32)` ### Example ```rust // Example of setting window title and size miniquad::set_window_title("My Miniquad App"); miniquad::set_window_size(800.0, 600.0); ``` ``` -------------------------------- ### miniquad::start() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt The entry point for a Miniquad application. This function initializes the library and starts the application's event loop. ```APIDOC ## miniquad::start() ### Description Initializes the miniquad library and runs the application's main loop. ### Function Signature `pub fn start(conf: Conf, run: F) where F: FnMut() -> ()` ### Parameters - **conf** (Conf) - The configuration for the application window and backend. - **run** (FnMut()) - A closure that will be executed as the main application loop. ``` -------------------------------- ### UniformDesc Creation Examples Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Shows how to create UniformDesc instances for scalar and array uniforms. ```rust UniformDesc::new("mvp", UniformType::Mat4) ``` ```rust UniformDesc::new("colors", UniformType::Float4).array(10) ``` -------------------------------- ### Creating a Custom Icon Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Example of how to create and assign a custom window icon. Ensure pixel data is in RGBA format. ```rust let mut icon_bytes = [0u8; 16 * 16 * 4]; // ... fill with RGBA pixel data ... let icon = Icon { small: icon_bytes, medium: icon_bytes, big: icon_bytes, }; Conf { icon: Some(icon), ..Default::default() } ``` -------------------------------- ### ShaderSource Usage Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Demonstrates selecting the correct ShaderSource variant based on the current graphics backend. ```rust let source = match ctx.info().backend { Backend::OpenGl => ShaderSource::Glsl { vertex: VS, fragment: FS }, Backend::Metal => ShaderSource::Msl { program: MSL }, }; let shader = ctx.new_shader(source, meta)?; ``` -------------------------------- ### VertexAttribute Instantiation Examples Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Demonstrates how to create VertexAttribute instances for different shader inputs like position, color, and normal. ```rust VertexAttribute::new("in_pos", VertexFormat::Float3) VertexAttribute::new("in_color", VertexFormat::Byte4) VertexAttribute::with_buffer("in_normal", VertexFormat::Float3, 1) ``` -------------------------------- ### Minimal miniquad Application Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md The most basic configuration to start a miniquad application using default settings. ```rust fn main() { miniquad::start(Conf::default(), || Box::new(MyApp::new())); } ``` -------------------------------- ### Shader Compilation Error Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/errors.md Provides an example of creating a shader with GLSL source that intentionally causes a compilation error and how to handle it. ```rust let shader_result = ctx.new_shader( ShaderSource::Glsl { vertex: r#"# #version 100 attribute vec3 in_pos; void main() { gl_Position = vec4(in_pos, 1.0); } "#, fragment: r#"# #version 100 uniform sampler2D u_texture; void main() { // Error: undefined variable 'vUv' gl_FragColor = texture2D(u_texture, vUv); } "#, }, ShaderMeta { uniforms: UniformBlockLayout { uniforms: vec![] }, images: vec!["u_texture".to_string()], }, ); if let Err(e) = shader_result { match e { ShaderError::CompilationError { shader_type, error_message } => { eprintln!("{} shader failed:\n{}", shader_type, error_message); // Output: // "Fragment shader failed: // error: undeclared identifier 'vUv'" } _ => eprintln!("Shader error: {}", e), } } ``` -------------------------------- ### Creating Buffers with BufferSource Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Example of creating a vertex buffer from a slice of vertices and an empty dynamic vertex buffer. ```rust let verts: [Vertex; 100] = [...]; let vb = ctx.new_buffer(BufferType::VertexBuffer, BufferUsage::Immutable, BufferSource::slice(&verts)); let dynamic = ctx.new_buffer(BufferType::VertexBuffer, BufferUsage::Dynamic, BufferSource::empty::(1000)); ``` -------------------------------- ### begin_default_pass Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Starts rendering to the default framebuffer with a specified clear action. ```APIDOC ## begin_default_pass ### Description Start rendering to the default framebuffer. ### Method Signature ```rust fn begin_default_pass(&mut self, action: PassAction) ``` ### Parameters #### Path Parameters - `action` (PassAction) - Required - Clear operation or preserve ### Request Example ```rust ctx.begin_default_pass(PassAction::clear_color(0.0, 0.0, 0.0, 1.0)); ``` ``` -------------------------------- ### fn info() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Get the graphics backend and capabilities. Returns platform identification and feature support flags. ```APIDOC ## fn info() ### Description Get the graphics backend and capabilities. ### Returns `ContextInfo` - Platform identification and feature support flags. ``` -------------------------------- ### begin_pass Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Starts rendering to an offscreen texture or the default framebuffer. ```APIDOC ## begin_pass ### Description Start rendering to an offscreen texture. ### Method Signature ```rust fn begin_pass(&mut self, pass: Option, action: PassAction) ``` ### Parameters #### Path Parameters - `pass` (Option) - Optional - Render pass, or `None` for default FB - `action` (PassAction) - Required - Clear operation ``` -------------------------------- ### Applying Uniforms Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Demonstrates how to create a Uniforms struct and apply it to the rendering context using UniformsSource::table. Ensure the Uniforms struct is marked with #[repr(C)]. ```rust #[repr(C)] struct Uniforms { mvp: [[f32; 4]; 4], color: [f32; 4], } let u = Uniforms { mvp: [...], color: [1.0, 0.0, 0.0, 1.0] }; ctx.apply_uniforms(UniformsSource::table(&u)); ``` -------------------------------- ### Standard Alpha Blending Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Demonstrates how to configure BlendState for standard alpha blending, where the source color is blended with the destination color based on the source's alpha. ```rust BlendState::new( Equation::Add, BlendFactor::Value(BlendValue::SourceAlpha), BlendFactor::OneMinusValue(BlendValue::SourceAlpha), ) ``` -------------------------------- ### Begin Default Pass Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Starts rendering to the default framebuffer. Specify a PassAction to clear or preserve the framebuffer contents. ```rust fn begin_default_pass(&mut self, action: PassAction) ``` ```rust ctx.begin_default_pass(PassAction::clear_color(0.0, 0.0, 0.0, 1.0)); ``` -------------------------------- ### Quitting the Application Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Provides an example of how to programmatically quit the application. Typically used in response to user actions or specific conditions. ```Rust window::quit(ctx); ``` -------------------------------- ### Begin Pass Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Starts rendering to an offscreen render pass or the default framebuffer if None is provided. Requires a PassAction for clearing. ```rust fn begin_pass(&mut self, pass: Option, action: PassAction) ``` -------------------------------- ### Miniquad File Loading Error Handling Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/errors.md Demonstrates how to handle the various fs::Error variants returned by fs::load_file() in a callback function, including specific actions for I/O errors, download failures, and platform-specific asset issues. ```rust miniquad::fs::load_file("assets/data.json", |response| { match response { Ok(bytes) => { // Successfully loaded let json_str = String::from_utf8(bytes).unwrap(); println!("Loaded: {}", json_str); } Err(Error::IOError(e)) => { eprintln!("File I/O error: {}", e); // Fallback: use default data, show error UI, etc. } Err(Error::DownloadFailed) => { eprintln!("Network error; check internet connection"); } Err(Error::AndroidAssetLoadingError) => { eprintln!("Asset file not included in APK"); } Err(Error::IOSAssetNoSuchFile) => { eprintln!("File not in app bundle"); } Err(Error::IOSAssetNoData) => { eprintln!("File is empty or unreadable"); } } }); ``` -------------------------------- ### Miniquad Minimal Working Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md This Rust code sets up a basic miniquad application. It initializes the rendering backend, defines shaders, vertex and index buffers, and a pipeline to draw a red triangle. The `EventHandler` trait is implemented to handle drawing and application events. ```rust use miniquad::* struct Stage { ctx: Box, pipeline: Pipeline, bindings: Bindings, } impl Stage { fn new() -> Self { let mut ctx = window::new_rendering_backend(); // Shader let shader = ctx.new_shader( ShaderSource::Glsl { vertex: r"#version 100 attribute vec2 in_pos; void main() { gl_Position = vec4(in_pos, 0.0, 1.0); }"#, fragment: r"#version 100 void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }"#, }, ShaderMeta { uniforms: UniformBlockLayout { uniforms: vec![] }, images: vec![], }, ).unwrap(); // Triangle vertices let verts = vec![[-0.5, 0.5], [0.5, 0.5], [0.0, -0.5]]; let vb = ctx.new_buffer( BufferType::VertexBuffer, BufferUsage::Immutable, BufferSource::slice(&verts), ); // Indices let indices = vec![0u16, 1, 2]; let ib = ctx.new_buffer( BufferType::IndexBuffer, BufferUsage::Immutable, BufferSource::slice(&indices), ); // Pipeline let pipeline = ctx.new_pipeline( &[BufferLayout::default()], &[VertexAttribute::new("in_pos", VertexFormat::Float2)], shader, PipelineParams::default(), ); Stage { ctx, pipeline, bindings: Bindings { vertex_buffers: vec![vb], index_buffer: ib, images: vec![], }, } } } impl EventHandler for Stage { fn update(&mut self) {} fn draw(&mut self) { self.ctx.begin_default_pass(PassAction::clear_color(0.0, 0.0, 0.0, 1.0)); self.ctx.apply_pipeline(&self.pipeline); self.ctx.apply_bindings(&self.bindings); self.ctx.draw(0, 3, 1); self.ctx.end_render_pass(); self.ctx.commit_frame(); } } fn main() { miniquad::start(Conf::default(), || Box::new(Stage::new())); } ``` -------------------------------- ### Clipboard Access Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to interact with the system clipboard to get or set text. Essential for copy-paste functionality. ```Rust let clipboard_content = window::clipboard(ctx); window::set_clipboard_content(ctx, "some text"); ``` -------------------------------- ### Keyboard Input Handling Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/event-types.md Implements keyboard event handling for movement controls and modifier key combinations like Ctrl+Z for undo. Handles both key down and key up events. ```rust impl EventHandler for MyApp { fn key_down_event(&mut self, key: KeyCode, mods: KeyMods, _repeat: bool) { match key { KeyCode::W => self.forward = true, KeyCode::A => self.left = true, KeyCode::S => self.backward = true, KeyCode::D => self.right = true, KeyCode::Escape => window::request_quit(), _ => {} } // Check modifiers if mods.ctrl { if key == KeyCode::Z { self.undo(); } } } fn key_up_event(&mut self, key: KeyCode, _mods: KeyMods) { match key { KeyCode::W => self.forward = false, KeyCode::A => self.left = false, KeyCode::S => self.backward = false, KeyCode::D => self.right = false, _ => {} } } } ``` -------------------------------- ### Mouse Input Handling Example Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/event-types.md Implements mouse event handling for tracking cursor position, and detecting mouse button presses and releases. Used for actions like selection or context menus. ```rust impl EventHandler for MyApp { fn mouse_motion_event(&mut self, x: f32, y: f32) { self.mouse_x = x; self.mouse_y = y; } fn mouse_button_down_event(&mut self, btn: MouseButton, x: f32, y: f32) { match btn { MouseButton::Left => self.selecting = true, MouseButton::Right => self.context_menu_pos = (x, y), _ => {} } } fn mouse_button_up_event(&mut self, btn: MouseButton, _x: f32, _y: f32) { match btn { MouseButton::Left => self.selecting = false, _ => {} } } } ``` -------------------------------- ### UniformType Size Method Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Illustrates the usage of the `size` method on UniformType to get the size in bytes. ```rust impl UniformType { pub fn size(&self) -> usize // Returns size in bytes } ``` -------------------------------- ### Default PipelineParams Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Provides the default configuration for PipelineParams. This is useful when you need a standard setup without specifying every detail. ```rust PipelineParams { cull_face: CullFace::Nothing, front_face_order: FrontFaceOrder::CounterClockwise, depth_test: Comparison::Always, depth_write: false, depth_write_offset: None, color_blend: None, alpha_blend: None, stencil_test: None, color_write: (true, true, true, true), primitive_type: PrimitiveType::Triangles, } ``` -------------------------------- ### Get Clipboard Text Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Reads text from the operating system's clipboard. Returns `None` if the clipboard is empty or unavailable. ```rust pub fn clipboard_get() -> Option ``` -------------------------------- ### Use Built-in Logo Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md Utilize the static method `miniquad_logo()` to get an Icon instance pre-populated with the miniquad branding. ```rust Icon::miniquad_logo() // Returns Icon with miniquad branding ``` -------------------------------- ### Get Apple Graphics API Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the graphics API currently in use on Apple platforms. Returns either `AppleGfxApi::OpenGl` or `AppleGfxApi::Metal`. ```rust #[cfg(target_vendor = "apple")] pub fn apple_gfx_api() -> crate::conf::AppleGfxApi ``` -------------------------------- ### Blocking Event Loop for Low Power Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt An example of configuring the event loop to block when no events are pending, which can save power. Useful for applications that don't require constant updates. ```Rust // Configuration for a blocking event loop would be set in Conf or application logic. ``` -------------------------------- ### Date/Time Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Method for getting the current time. ```APIDOC ## Date/Time ### Description Provides a method to get the current time. ### Method - `date::now()`: Returns the number of seconds since the UNIX epoch. ``` -------------------------------- ### High-DPI Desktop App Configuration Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md Set up a desktop application with high DPI support, a resizable window, and a specific swap interval. ```rust Conf { window_title: "Desktop App".to_string(), window_width: 640, window_height: 480, high_dpi: true, window_resizable: true, platform: Platform { swap_interval: Some(1), ..Default::default() }, ..Default::default() } ``` -------------------------------- ### Get Texture Size Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves the dimensions (width and height) of a texture. ```rust fn texture_size(&self, texture: TextureId) -> (u32, u32) ``` -------------------------------- ### Get Texture Parameters Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves the `TextureParams` associated with a given `TextureId`. ```rust fn texture_params(&self, texture: TextureId) -> TextureParams ``` -------------------------------- ### window::new_rendering_backend() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Creates a platform-appropriate graphics context, defaulting to Metal on Apple platforms or OpenGL otherwise. ```APIDOC ## window::new_rendering_backend() ### Description Create a platform-appropriate graphics context. ### Returns - `Box`: A boxed trait object representing the rendering backend. ### Notes Returns a Metal context on Apple platforms (if configured), otherwise OpenGL. Called automatically by the framework but available for manual context creation. ``` -------------------------------- ### Get GPU buffer size Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves the size of a GPU buffer in bytes. ```rust fn buffer_size(&mut self, buffer: BufferId) -> usize ``` -------------------------------- ### Configure Miniquad Application Window Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Set up window properties like title, dimensions, and high DPI support. Uses `Default::default()` for unspecified options. ```rust let conf = miniquad::Conf { window_title: "My App".to_string(), window_width: 800, window_height: 600, high_dpi: true, ..Default::default() }; ``` -------------------------------- ### PassAction Enum Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Defines actions to be performed at the start of a render pass, such as clearing buffers. ```APIDOC ## PassAction Enum What to do at the start of a render pass. ```rust pub enum PassAction { Nothing, Clear { color: Option<(f32, f32, f32, f32)>, depth: Option, stencil: Option }, } ``` | Variant | Description | |---------|-------------| | `Nothing` | Keep existing framebuffer contents | | `Clear { ... }` | Clear specified channels | **Methods:** ```rust impl PassAction { pub fn clear_color(r: f32, g: f32, b: f32, a: f32) -> PassAction } ``` **Default:** `Clear { color: Some((0, 0, 0, 0)), depth: Some(1.0), stencil: None }` ``` -------------------------------- ### Initialize and Use Miniquad Graphics Context Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Obtain a rendering backend, create graphics resources like shaders and buffers, and perform drawing operations. ```rust let mut ctx: Box = window::new_rendering_backend(); // Create shaders, buffers, textures, pipelines, and draw let shader = ctx.new_shader(shader_source, meta)?; let buffer = ctx.new_buffer(BufferType::VertexBuffer, BufferUsage::Immutable, data); let pipeline = ctx.new_pipeline(&layout, &attrs, shader, params); ctx.begin_default_pass(PassAction::clear_color(0.0, 0.0, 0.0, 1.0)); ctx.apply_pipeline(&pipeline); ctx.apply_bindings(&bindings); ctx.draw(0, 6, 1); ctx.end_render_pass(); ctx.commit_frame(); ``` -------------------------------- ### Platform-Specific Configurations Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how to apply platform-specific configurations. This allows tailoring the application's behavior on different operating systems or platforms. ```Rust let conf = Conf { platform: Platform { // ... platform-specific settings ... ..Default::default() }, ..Default::default() }; miniquad::start(conf, |ctx| {}); ``` -------------------------------- ### Window Size and DPI Scaling Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to retrieve the current screen size and DPI scale factor for the window. Important for responsive UI design. ```Rust let size = window::screen_size(ctx); let dpi = window::dpi_scale(ctx); ``` -------------------------------- ### Get Apple View Controller (iOS) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the Objective-C view controller specifically on iOS. ```rust #[cfg(target_os = "ios")] pub fn apple_view_ctrl() -> crate::native::apple::frameworks::ObjcId ``` -------------------------------- ### Linux Window Backend Selection Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Select the desired window system backend for Linux. Options include X11 only, Wayland only, or fallbacks between the two. Note that Wayland support is less stable than X11. ```rust pub enum LinuxBackend { X11Only, WaylandOnly, X11WithWaylandFallback, WaylandWithX11Fallback, } ``` -------------------------------- ### Get Window Position Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the current position of the window in screen pixels. This function is only available on Windows and Linux. ```rust #[cfg(any(target_os = "windows", target_os = "linux"))] pub fn get_window_position() -> (u32, u32) ``` -------------------------------- ### Default Conf Implementation (Desktop) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Provides the default configuration values for desktop platforms. ```rust impl Default for Conf { fn default() -> Conf { Conf { window_title: "".to_owned(), window_width: 800, window_height: 600, high_dpi: false, fullscreen: false, sample_count: 1, window_resizable: true, icon: Some(Icon::miniquad_logo()), platform: Default::default(), } } } ``` -------------------------------- ### BufferSource Methods Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Provides methods for creating BufferSource instances, which represent the initial data for buffer creation. This includes creating empty buffers or buffers from data slices. ```APIDOC ## BufferSource Methods ### Description Methods for creating `BufferSource` instances, which define the initial data for GPU buffers. ### Methods - `empty(size: usize) -> BufferSource<'a>`: Creates an empty buffer of a specified size. - `slice(data: &'a [T]) -> BufferSource<'a>`: Creates a buffer from a slice of data. - `unsafe fn pointer(ptr: *const u8, size: usize, element_size: usize) -> BufferSource<'a>`: Creates a buffer from a raw pointer (unsafe). ### Example ```rust // Example of creating a vertex buffer from a slice let verts: [Vertex; 100] = [...]; let vb = ctx.new_buffer(BufferType::VertexBuffer, BufferUsage::Immutable, BufferSource::slice(&verts)); // Example of creating a dynamic buffer with pre-allocated space let dynamic = ctx.new_buffer(BufferType::VertexBuffer, BufferUsage::Dynamic, BufferSource::empty::(1000)); ``` ``` -------------------------------- ### Web Demo Configuration (WebGL 2) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Configure miniquad for a web demo using WebGL 2, with a specified window title and enabling a blocking event loop. ```rust Conf { window_title: "Web Demo".to_string(), platform: Platform { webgl_version: WebGLVersion::WebGL2, blocking_event_loop: true, ..Default::default() }, ..Default::default() } ``` -------------------------------- ### Wayland Window Decorations Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md Configure how window decorations are drawn on Wayland when the server does not provide them. `ServerWithLibDecorFallback` provides native-looking decorations. ```rust platform: Platform { wayland_decorations: WaylandDecorations::ServerWithLibDecorFallback, ..Default::default() } ``` -------------------------------- ### X11 OpenGL Context Creation Method Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Choose the OpenGL context creation method on X11. Options include GLX only, EGL only, or fallbacks between GLX and EGL. GLX is older and more stable, while EGL is newer and better for mobile. ```rust pub enum LinuxX11Gl { GLXOnly, EGLOnly, GLXWithEGLFallback, EGLWithGLXFallback, } ``` -------------------------------- ### Desktop Game Configuration (1080p, Fullscreen, High DPI, Metal) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Configures a desktop application for a 1080p fullscreen experience with high DPI support and Metal graphics API on Apple platforms. VSync is enabled. ```rust let conf = Conf { window_title: "My Game".to_string(), window_width: 1920, window_height: 1080, fullscreen: true, high_dpi: true, sample_count: 4, // MSAA 4x platform: Platform { apple_gfx_api: AppleGfxApi::Metal, swap_interval: Some(1), // VSync on ..Default::default() }, ..Default::default() }; miniquad::start(conf, || Box::new(MyApp::new())); ``` -------------------------------- ### Low-Latency Web Demo (WebGL 2, Blocking Loop) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Sets up a web demo using WebGL 2 with a blocking event loop for low latency. The sleep interval is set to 0 for immediate response. ```rust let conf = Conf { window_title: "Web Demo".to_string(), window_resizable: false, platform: Platform { webgl_version: WebGLVersion::WebGL2, blocking_event_loop: true, sleep_interval_ms: Some(0), // No sleep, respond immediately ..Default::default() }, ..Default::default() }; miniquad::start(conf, || Box::new(MyApp::new())); ``` -------------------------------- ### Date and Time Retrieval Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to get the current date and time. Useful for logging, timestamps, or time-based game logic. ```Rust let now = date::now(); ``` -------------------------------- ### window::* functions Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt A collection of functions for interacting with the application window, including screen size, DPI scaling, clipboard access, cursor manipulation, and application termination. ```APIDOC ## window::* (Window Functions) ### Description Provides a set of utility functions for managing and querying the application window. ### Functions - **`screen_size()`**: Returns the dimensions of the screen. - **`dpi_scale()`**: Returns the current DPI scale factor of the window. - **`clipboard()`**: Provides access to the system clipboard. - **`cursor()`**: Manages the mouse cursor's visibility and shape. - **`quit()`**: Requests the application to terminate. ``` -------------------------------- ### window::set_fullscreen() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Toggles the application window between fullscreen and windowed modes. Use `true` to enable fullscreen and `false` to disable it. ```APIDOC ## window::set_fullscreen() ### Description Toggle fullscreen mode for the application window. ### Method `set_fullscreen(fullscreen: bool)` ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `fullscreen` (bool) - Required - `true` to enable fullscreen mode, `false` to switch to windowed mode. ``` -------------------------------- ### TouchPhase Enum Definition Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/event-types.md Defines the different states a touch input can be in during its lifecycle. Includes Started, Moved, Ended, and Cancelled phases. ```rust pub enum TouchPhase { Started, Moved, Ended, Cancelled, } ``` -------------------------------- ### Get Graphics Backend Information Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves information about the graphics backend and its capabilities, including platform identification and feature support flags. ```rust fn info(&self) -> ContextInfo ``` -------------------------------- ### Get Dropped File Count Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the number of files that have been dropped onto the window. This function should be called within a `files_dropped_event()` handler. ```rust pub fn dropped_file_count() -> usize ``` -------------------------------- ### Get Apple View Object Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the Objective-C view object on Apple platforms. This is intended for advanced graphics integration with native Apple APIs. ```rust #[cfg(target_vendor = "apple")] pub fn apple_view() -> crate::native::apple::frameworks::ObjcId ``` -------------------------------- ### window::dpi_scale() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Gets the DPI scaling factor, which indicates the ratio between window pixels and framebuffer pixels. Essential for adapting graphics to different display densities. ```APIDOC ## window::dpi_scale() ### Description Get the DPI scaling factor. This is the scaling ratio from window pixels to framebuffer pixels. Typically `1.0` on standard displays and `2.0+` on high-DPI displays. ### Method `dpi_scale() -> f32` ### Endpoint N/A (Function Call) ### Parameters None ### Request Example ```rust let scale = window::dpi_scale(); println!("DPI Scale: {}", scale); ``` ### Response #### Success Response - `f32`: The DPI scaling factor. ``` -------------------------------- ### Create New Rendering Backend Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Creates a platform-appropriate graphics context. This function is automatically called by the framework but can be used for manual context creation. It returns a Metal context on Apple platforms if configured, otherwise OpenGL. ```rust pub fn new_rendering_backend() -> Box ``` -------------------------------- ### Desktop Game Configuration Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Configure miniquad for a desktop game with specific window dimensions, title, and anti-aliasing settings. ```rust Conf { window_title: "My Game".to_string(), window_width: 1920, window_height: 1080, sample_count: 4, platform: Platform { swap_interval: Some(1), ..Default::default() }, ..Default::default() } ``` -------------------------------- ### Retry File Loading with Fallback Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/errors.md Demonstrates how to handle potential errors when loading a file by providing a fallback option. If the primary file fails to load, it attempts to load a secondary fallback file. ```rust miniquad::fs::load_file("assets/texture.png", |response| { match response { Ok(bytes) => { // Process bytes } Err(_) => { // Fallback: load alternative texture miniquad::fs::load_file("assets/texture_fallback.png", |response| { match response { Ok(bytes) => { /* use fallback */ } Err(e) => { eprintln!("Both primary and fallback failed: {}", e); // Use embedded placeholder texture } } }); } } }); ``` -------------------------------- ### window::clipboard_set() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Writes the provided string data to the operating system's clipboard. ```APIDOC ## window::clipboard_set() ### Description Writes to the OS clipboard. ### Parameters #### Request Body - `data` (string) - Required - Text to copy to clipboard ### Returns None ``` -------------------------------- ### Get all color attachment textures from a render pass Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves a slice of all color attachment textures associated with a render pass. Returns an empty slice for depth-only passes. ```rust fn render_pass_color_attachments(&self, render_pass: RenderPass) -> &[TextureId] ``` -------------------------------- ### Get the color attachment texture from a render pass Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves the primary color attachment texture from a render pass. Panics if the pass is depth-only or has multiple color attachments. ```rust fn render_pass_texture(&self, render_pass: RenderPass) -> TextureId ``` -------------------------------- ### 1080p Game with MSAA 4x Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md Configure a game window to 1920x1080 resolution with 4x Multi-Sample Anti-Aliasing. ```rust Conf { window_title: "My Game".to_string(), window_width: 1920, window_height: 1080, sample_count: 4, ..Default::default() } ``` -------------------------------- ### Get Dropped File Path (Desktop) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the filesystem path of a dropped file. This function is available on desktop platforms. Use the `index` parameter to specify which file to retrieve. ```rust pub fn dropped_file_path(index: usize) -> Option ``` -------------------------------- ### Default Platform Configuration Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Provides the default implementation for the Platform struct, setting up sensible defaults for cross-platform compatibility. This is useful for quick initialization when specific configurations are not required. ```rust impl Default for Platform { fn default() -> Platform { Platform { linux_x11_gl: LinuxX11Gl::default(), linux_backend: LinuxBackend::default(), apple_gfx_api: AppleGfxApi::default(), webgl_version: WebGLVersion::default(), blocking_event_loop: false, sleep_interval_ms: None, swap_interval: None, framebuffer_alpha: false, wayland_decorations: WaylandDecorations::default(), linux_wm_class: "miniquad-application", android_panic_hook: true, } } } ``` -------------------------------- ### Get Dropped File Bytes (WASM) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the raw byte data of a dropped file. This function is specific to WebAssembly targets. Use the `index` parameter to specify which file to retrieve. ```rust pub fn dropped_file_bytes(index: usize) -> Option> ``` -------------------------------- ### File System Operations Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Methods for asynchronous file loading. ```APIDOC ## File System ### Description Provides asynchronous file loading capabilities across different platforms. ### Methods - `fs::load_file(path, callback)`: Asynchronously loads a file from the specified path and calls the callback with the file content or an error. ### Error Type - `fs::Error`: Represents errors that can occur during file system operations. ``` -------------------------------- ### Graceful Degradation with Placeholder Texture Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/errors.md Illustrates a strategy for handling asset loading failures by initializing with a placeholder and then attempting to load the actual asset. This pattern ensures the application remains functional even if assets are missing. ```rust struct Game { texture: TextureId, texture_loaded: bool, } impl Game { fn new() -> Self { let game = Game { texture: ctx.new_texture_from_rgba8(1, 1, &[255, 255, 255, 255]), // white placeholder texture_loaded: false, }; // Try to load actual texture miniquad::fs::load_file("textures/hero.png", |response| { // Callback can't access self, so this requires interior mutability or event signaling }); game } } ``` -------------------------------- ### Get Native GPU Texture Handle Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-backend.md Retrieves the native GPU handle (e.g., `GLuint` for OpenGL) for interoperation with native APIs. This function is unsafe and requires the caller to ensure proper synchronization. ```rust unsafe fn texture_raw_id(&self, texture: TextureId) -> RawId ``` -------------------------------- ### Low-Power App with Blocking Event Loop Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md Configure an application for low power consumption using a blocking event loop that wakes up periodically. ```rust Conf { window_title: "Low Power".to_string(), platform: Platform { blocking_event_loop: true, sleep_interval_ms: Some(100), // Wake every 100 ms ..Default::default() }, ..Default::default() } ``` -------------------------------- ### Android App Configuration (Framebuffer Alpha, Panic Hook, Periodic Wakeup) Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/conf-types.md Configures an Android application with framebuffer alpha enabled, a panic hook for debugging, and a periodic wakeup for a maximum of 20 FPS when idle. ```rust let conf = Conf { window_title: "Mobile App".to_string(), platform: Platform { framebuffer_alpha: true, blocking_event_loop: true, sleep_interval_ms: Some(50), // 20 FPS max when idle android_panic_hook: true, ..Default::default() }, ..Default::default() }; miniquad::start(conf, || Box::new(MyApp::new())); ``` -------------------------------- ### Create and Update Dynamic Vertex Buffer Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/QUICK_START.md Initialize a dynamic vertex buffer with initial data. Later, clear and extend the buffer with new vertex data for updates. ```rust let mut data = vec![/* initial vertices */]; let buffer = ctx.new_buffer(BufferType::VertexBuffer, BufferUsage::Dynamic, BufferSource::slice(&data)); // Later, update: data.clear(); data.extend_from_slice(&new_vertices); ctx.buffer_update(buffer, BufferSource::slice(&data)); ``` -------------------------------- ### window::apple_gfx_api() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Retrieves the graphics API currently in use on Apple platforms. ```APIDOC ## window::apple_gfx_api() ### Description Get the graphics API in use on Apple platforms. ### Returns - `crate::conf::AppleGfxApi`: Returns `AppleGfxApi::OpenGl` or `AppleGfxApi::Metal`. ``` -------------------------------- ### Graphics Backend Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the RenderingBackend trait, covering rendering pipelines, buffers, textures, and shader compilation. ```APIDOC ## RenderingBackend Trait ### Description Trait defining the interface for graphics rendering operations. It includes methods for managing buffers, textures, pipelines, and shader compilation. ### Methods (Partial List) - `create_buffer(desc: BufferDesc, data: &[u8]) -> Buffer` - `update_buffer(buffer: Buffer, data: &[u8])` - `delete_buffer(buffer: Buffer)` - `create_texture()` - `update_texture_image()` - `update_texture_params()` - `delete_texture()` - `create_pipeline_from_strs()` - `create_pipeline()` - `delete_pipeline()` - `begin_default_pass()` - `begin_pass()` - `end_pass()` - `draw()` ### Shader Compilation Flow - The trait supports complete shader compilation. ### Example: Triangle Rendering ```rust // Simplified example of rendering a triangle let vertices: Vec = vec![...]; let indices: Vec = vec![...]; let buffer = miniquad::graphics::Buffer::new_with_data(miniquad::graphics::BufferType::VertexBuffer, &vertices); let index_buffer = miniquad::graphics::Buffer::new_with_data(miniquad::graphics::BufferType::IndexBuffer, &indices); let pipeline = miniquad::graphics::Pipeline::new( miniquad::graphics::Shader::new_from_strs( "pass_through", "#version 100\nuniform mat4 mvp; attribute vec4 position; attribute vec2 texcoord; vary vec2 v_texcoord; void main() { gl_Position = mvp * position; v_texcoord = texcoord; }", "#version 100\nuniform sampler2D texture; vary vec2 v_texcoord; void main() { gl_FragColor = texture2D(texture, v_texcoord); }", )?, &[miniquad::graphics::VertexAttribute::new("position", miniquad::graphics::VertexFormat::Float4), miniquad::graphics::VertexAttribute::new("texcoord", miniquad::graphics::VertexFormat::Float2)], miniquad::graphics::BlendState::new(), miniquad::graphics::DepthState::new(), ); miniquad::graphics::draw(&pipeline, &[buffer, index_buffer], &[], miniquad::graphics::DrawParams::default()); ``` ``` -------------------------------- ### window::clipboard_get() Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/start.md Reads the text content from the operating system's clipboard. ```APIDOC ## window::clipboard_get() ### Description Reads the OS clipboard. ### Returns - `Option`: The clipboard text, or `None` if empty or unavailable. ``` -------------------------------- ### Android App Configuration Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/configuration.md Basic configuration for an Android application, enabling fullscreen, high DPI, and a blocking event loop with a panic hook. ```rust Conf { window_title: "Mobile".to_string(), // window_width/height ignored on Android high_dpi: true, fullscreen: true, sample_count: 4, window_resizable: false, platform: Platform { blocking_event_loop: true, sleep_interval_ms: Some(50), framebuffer_alpha: false, android_panic_hook: true, ..Default::default() }, ..Default::default() } ``` -------------------------------- ### BufferSource Methods Source: https://github.com/not-fl3/miniquad/blob/master/_autodocs/api-reference/graphics-types.md Provides methods for creating BufferSource instances from slices or specifying empty buffers. ```rust impl<'a> BufferSource<'a> { pub fn empty(size: usize) -> BufferSource<'a> pub fn slice(data: &'a [T]) -> BufferSource<'a> pub unsafe fn pointer(ptr: *const u8, size: usize, element_size: usize) -> BufferSource<'a> } ```