Skip to main content

Crate oxigdal_wasm

Crate oxigdal_wasm 

Source
Expand description

§OxiGDAL WASM - WebAssembly Bindings for Browser-based Geospatial Processing

This crate provides comprehensive WebAssembly bindings for OxiGDAL, enabling high-performance browser-based geospatial data processing with a focus on Cloud Optimized GeoTIFF (COG) visualization and manipulation.

§Features

§Core Capabilities

  • COG Viewing: Efficient viewing of Cloud Optimized GeoTIFFs
  • Tile Management: Advanced tile caching and pyramid management
  • Progressive Rendering: Smooth progressive loading with adaptive quality
  • Image Processing: Color manipulation, contrast enhancement, filters
  • Performance Profiling: Built-in profiling and bottleneck detection
  • Worker Pool: Parallel tile loading using Web Workers
  • Streaming: Adaptive tile streaming with bandwidth estimation

§Advanced Features

  • Compression: Multiple compression algorithms for bandwidth reduction
  • Color Operations: Extensive color space conversions and palettes
  • TypeScript Bindings: Auto-generated TypeScript definitions
  • Error Handling: Comprehensive error types and recovery
  • Viewport Management: Advanced viewport transformations and history

§Architecture

The crate is organized into several modules:

  • bindings: TypeScript type definitions and documentation generation
  • canvas: Image processing, resampling, and canvas rendering utilities
  • color: Advanced color manipulation, palettes, and color correction
  • compression: Tile compression algorithms (RLE, Delta, Huffman, LZ77)
  • error: Comprehensive error types for all operations
  • fetch: HTTP fetching with retry logic and parallel requests
  • profiler: Performance profiling and bottleneck detection
  • rendering: Canvas rendering, double buffering, and progressive rendering
  • streaming: Adaptive tile streaming with bandwidth management
  • tile: Tile coordinate systems, caching, and pyramid management
  • worker: Web Worker pool for parallel processing

§Basic Usage Example (JavaScript)

import init, { WasmCogViewer } from '@cooljapan/oxigdal';

async function viewCog(url) {
    // Initialize the WASM module
    await init();

    // Create a viewer instance
    const viewer = new WasmCogViewer();

    // Open a COG file
    await viewer.open(url);

    // Get image metadata
    console.log(`Image size: ${viewer.width()}x${viewer.height()}`);
    console.log(`Tile size: ${viewer.tile_width()}x${viewer.tile_height()}`);
    console.log(`Bands: ${viewer.band_count()}`);
    console.log(`Overviews: ${viewer.overview_count()}`);

    // Read a tile as ImageData for canvas rendering
    const imageData = await viewer.read_tile_as_image_data(0, 0, 0);

    // Render to canvas
    const canvas = document.getElementById('map-canvas');
    const ctx = canvas.getContext('2d');
    ctx.putImageData(imageData, 0, 0);
}

§Advanced Usage Example (JavaScript)

import init, {
    AdvancedCogViewer,
    WasmImageProcessor,
    WasmColorPalette,
    WasmProfiler,
    WasmTileCache
} from '@cooljapan/oxigdal';

async function advancedProcessing() {
    await init();

    // Create an advanced viewer with caching
    const viewer = new AdvancedCogViewer();
    await viewer.open('https://example.com/image.tif', 100); // 100MB cache

    // Setup profiling
    const profiler = new WasmProfiler();
    profiler.startTimer('tile_load');

    // Load and process a tile
    const imageData = await viewer.readTileAsImageData(0, 0, 0);
    profiler.stopTimer('tile_load');

    // Apply color palette
    const palette = WasmColorPalette.createViridis();
    const imageBytes = new Uint8Array(imageData.data.buffer);
    palette.applyToGrayscale(imageBytes);

    // Apply image processing
    WasmImageProcessor.linearStretch(imageBytes, imageData.width, imageData.height);

    // Get cache statistics
    const cacheStats = viewer.getCacheStats();
    console.log('Cache hit rate:', JSON.parse(cacheStats).hit_count);

    // Get profiling statistics
    const profStats = profiler.getAllStats();
    console.log('Performance:', profStats);
}

