### Start Demo Server Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-guide/how-to-run.md Starts the demo server after the library has been built. This allows you to view and interact with the web demo. ```bash just web-demo start ``` -------------------------------- ### Fetching Tiles Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/IoAndSources.md Example demonstrating how to use the SourceClient to fetch tile data asynchronously. ```APIDOC ### Fetching Tiles ```rust use maplibre::io::source_client::SourceClient; use maplibre::coords::WorldTileCoords; use maplibre::io::source_type::SourceType; let coords = WorldTileCoords { x: 10, y: 20, z: ZoomLevel::new(4) }; let source_type = SourceType::VectorTile("https://example.com/{z}/{x}/{y}.pbf"); let tile_data = source_client.fetch(&coords, &source_type).await?; ``` ``` -------------------------------- ### KernelBuilder::new Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Kernel.md Demonstrates how to create a new instance of KernelBuilder. ```rust let builder = KernelBuilder::::new(); ``` -------------------------------- ### KernelBuilder::build Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Kernel.md Demonstrates the complete process of building a Kernel instance by chaining configuration methods and finally calling `build()`. ```rust let kernel = KernelBuilder::new() .with_map_window_config(window_config) .with_scheduler(scheduler) .with_apc(apc) .with_http_client(http_client) .build(); ``` -------------------------------- ### KernelBuilder::with_map_window_config Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Kernel.md Shows how to use the `with_map_window_config` method to set the window configuration during the builder process. ```rust let builder = KernelBuilder::new() .with_map_window_config(window_config); ``` -------------------------------- ### Build Script for Parallel Raytracing Example Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/appendix/link-collection.md This build script is used for the wasm-bindgen raytracing example, demonstrating how to build for shared memory. ```bash emcc -O3 -s USE_PTHREADS=1 -s MAIN_MODULE=1 -s SIDE_MODULE=1 -s WASM_BIGINT -o raytrace.js raytrace.cpp ``` -------------------------------- ### Platform Feature Selection Example (Cargo.toml) Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Illustrates how to select platform-specific implementations using Cargo features in a Cargo.toml file. ```toml [features] # Web platform web-webgl = ["wgpu/webgl"] # Desktop with Winit default = ["vector"] # Mobile/native features embed-static-tiles = ["maplibre-build-tools/sqlite"] ``` -------------------------------- ### Schedule System Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Illustrates adding systems to specific stages within a render schedule and running the schedule. Assumes Schedule and RenderStageLabel are available. ```rust schedule.add_system_to_stage(RenderStageLabel::Extract, system); schedule.add_system_to_stage(RenderStageLabel::Prepare, system); schedule.run(&mut context)?; ``` -------------------------------- ### Initialize Renderer with Default Settings Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Creates a new RendererBuilder instance using default configurations. This is the starting point for most rendering setups. ```rust let renderer_builder = RendererBuilder::new(); // Uses defaults let wgpu_settings = WgpuSettings::default(); // Platform-specific let renderer_settings = RendererSettings::default(); // MSAA=4 ``` -------------------------------- ### Clone the maplibre-rs repository Source: https://github.com/maplibre/maplibre-rs/blob/main/README.md Clone the project repository to get started with the source code. ```bash git clone https://github.com/maplibre/maplibre-rs.git ``` -------------------------------- ### Registering Built-in and Custom Plugins Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Plugin.md Example of how to create a vector of plugins, including the `VectorPlugin` and potentially custom plugins, for map initialization. ```rust use maplibre::plugin::Plugin; use maplibre::vector::VectorPlugin; use maplibre::vector::transferables::DefaultVectorTransferables; let plugins: Vec>> = vec![ Box::new(VectorPlugin::::default()), // Add more plugins... ]; let map = Map::new(style, kernel, renderer_builder, plugins)?; ``` -------------------------------- ### Fetch Tile Data Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Shows how to fetch tile data using the SourceClient. Requires coordinates, source type, and an async context. ```rust let tile_data = source_client.fetch(&coords, &source_type).await?; ``` -------------------------------- ### Fetching Tiles using SourceClient Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/IoAndSources.md Illustrates how to fetch tile data using the SourceClient. This example shows the necessary imports and how to specify coordinates and source type for the tile request. ```rust use maplibre::io::source_client::SourceClient; use maplibre::coords::WorldTileCoords; use maplibre::io::source_type::SourceType; let coords = WorldTileCoords { x: 10, y: 20, z: ZoomLevel::new(4) }; let source_type = SourceType::VectorTile("https://example.com/{z}/{x}/{y}.pbf"); let tile_data = source_client.fetch(&coords, &source_type).await?; ``` -------------------------------- ### Complete Map Initialization and Rendering Loop Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/MapContext.md Provides a full example of initializing a MapLibre RS map, setting up the renderer, and entering a rendering loop that handles window resizing and frame rendering. ```rust use maplibre::map::Map; use maplibre::style::Style; use maplibre::kernel::Kernel; use maplibre::render::builder::RendererBuilder; use maplibre::window::PhysicalSize; // Create map let style = Style::default(); let kernel = Kernel::new(/* ... */); let renderer_builder = RendererBuilder::new(); let plugins = vec![]; let mut map = Map::new(style, kernel, renderer_builder, plugins)?; // Initialize renderer map.initialize_renderer().await?; // Rendering loop let mut last_size = map.window().size(); loop { // Check for resize let current_size = map.window().size(); if current_size != last_size { let scale_factor = map.window().scale_factor(); let context = map.context_mut()?; context.resize(current_size, scale_factor); last_size = current_size; } // Run render frame map.run_schedule()?; // Handle events... // Update style, camera, etc. } ``` -------------------------------- ### Creating a Custom Environment Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Guides users through implementing the necessary traits to create a custom environment for maplibre-rs on a new platform. ```APIDOC ## Creating a Custom Environment To implement maplibre-rs for a new platform: 1. **Implement `MapWindowConfig`** — Provide window creation for the target platform 2. **Implement `Scheduler`** — Provide task scheduling (can use existing like Tokio) 3. **Implement `HttpClient`** — Provide HTTP fetching (can use reqwest, fetch API, etc.) 4. **Implement `AsyncProcedureCall`** — Provide APC for tile processing (can use SchedulerAsyncProcedureCall) 5. **Implement `OffscreenKernel`** — Provide kernel for worker threads 6. **Implement `Environment`** — Combine all above into Environment trait **Example Template**: ```rust use maplibre::environment::*; struct MyPlatformEnvironment; impl Environment for MyPlatformEnvironment { type MapWindowConfig = MyWindowConfig; type AsyncProcedureCall = SchedulerAsyncProcedureCall; type Scheduler = MyScheduler; type HttpClient = MyHttpClient; type OffscreenKernelEnvironment = MyOffscreenKernel; } impl MapWindowConfig for MyWindowConfig { type MapWindow = MyWindow; fn create(&self) -> Result { // Implementation... } } // Implement other traits... ``` ``` -------------------------------- ### Desktop Environment Implementation (Winit) Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Example implementation of the `Environment` trait for desktop platforms using the `winit` windowing library. This configuration utilizes Tokio for the async runtime and `reqwest` for HTTP requests, supporting full multi-threading. ```rust use maplibre::environment::Environment; use maplibre::window::MapWindowConfig; struct DesktopEnvironment; impl Environment for DesktopEnvironment { type MapWindowConfig = WinitWindowConfig; type AsyncProcedureCall = SchedulerAsyncProcedureCall<...>; type Scheduler = TokioScheduler; type HttpClient = ReqwestHttpClient; type OffscreenKernelEnvironment = DesktopOffscreenKernel; } ``` -------------------------------- ### Example package.json Scripts for WebPack Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-documents/library-packaging/web.md These scripts define common WebPack build commands for development, production, and specific configurations like WebGL. ```json { "scripts": { "webpack": "webpack --mode=development", "webpack-webgl": "npm run build -- --env webgl", "webpack-production": "webpack --mode=production", "webpack-webgl-production": "npm run production-build -- --env webgl" } } ``` -------------------------------- ### Rust Example: Working with Zoom and ZoomLevel Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Coordinates.md Demonstrates creating and converting between discrete (integer) and continuous (floating-point) zoom levels, as well as performing arithmetic operations. ```rust use maplibre::coords::{Zoom, ZoomLevel}; // Discrete zoom level (integer) let zoom_level = ZoomLevel::new(10); // Continuous zoom (floating point for smooth animation) let zoom = Zoom::new(10.5); // Convert between them let zoom_from_level = Zoom::from(zoom_level); // Arithmetic operations let zoom2 = Zoom::new(2.0); let diff = zoom - zoom2; ``` -------------------------------- ### Desktop Window Implementation (Winit) Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Provides a structural example of how the `maplibre-winit` crate implements the `MapWindowConfig` and `HeadedMapWindow` traits for desktop environments using the Winit library. ```rust // File: maplibre-winit/src/lib.rs pub struct WinitWindowConfig { ... } pub struct WinitWindow { ... } implement MapWindowConfig for WinitWindowConfig { type MapWindow = WinitWindow; } implement HeadedMapWindow for WinitWindow { // OS window integration } ``` -------------------------------- ### Example: Receiving and Extracting Tile Data Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/IoAndSources.md Demonstrates how to receive messages filtered by a specific tag (e.g., `TILE_TAG`) and then extract the typed `TileData` from them. ```rust let messages = apc.receive(|msg| msg.has_tag(&TILE_TAG)); for msg in messages { let data = msg.into_transferable::(); } ``` -------------------------------- ### Create a Headed Window Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Demonstrates the process of creating a headed map window with a custom configuration. It shows how to get the window size, handle, request redraws, and retrieve the scale factor and ID. ```rust use maplibre::window::{MapWindowConfig, HeadedMapWindow, PhysicalSize}; let config = MyWindowConfig { width: 1024, height: 768, }; let window = config.create()?; // Check size let size = window.size(); println!("Window: {}x{}", size.width(), size.height()); // Get OS handle for GPU surface let handle = window.handle(); // Request redraw window.request_redraw(); // Get DPI scale let scale = window.scale_factor(); // Get window ID let id = window.id(); ``` -------------------------------- ### Configure WGPU Settings Based on Operating System Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Adjusts WGPU settings, such as power preference, based on the target operating system. This example provides specific configurations for Android, WASM, and other desktop platforms. ```rust let wgpu_settings = match std::env::consts::OS { "android" => { // Reduced limits for mobile WgpuSettings { power_preference: PowerPreference::LowPower, ..Default::default() } } "wasm" => { // WebGL defaults WgpuSettings::default() } _ => { // Desktop: use high performance WgpuSettings { power_preference: PowerPreference::HighPerformance, ..Default::default() } } }; ``` -------------------------------- ### Async Procedure Call Example Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Demonstrates making an asynchronous procedure call and processing results. Ensure the AsyncProcedureCall trait and TileData are in scope. ```rust apc.call(input, procedure)?; let messages = apc.receive(|msg| msg.has_tag(&TILE_TAG)); for msg in messages { let data = msg.into_transferable::(); } ``` -------------------------------- ### Example: Convert Physical to Logical Size Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Demonstrates converting a `PhysicalSize` to a `LogicalSize` using a scale factor of 2.0. The resulting logical dimensions are half of the physical dimensions. ```rust let physical = PhysicalSize::new(1920, 1080).unwrap(); let scale = 2.0; // 200% DPI let logical = physical.to_logical(scale); // logical dimensions: 960x540 ``` -------------------------------- ### Create and Interact with a Map Window Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Illustrates the basic usage of the MapWindow trait for creating and managing a map window. It shows how to get window size and request a redraw. ```rust let window = map_window_config.create()?; let size = window.size(); window.request_redraw(); ``` -------------------------------- ### Initialize Renderer: initialize_renderer Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Asynchronously initializes the rendering pipeline. Must be called after Map creation and before run_schedule. Handles GPU device and render graph setup. ```rust pub async fn initialize_renderer(&mut self) -> Result<(), MapError> ``` ```rust let mut map = Map::new(style, kernel, renderer_builder, plugins)?; map.initialize_renderer().await?; ``` -------------------------------- ### Raster Tile Source Configuration Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Configure a raster tile source for MapLibre. Specify tile URLs, zoom levels, and use default settings for other parameters. The example uses PNG format. ```rust Source::Raster(VectorSource { tiles: Some(vec![ "https://example.com/tiles/{z}/{x}/{y}.png".to_string(), ]), minzoom: Some(0), maxzoom: Some(18), ..Default::default() }) ``` -------------------------------- ### Using Default Environment (Desktop) Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Demonstrates how to use the default `WinitEnvironment` for desktop applications, initializing the kernel with common configurations. ```APIDOC ## Using Default Environment (Desktop) ```rust use maplibre_winit::WinitEnvironment; use maplibre::kernel::KernelBuilder; use maplibre::map::Map; // WinitEnvironment is a concrete Environment implementation let kernel = KernelBuilder::::new() .with_map_window_config(window_config) .with_scheduler(tokio_scheduler) .with_apc(apc) .with_http_client(http_client) .build(); let map = Map::new(style, kernel, renderer_builder, plugins)?; ``` ``` -------------------------------- ### Web Environment Implementation (WASM) Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Example implementation of the `Environment` trait for web platforms targeting WebAssembly. It uses a WebGL/WebGPU canvas for windowing, Web Workers for asynchronous operations, and the Fetch API for HTTP requests, relying on message passing instead of true multi-threading. ```rust struct WebEnvironment; impl Environment for WebEnvironment { type MapWindowConfig = WebGlWindowConfig; type AsyncProcedureCall = PassingAsyncProcedureCall; type Scheduler = WebWorkerScheduler; type HttpClient = FetchApiClient; type OffscreenKernelEnvironment = WebOffscreenKernel; } ``` -------------------------------- ### Rust Example: Geographic Coordinates Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Coordinates.md Shows how to create geographic positions using the LatLon struct, including specific locations and the default origin (prime meridian, equator). ```rust use maplibre::coords::LatLon; // Create a geographic position let brussels = LatLon::new(50.85045, 4.34878); let new_york = LatLon::new(40.7128, -74.0060); // Default position (prime meridian, equator) let origin = LatLon::default(); ``` -------------------------------- ### Example WebPack Configuration with wasm-pack-plugin Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-documents/library-packaging/web.md This configuration sets up WebPack to bundle a Rust project compiled to WebAssembly using the wasm-pack-plugin. It includes settings for entry points, output, module rules, and environment variable definitions. ```javascript const path = require("path"); const webpack = require("webpack"); const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin"); let dist = path.join(__dirname, 'dist/maplibre-rs'); module.exports = (env) => ({ mode: "development", entry: "./src/index.ts", experiments: { syncWebAssembly: true, }, performance: { maxEntrypointSize: 400000, maxAssetSize: 400000000, }, output: { path: dist, filename: "maplibre-rs.js", library: { name: 'maplibre_rs', type: 'umd', }, }, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, use: [ { loader: 'ts-loader', options: {} } ] }, ], }, resolve: { extensions: ['.ts', '.js'], }, plugins: [ new webpack.DefinePlugin({ 'process.env.WEBGL': !!env.webgl }), new WasmPackPlugin({ crateDirectory: path.resolve(__dirname, '../'), // Check https://rustwasm.github.io/wasm-pack/book/commands/build.html for // the available set of arguments. // // Optional space delimited arguments to appear before the wasm-pack // command. Default arguments are `--verbose`. //args: '--log-level warn', // Default arguments are `--typescript --target browser --mode normal`. extraArgs: ` --target web -- . -Z build-std=std,panic_abort ${env.webgl ? '--features web-webgl' : ''} ${env.tracing ? '--features trace' : ''}`, // Optional array of absolute paths to directories, changes to which // will trigger the build. // watchDirectories: [ // path.resolve(__dirname, "another-crate/src") // ], // The same as the `--out-dir` option for `wasm-pack` outDir: path.resolve(__dirname, 'src/wasm-pack'), // The same as the `--out-name` option for `wasm-pack` // outName: "index", // If defined, `forceWatch` will force activate/deactivate watch mode for // `.rs` files. // // The default (not set) aligns watch mode for `.rs` files to Webpack's // watch mode. // forceWatch: true, // If defined, `forceMode` will force the compilation mode for `wasm-pack` // // Possible values are `development` and `production`. // // the mode `development` makes `wasm-pack` build in `debug` mode. // the mode `production` makes `wasm-pack` build in `release` mode. // forceMode: "production", // Controls plugin output verbosity, either 'info' or 'error'. // Defaults to 'info'. // pluginLogLevel: 'info' }), ] }); ``` -------------------------------- ### ESBuild IIFE Module Translation Example Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-documents/library-packaging/web.md Illustrates how ESBuild translates a WASM module reference in an IIFE context. This is useful for understanding how ESBuild handles asset resolution with `import.meta.url`. ```javascript var __currentScriptUrl__ = document.currentScript && document.currentScript.src || document.baseURI; new URL("./assets/index_bg.wasm?emit=file", __currentScriptUrl__); ``` -------------------------------- ### Setting Up ViewState Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Illustrates how to initialize and configure a ViewState, including setting the window size, center coordinates, zoom level, pitch, and field of view. Also shows how to handle window resizing and retrieve the visible region. ```rust use maplibre::render::view_state::{ViewState, ViewStatePadding}; use maplibre::coords::{Zoom, WorldCoords, LatLon, ZoomLevel}; use maplibre::window::PhysicalSize; use cgmath::{Deg, Rad}; let size = PhysicalSize::new(1920, 1080).unwrap(); let center = WorldCoords::from_lat_lon( LatLon::new(40.7128, -74.0060), // New York Zoom::new(12.0) ); let mut view_state = ViewState::new( size, center, Zoom::new(12.0), Deg(30.0), // 30 degree pitch Rad(1.0) // ~57 degree FOV ); // Handle window resize let new_size = PhysicalSize::new(1600, 900).unwrap(); view_state.resize(new_size.to_logical(1.0)); // Get visible tiles let visible_region = view_state.create_view_region( ZoomLevel::new(12), ViewStatePadding::Loose ); ``` -------------------------------- ### Using Default Desktop Environment Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Demonstrates how to initialize a MapLibre kernel using the default WinitEnvironment for desktop platforms, configuring windowing, scheduling, APC, and HTTP client. ```rust use maplibre_winit::WinitEnvironment; use maplibre::kernel::KernelBuilder; use maplibre::map::Map; // WinitEnvironment is a concrete Environment implementation let kernel = KernelBuilder::::new() .with_map_window_config(window_config) .with_scheduler(tokio_scheduler) .with_apc(apc) .with_http_client(http_client) .build(); let map = Map::new(style, kernel, renderer_builder, plugins)?; ``` -------------------------------- ### Get Window Size Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Retrieves the current dimensions of the window in physical pixels. Use this to get the window's width and height. ```rust let size = window.size(); println!("Window: {}x{}", size.width(), size.height()); ``` -------------------------------- ### Get Edge Insets from ViewState Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Retrieves the current padding applied to the viewport edges. ```rust pub fn edge_insets(&self) -> &EdgeInsets ``` -------------------------------- ### Get Map Window Reference: window Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Returns a reference to the map's window for rendering. ```rust pub fn window(&self) -> &::MapWindow ``` -------------------------------- ### Creating and Configuring a Renderer Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Demonstrates how to create and configure a renderer using RendererBuilder, setting WGPU and renderer-specific settings like MSAA and presentation mode. ```rust use maplibre::render::{ builder::RendererBuilder, settings::{RendererSettings, WgpuSettings, Msaa}, }; use wgpu::PresentMode; let wgpu_settings = WgpuSettings { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; let renderer_settings = RendererSettings { msaa: Msaa { samples: 4 }, present_mode: PresentMode::AutoVsync, ..Default::default() }; let builder = RendererBuilder::new() .with_wgpu_settings(wgpu_settings) .with_renderer_settings(renderer_settings); ``` -------------------------------- ### Build and run maplibre-demo on desktop Source: https://github.com/maplibre/maplibre-rs/blob/main/README.md Build and run the maplibre-demo application on a desktop environment. ```bash cargo run -p maplibre-demo ``` -------------------------------- ### Get Logical Width Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Returns the width of the logical window size. This value represents device-independent units. ```rust pub fn width(&self) -> u32 ``` -------------------------------- ### Getting Mutable Map Context Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/MapContext.md Illustrates how to obtain a mutable reference to the `MapContext` for modifying map state. ```rust let context_mut = map.context_mut()?; ``` -------------------------------- ### Get Window ID Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Retrieves a unique identifier for the window. This is useful for tracking which window specific events belong to. ```rust let window_id = window.id(); // Store and use to identify events for this window ``` -------------------------------- ### Get Window Handle Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Retrieves the native OS window handle. This is required for creating GPU surfaces with wgpu. ```rust let handle = window.handle(); // Use with wgpu::Instance::create_surface() ``` -------------------------------- ### Programmatic WGPU Backend Selection Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Demonstrates how to programmatically select a specific WGPU backend, in this case, Vulkan. ```rust use wgpu::Backends; let wgpu_settings = WgpuSettings { backends: Some(Backends::VULKAN), ..Default::default() }; ``` -------------------------------- ### MapWindow Trait Definition Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Represents a window or surface for rendering the map. It provides a method to get the current window dimensions. ```rust pub trait MapWindow { fn size(&self) -> PhysicalSize; } ``` -------------------------------- ### Get Kernel Reference Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Retrieves a reference to the shared kernel, which holds platform-specific implementations. This is useful for accessing underlying functionalities. ```rust pub fn kernel(&self) -> &Rc> ``` -------------------------------- ### Getting Read-Only Map Context Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/MapContext.md Shows the standard way to obtain a read-only reference to the `MapContext` via the `map` object. ```rust let context = map.context()?; ``` -------------------------------- ### WgpuSettings Structure Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Configuration options for initializing the WebGPU backend. Allows customization of device selection, features, and limits. ```rust #[derive(Clone)] pub struct WgpuSettings { pub device_label: Option>, pub backends: Option, pub power_preference: PowerPreference, pub features: Features, pub disabled_features: Option, pub limits: Limits, pub constrained_limits: Option, pub record_trace: bool, } ``` -------------------------------- ### Initialize Map with Plugins Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Demonstrates how to initialize a Map instance with a vector of plugins. Ensure all necessary dependencies like schedule, kernel, render, and tcs are available. ```rust let plugins: Vec>> = vec![ Box::new(VectorPlugin::::default()), ]; let map = Map::new(style, kernel, renderer_builder, plugins)?; ``` -------------------------------- ### Initialize Renderer Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Shows the asynchronous initialization of the main Renderer. Requires window, wgpu_settings, and renderer_settings as input. ```rust let renderer = Renderer::initialize( window, wgpu_settings, renderer_settings ).await?; ``` -------------------------------- ### Generate and open API documentation Source: https://github.com/maplibre/maplibre-rs/blob/main/README.md Generate the API documentation for the crate and open it in a web browser. This includes documentation for all dependencies. ```bash cargo doc --open ``` -------------------------------- ### Get Message Tag Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/IoAndSources.md Retrieves the type tag associated with a `Message`. The tag serves as an identifier for the data contained within the message. ```rust pub fn tag(&self) -> &'static dyn MessageTag ``` -------------------------------- ### Initialize and Run Map Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Demonstrates the basic lifecycle of a Map instance, including initialization and entering the main run loop. Ensure all necessary dependencies like style, kernel, renderer builder, and plugins are provided. ```rust let mut map = Map::new(style, kernel, renderer_builder, plugins)?; map.initialize_renderer().await?; loop { map.run_schedule()? } ``` -------------------------------- ### MapWindow Trait Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Represents a window or surface where the map is rendered. It provides methods to get window dimensions and manage rendering requests. ```APIDOC ## MapWindow Trait Represents a window or surface to render the map to. ### Methods | Method | Returns | Purpose | |---|---|---| | `size` | `PhysicalSize` | Get current window dimensions | ``` -------------------------------- ### Get Physical Height as NonZeroU32 Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Returns the height of the physical window size as a `NonZeroU32`. This ensures the height is always greater than zero. ```rust pub fn height_non_zero(&self) -> NonZeroU32 ``` -------------------------------- ### Get Physical Height Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Returns the height of the physical window size in pixels. The returned value is a `u32` and is guaranteed to be greater than zero. ```rust pub fn height(&self) -> u32 ``` -------------------------------- ### Build Kernel with Services Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/MODULE_OVERVIEW.md Illustrates the fluent builder pattern for constructing a Kernel instance. This involves configuring essential services like the scheduler, async procedure call system, and HTTP client, which are crucial for platform abstraction and I/O operations. ```rust let kernel = KernelBuilder::new() .with_scheduler(scheduler) .with_apc(apc) .with_http_client(http_client) .with_map_window_config(window_config) .build(); ``` -------------------------------- ### Get Physical Width as NonZeroU32 Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Returns the width of the physical window size as a `NonZeroU32`. This ensures the width is always greater than zero. ```rust pub fn width_non_zero(&self) -> NonZeroU32 ``` -------------------------------- ### Get Mutable Map Window Reference: window_mut Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Returns a mutable reference to the map's window, allowing for configuration changes. ```rust pub fn window_mut(&mut self) -> &mut ::MapWindow ``` -------------------------------- ### Registering System in Prepare Stage Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Plugin.md Adds a system to the `Prepare` stage of the render schedule. This stage is for preparing GPU resources based on extracted data. ```rust schedule.add_system_to_stage( RenderStageLabel::Prepare, SystemContainer::new(my_prepare_system), ); ``` -------------------------------- ### Creating a Custom Plugin Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Plugin.md Demonstrates how to define and implement a custom plugin by creating a struct and implementing the `Plugin` trait. This includes adding systems, render graph nodes, and resources. ```rust use maplibre::plugin::Plugin; use std::rc::Rc; struct MyCustomPlugin; impl Plugin for MyCustomPlugin { fn build( &self, schedule: &mut Schedule, kernel: Rc>, world: &mut World, graph: &mut RenderGraph, ) { // Add systems to schedule schedule.add_system_to_stage( RenderStageLabel::Extract, SystemContainer::new(my_extract_system), ); // Add render graph nodes graph.add_node("my_pass", MyRenderPass::new()); // Insert resources world.resources.insert(MyPluginData::default()); } } let plugins: Vec>> = vec![ Box::new(MyCustomPlugin), ]; ``` -------------------------------- ### Initialize RendererBuilder with Custom Settings Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Configure the GPU renderer by providing custom `RendererSettings` and `WgpuSettings` to the `RendererBuilder`. ```rust let renderer_settings = RendererSettings { msaa: Msaa { samples: 4 }, texture_format: None, // Auto-detect depth_texture_format: TextureFormat::Depth24PlusStencil8, present_mode: PresentMode::AutoVsync, }; let wgpu_settings = WgpuSettings { backends: Some(Backends::all()), power_preference: PowerPreference::HighPerformance, record_trace: false, ..Default::default() }; let builder = RendererBuilder::new() .with_renderer_settings(renderer_settings) .with_wgpu_settings(wgpu_settings); ``` -------------------------------- ### MapWindow Trait Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Represents a generic window or rendering surface, whether headed or headless. It provides a method to get the current dimensions of the window. ```APIDOC ## MapWindow Trait Represents a window or rendering surface (headed or headless). ### Methods #### `size` ```rust fn size(&self) -> PhysicalSize ``` Returns the current window dimensions in physical pixels. **Returns**: `PhysicalSize` with width and height **Example**: ```rust let size = window.size(); println!("Window: {}x{}", size.width(), size.height()); ``` ``` -------------------------------- ### KernelBuilder::new Method Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Kernel.md Initializes a new, empty KernelBuilder. All configuration options are initially set to None. ```rust pub fn new() -> Self ``` -------------------------------- ### Create New ViewState Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Initializes a new ViewState with specific camera parameters. Use this to set up the initial view of the map. ```rust pub fn new>, P: Into>>( window_size: PhysicalSize, position: WorldCoords, zoom: Zoom, pitch: P, fovy: F, ) -> Self ``` ```rust use maplibre::coords::{Zoom, WorldCoords, LatLon}; use maplibre::render::view_state::ViewState; use maplibre::window::PhysicalSize; use cgmath::{Deg, Rad}; let size = PhysicalSize::new(1024, 768).unwrap(); let position = WorldCoords::from_lat_lon( LatLon::new(50.85045, 4.34878), Zoom::new(13.0) ); let view = ViewState::new( size, position, Zoom::new(13.0), Deg(0.0), Rad(0.6435011087932844) // ~45 degrees ); ``` -------------------------------- ### Get Scale Factor Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Retrieves the DPI scale factor of the display, which accounts for high-DPI screens. Use this to convert between physical and logical coordinates. ```rust let scale = window.scale_factor(); let logical_width = physical_width as f64 / scale; ``` -------------------------------- ### Distinguishing Recoverable Errors Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/errors.md Differentiates between recoverable and unrecoverable errors. For example, 'RendererNotReady' might be recoverable by initialization, while 'DeviceInit' indicates an unrecoverable GPU issue. ```rust match error { MapError::RendererNotReady => { // Recoverable: initialize and retry } MapError::DeviceInit(_) => { // Unrecoverable: GPU not available std::process::exit(1); } _ => { // Handle other errors } } ``` -------------------------------- ### ViewState::new Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Creates a new view state with initial camera configuration. This is the primary method for setting up the initial camera perspective for rendering. ```APIDOC ## ViewState::new ### Description Creates a new view state with initial camera configuration. ### Method `new` ### Signature `pub fn new>, P: Into>>(window_size: PhysicalSize, position: WorldCoords, zoom: Zoom, pitch: P, fovy: F) -> Self` ### Parameters #### Path Parameters - **window_size** (`PhysicalSize`) - Required - Viewport dimensions - **position** (`WorldCoords`) - Required - Camera position in world coordinates - **zoom** (`Zoom`) - Required - Camera zoom level - **pitch** (`P: Into>`) - Required - Camera pitch angle (0 = straight down, 60 = tilted) - **fovy** (`F: Into>`) - Required - Vertical field of view in radians ### Returns `Self` (a new ViewState instance) ### Example ```rust use maplibre::coords::{Zoom, WorldCoords, LatLon}; use maplibre::render::view_state::ViewState; use maplibre::window::PhysicalSize; use cgmath::{Deg, Rad}; let size = PhysicalSize::new(1024, 768).unwrap(); let position = WorldCoords::from_lat_lon( LatLon::new(50.85045, 4.34878), Zoom::new(13.0) ); let view = ViewState::new( size, position, Zoom::new(13.0), Deg(0.0), Rad(0.6435011087932844) // ~45 degrees ); ``` ``` -------------------------------- ### Map Constructor: new Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Creates a new Map instance. Requires style, kernel, renderer builder, and plugins. Ensure window creation does not fail. ```rust pub fn new( style: Style, kernel: Kernel, renderer_builder: RendererBuilder, plugins: Vec>>, ) -> Result where <::MapWindowConfig as MapWindowConfig>::MapWindow: HeadedMapWindow ``` ```rust let style = Style::default(); let kernel = Kernel::default(); let renderer_builder = RendererBuilder::new(); let plugins = vec![]; let map = Map::new(style, kernel, renderer_builder, plugins)?; ``` -------------------------------- ### Renderer::initialize Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Initializes the renderer for a headed window, setting up the GPU device, surface, and render graph. This is an asynchronous operation that may fail if GPU resources cannot be acquired. ```APIDOC ## Renderer::initialize ### Description Initializes the renderer for a headed window (with display). Creates GPU device, surface, and render graph. ### Method `async fn initialize(window: &MWC::MapWindow, wgpu_settings: WgpuSettings, settings: RendererSettings) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **window** (`&MWC::MapWindow`) - Required - Target window for rendering - **wgpu_settings** (`WgpuSettings`) - Required - WebGPU backend configuration - **settings** (`RendererSettings`) - Required - Renderer settings (MSAA, format) ### Returns `Result` ### Throws - `RenderError::RequestAdaptor` — if no suitable GPU adapter found - `RenderError::RequestDevice` — if device creation fails - `RenderError::CreateSurfaceError` — if surface creation fails ### Request Example None ### Response #### Success Response `Renderer` instance on success. #### Response Example None ``` -------------------------------- ### Watch for Changes (WebGL) Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-guide/how-to-run.md Builds the library with WebGL support and watches for file changes, recompiling automatically. Supports the same flags as `web-lib build`. ```bash just web-lib watch --webgl ``` -------------------------------- ### Run MapLibre RS with Vulkan Backend and Debug Logging Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md This command executes a release build of MapLibre RS, forcing the Vulkan GPU backend and setting the logging level to debug. Ensure WGPU_BACKEND and RUST_LOG environment variables are set before running. ```bash WGPU_BACKEND=vulkan RUST_LOG=debug cargo run --release ``` -------------------------------- ### MapLibre RS Default Desktop Configuration Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Use this configuration for standard desktop builds. It includes the base MapLibre RS dependency. ```toml maplibre = "0.1.0" ``` -------------------------------- ### Modifying ViewState Edge Insets Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/MapContext.md Shows how to get mutable access to the map's context to modify the view state, specifically by setting edge insets for the camera. ```rust let context = map.context_mut()?; // Change camera pitch context.view_state.set_edge_insets(EdgeInsets { top: 100.0, bottom: 100.0, left: 0.0, right: 0.0, }); ``` -------------------------------- ### Convert Between Physical and Logical Window Sizes Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Window.md Illustrates the conversion between physical and logical window dimensions. It shows how to obtain both representations and use them for different purposes, such as UI layout (logical) and GPU resources (physical). ```rust let physical = window.size(); let scale = window.scale_factor(); let logical = physical.to_logical(scale); // Use logical for UI layout let logical_width = logical.width(); let logical_height = logical.height(); // Use physical for GPU resources let pixel_width = physical.width(); let pixel_height = physical.height(); ``` -------------------------------- ### WgpuSettings Struct Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/types.md Configuration options for the WebGPU backend. ```rust #[derive(Clone)] pub struct WgpuSettings { pub device_label: Option>, pub backends: Option, pub power_preference: wgpu::PowerPreference, pub features: wgpu::Features, pub disabled_features: Option, pub limits: wgpu::Limits, pub constrained_limits: Option, pub record_trace: bool, } ``` -------------------------------- ### Get Mutable Map Context: context_mut Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Provides mutable access to the map's rendering context for modifying style, view state, etc. Requires the renderer to be initialized. ```rust pub fn context_mut(&mut self) -> Result<&mut MapContext, MapError> ``` -------------------------------- ### KernelBuilder Initialization Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/configuration.md Initialize the `KernelBuilder` with essential components like window configuration, scheduler, async procedure call handler, and HTTP client. All specified components are required for building the kernel. ```rust use maplibre::kernel::KernelBuilder; let kernel = KernelBuilder::new() .with_map_window_config(window_config) .with_scheduler(scheduler) .with_apc(apc) .with_http_client(http_client) .build(); ``` -------------------------------- ### Get Read-Only Map Context: context Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Map.md Provides read-only access to the map's rendering context, including style, world, view state, and renderer. Requires the renderer to be initialized. ```rust pub fn context(&self) -> Result<&MapContext, MapError> ``` ```rust let context = map.context()?; let style = &context.style; ``` -------------------------------- ### Build WebGPU Library Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-guide/how-to-run.md Builds the MapLibre RS library with WebGPU support. Use this when your target browser supports recent WebGPU specifications. ```bash just web-lib build # WebGPU ``` -------------------------------- ### Providing Custom Http Client Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Shows how to provide a custom `HttpClient` implementation to the `Environment`, allowing for advanced network request handling. ```APIDOC ## Providing Custom Http Client ```rust use maplibre::io::source_client::HttpClient; #[derive(Clone)] struct CustomHttpClient; #[async_trait::async_trait] impl HttpClient for CustomHttpClient { async fn fetch(&self, url: &str) -> Result, SourceFetchError> { // Custom implementation with caching, custom headers, etc. todo!() } } impl Environment for MyEnvironment { type HttpClient = CustomHttpClient; // ... other types } ``` ``` -------------------------------- ### WgpuSettings Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/types.md Configuration options for the WebGPU backend, including device labels, backends, and features. ```APIDOC ## WgpuSettings ### Description Configuration options for the WebGPU backend, including device labels, backends, and features. ### Struct ```rust #[derive(Clone)] pub struct WgpuSettings { pub device_label: Option>, pub backends: Option, pub power_preference: wgpu::PowerPreference, pub features: wgpu::Features, pub disabled_features: Option, pub limits: wgpu::Limits, pub constrained_limits: Option, pub record_trace: bool, } ``` ``` -------------------------------- ### Create a Kernel with Components Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Kernel.md Instantiate a Kernel with all necessary components using KernelBuilder. This is useful when you need a fully configured kernel for your application. ```rust use maplibre::kernel::KernelBuilder; let kernel = KernelBuilder::new() .with_map_window_config(my_window_config) .with_scheduler(my_scheduler) .with_apc(my_apc) .with_http_client(my_http_client) .build(); // Use the kernel let scheduler = kernel.scheduler(); let apc = kernel.apc(); ``` -------------------------------- ### HeadedMapWindow Trait Definition Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Environment.md Extends MapWindow with platform-specific window handle and interaction capabilities. Requires associated types for window handles and provides methods for requesting redraws and getting scale factors. ```rust pub trait HeadedMapWindow: MapWindow { type WindowHandle: HasWindowHandle + HasDisplayHandle + Sync; fn handle(&self) -> &Self::WindowHandle; fn request_redraw(&self); fn scale_factor(&self) -> f64; fn id(&self) -> u64; } ``` -------------------------------- ### RenderResources::new Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/RendererAndViewState.md Creates a new RenderResources instance, initializing it with the provided presentation surface. This is used to set up the necessary textures and buffers for rendering. ```APIDOC ## RenderResources::new ### Description Creates render resources for a surface. ### Method `pub fn new(surface: Surface) -> Self` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **surface** (`Surface`) - Required - Target surface ### Returns `RenderResources` ### Throws None ### Request Example None ### Response #### Success Response `RenderResources` instance. #### Response Example None ``` -------------------------------- ### Catching Rendering Errors Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/errors.md Illustrates how to handle various RenderErrors, including specific cases like RequestAdaptor and RequestDevice, and using the should_exit method for unrecoverable errors. This example shows retrying with reduced features. ```rust use maplibre::render::error::RenderError; match renderer.initialize(...).await { Ok(renderer) => { /* use renderer */ } Err(RenderError::RequestAdaptor) => { eprintln!("No suitable GPU adapter found"); eprintln!("Check GPU drivers and WebGPU support"); return; } Err(RenderError::RequestDevice(e)) => { eprintln!("GPU device request failed: {}", e); // Try with reduced feature set let reduced_features = WgpuSettings { features: Features::empty(), ..Default::default() }; // Retry with reduced_features... } Err(e) if e.should_exit() => { eprintln!("Unrecoverable render error: {}", e); std::process::exit(1); } Err(e) => { eprintln!("Render error: {}", e); } } ``` -------------------------------- ### Create Fat Binary with lipo Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-documents/library-packaging/apple.md This command uses the 'lipo' tool to create a fat binary by merging multiple architecture-specific binaries. This is often a prerequisite for creating a unified xcframework when dealing with different architectures. ```bash lipo -create binA binB -output binfat ``` -------------------------------- ### Build WebGL Library Source: https://github.com/maplibre/maplibre-rs/blob/main/docs/src/development-guide/how-to-run.md Builds the MapLibre RS library with WebGL support. This is the fallback if WebGPU is not available. ```bash just web-lib build --webgl # WebGL ``` -------------------------------- ### Directory Structure Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/README.md Overview of the documentation structure for maplibre-rs. ```bash . ├── README.md ← You are here ├── INDEX.md ← Master index and quick reference ├── MODULE_OVERVIEW.md ← Architecture and module relationships ├── types.md ← Complete type reference (types only) ├── errors.md ← Error types and recovery strategies ├── configuration.md ← Configuration options and environment │ └── api-reference/ ← Detailed API documentation by type ├── Map.md ← Main Map type and entry point ├── MapContext.md ← Runtime state container ├── Kernel.md ← Dependency injection container ├── Environment.md ← Platform abstraction traits ├── Plugin.md ← Plugin system ├── Coordinates.md ← Coordinate types and operations ├── Style.md ← Map styling (layers, sources, paint) ├── RendererAndViewState.md ← GPU rendering and camera ├── Window.md ← Window/surface abstraction └── IoAndSources.md ← Async operations and tile fetching ``` -------------------------------- ### KernelBuilder::build Method Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Kernel.md Constructs and returns a `Kernel` instance using the configurations provided to the `KernelBuilder`. Panics if any required component is missing. ```rust pub fn build(self) -> Kernel ``` -------------------------------- ### Registering System in Queue Stage Source: https://github.com/maplibre/maplibre-rs/blob/main/_autodocs/api-reference/Plugin.md Adds a system to the `Queue` stage of the render schedule. This stage is used for queuing render commands and uploading data to the GPU. ```rust schedule.add_system_to_stage( RenderStageLabel::Queue, SystemContainer::new(my_queue_system), ); ```