§Progressive Loading Example (JavaScript)

async function progressiveLoad(url, canvas) {
    const viewer = new AdvancedCogViewer();
    await viewer.open(url, 100);

    // Start with low quality for quick feedback
    viewer.setViewportSize(canvas.width, canvas.height);
    viewer.fitToImage();

    const ctx = canvas.getContext('2d');

    // Load visible tiles progressively
    const viewport = JSON.parse(viewer.getViewport());
    for (let level = viewer.overview_count(); level >= 0; level--) {
        // Load tiles at this level
        const imageData = await viewer.readTileAsImageData(level, 0, 0);
        ctx.putImageData(imageData, 0, 0);

        // Allow UI updates
        await new Promise(resolve => setTimeout(resolve, 0));
    }
}

§Performance Considerations

§Memory Management

  • The tile cache automatically evicts old tiles using LRU strategy
  • Configure cache size based on available memory
  • Use compression to reduce memory footprint

§Network Optimization

  • HTTP range requests are used for partial file reads
  • Retry logic handles network failures gracefully
  • Parallel requests improve throughput
  • Adaptive streaming adjusts quality based on bandwidth

§Rendering Performance

  • Double buffering prevents flickering
  • Progressive rendering provides quick feedback
  • Web Workers enable parallel tile processing
  • Canvas operations are optimized for WASM

§Error Handling

All operations return Result types that can be converted to JavaScript exceptions. Errors are categorized by type:

  • FetchError: Network and HTTP errors
  • CanvasError: Canvas and rendering errors
  • WorkerError: Web Worker errors
  • TileCacheError: Cache management errors
  • JsInteropError: JavaScript interop errors
try {
    await viewer.open(url);
} catch (error) {
    if (error.message.includes('HTTP 404')) {
        console.error('File not found');
    } else if (error.message.includes('CORS')) {
        console.error('Cross-origin request blocked');
    } else {
        console.error('Unknown error:', error);
    }
}

§Browser Compatibility

This crate requires:

  • WebAssembly support
  • Fetch API with range request support
  • Canvas API
  • Web Workers (optional, for parallel processing)
  • Performance API (optional, for profiling)

Supported browsers:

  • Chrome 57+
  • Firefox 52+
  • Safari 11+
  • Edge 16+

§Building for Production

# Optimize for size
wasm-pack build --target web --release -- --features optimize-size

# Optimize for speed
wasm-pack build --target web --release -- --features optimize-speed

# Generate TypeScript definitions
wasm-pack build --target bundler --release

§License

This crate is part of the OxiGDAL project and follows the same licensing terms.

Modules§

component
WASM Component Model bindings for OxiGDAL.
wasm_memory
WASM linear-memory management utilities.

Structs§

AdvancedCogViewer
Advanced COG viewer with comprehensive tile management and caching
Animation
Basic animation state
AnimationManager
Animation frame manager
AnimationStats
Animation statistics
BandwidthEstimator
Bandwidth estimator
BatchTileLoader
Batch tile loader for efficient multi-tile loading
Bottleneck
Bottleneck information
BottleneckDetector
Bottleneck detector
CacheStats
Cache statistics
CachedTile
Cached tile data
CanvasBuffer
Canvas buffer for double buffering
CanvasRenderer
Canvas renderer with double buffering and progressive rendering
ChannelHistogramJson
JSON-serializable representation of a single channel histogram
ChannelOps
Color channel operations
ColorCorrectionMatrix
Color correction matrix
ColorPalette
Color palette
ColorQuantizer
Color quantization
ColorTemperature
Color temperature adjustment
CompressionBenchmark
Compression benchmark
CompressionSelector
Compression selector for automatic algorithm selection
CompressionStats
Compression statistics
CounterStats
Counter statistics
CustomBinHistogramJson
JSON-serializable representation of a custom bin range histogram
DeltaCompressor
Delta encoding compression
DocGenerator
Documentation generator
EnhancedFetchBackend
Enhanced fetch backend with retry logic and statistics
FetchBackend
HTTP fetch backend using browser’s fetch API
FetchStats
Fetch statistics
FrameRateStats
Frame rate statistics
FrameRateTracker
Frame rate tracker
GeoJsonExporter
GeoJSON export utilities
GradientGenerator
Color gradient generator
Histogram
Image histogram
HistogramJson
JSON-serializable representation of the full histogram
Hsv
Color in HSV color space
HuffmanCompressor
Simplified Huffman encoding
ImageProcessor
Image processing utilities
ImageStats
Image statistics
ImportanceCalculator
Tile importance calculator
Lz77Compressor
LZ77-style compression
MemoryMonitor
Memory monitor
MemorySnapshot
Memory snapshot
MemoryStats
Memory statistics
MultiResolutionStreamer
Multi-resolution tile streamer
PaletteEntry
Color palette entry
PanAnimation
Animation for panning the viewport
PendingJob
Pending job information
PerformanceCounter
Performance counter
PoolStats
Worker pool statistics
PrefetchScheduler
Prefetch scheduler
PrioritizedRequest
Prioritized fetch request
Profiler
Performance profiler
ProfilerSummary
Profiler summary
ProgressiveLoader
Progressive loader for prioritized tile loading
ProgressiveRenderStats
Progressive rendering statistics
ProgressiveRenderer
Progressive rendering manager
QualityAdapter
Quality adapter for dynamic quality adjustment based on bandwidth
RequestQueue
Request queue with priority management
Resampler
Image resampler
RetryConfig
Retry configuration
Rgb
Color in RGB color space
RleCompressor
Run-length encoding compression
SpringAnimation
Spring animation using physics simulation
StreamBuffer
Stream buffer for managing loaded tiles
StreamBufferStats
Stream buffer statistics
StreamingStats
Streaming statistics
TileBounds
Tile bounds in the pyramid
TileCache
LRU tile cache
TileCompressor
Unified compression interface
TileCoord
Tile coordinate in a pyramid
TilePrefetcher
Tile prefetcher
TilePyramid
Tile pyramid metadata
TileStreamer
Progressive tile streamer
TsClass
Class definition
TsFunction
Function signature
TsInterface
Interface definition
TsModule
Module definition
TsParameter
Function parameter
TsTypeAlias
Type alias definition
Viewport
Viewport for managing the visible area of the image
ViewportHistory
Viewport history for undo/redo
ViewportState
Viewport state with transformation and bounds
ViewportTransform
Viewport transformation matrix
WasmCogViewer
WASM-compatible COG (Cloud Optimized GeoTIFF) viewer
WasmColorPalette
WASM bindings for color operations
WasmImageProcessor
WASM bindings for canvas operations
WasmProfiler
WASM bindings for profiler
WasmTileCache
WASM bindings for tile management
WasmWorkerPool
WASM bindings for worker pool (for demonstration/testing)
WhiteBalance
White balance adjustment
WorkerInfo
Worker information
WorkerJobRequest
Worker job request
WorkerJobResponse
Worker job response
WorkerPool
Worker pool for parallel tile loading
YCbCr
Color in YCbCr color space
ZoomAnimation
Animation for zooming the viewport

Enums§

CanvasError
Canvas rendering errors
CompressionAlgorithm
Compression algorithm
ContrastMethod
Contrast enhancement methods
Easing
Easing function types
FetchError
Fetch-related errors
JobStatus
Job status
JsInteropError
JavaScript interop errors
LoadStrategy
Load strategy for streaming
PrefetchStrategy
Prefetching strategy
RenderQuality
Rendering quality levels
RequestPriority
Request priority
ResampleMethod
Resampling methods
StreamingQuality
Streaming quality level
TileCacheError
Tile cache errors
TsType
TypeScript type representation
WasmError
Comprehensive WASM error types
WorkerError
Web Worker errors
WorkerRequestType
Worker request types
WorkerResponseType
Worker response types

Traits§

EasingFunction
Trait for applying easing functions

Functions§

create_oxigdal_wasm_docs
Creates the standard OxiGDAL WASM bindings documentation
init
Initialize the WASM module with better error handling
is_tiff_url
Checks if the given URL points to a TIFF file by reading the header
version
Version information

Type Aliases§

JobId
Unique job identifier
WasmResult
Result type for WASM operations