# gl-marching-squares
**Repository Path**: rolldown/gl-marching-squares
## Basic Information
- **Project Name**: gl-marching-squares
- **Description**: 高性能等值线提取库,基于Marching Squares算法实现,支持ESM、CJS和IIFE多种模块格式,适用于WebGL可视化、科学数据展示等场景。
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: main
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 1
- **Created**: 2025-10-10
- **Last Updated**: 2025-11-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# gl-marching-squares
A high-performance contour extraction library based on the Marching Squares algorithm, supporting ESM, CJS, and IIFE module formats. Ideal for WebGL visualization, scientific data rendering, geographic information systems, and image processing.
## Core Features
- **Multi-Module Compatibility**: Natively supports ESM (modern frontend), CJS (Node.js), and IIFE (browser global) environments.
- **Blazing-Fast Performance**:
- Sparse grid optimization (skips empty regions, 50-80% faster for sparse data).
- Pre-allocated memory (eliminates dynamic resizing overhead).
- Native Float32Array support (reduces memory usage and improves CPU cache efficiency).
- **Flexible Contour Control**: Toggle contour closing with `enableClosing` and customize precision with epsilon values.
- **Image Processing Support**: Natively compatible with `ImageData` format for direct contour extraction from images.
- **Type Safety**: Full TypeScript definitions for IDE autocompletion and compile-time validation.
- **Bulk Processing**: Efficient multi-threshold contour generation with `generateMultiContours`.
## Installation
### 1. Package Managers (ESM/CJS)
For Node.js or frontend projects (Webpack/Vite/Rollup):
```bash
# npm
npm install gl-marching-squares --save
# yarn
yarn add gl-marching-squares
```
### 2. Direct Browser Import (IIFE)
For no-build browser projects - exposed as global variable `glmarchingsquares`:
```html
```
## Quick Start Examples
### 1. Basic Grid Contour Extraction
```typescript
import { generateContour, convertToFloat32Array } from 'gl-marching-squares';
// Define 2D grid data
const grid = [
[0, 1, 0, 1, 0],
[1, 2, 1, 2, 1],
[0, 1, 0, 1, 0],
[1, 2, 1, 2, 1],
[0, 1, 0, 1, 0]
];
// Convert to high-performance format
const { data, width, height } = convertToFloat32Array(grid);
// Generate contours
const contours = generateContour(data, width, height, 1, {
enableClosing: true
});
```
### 2. Contour Extraction from ImageData
```typescript
import { generateContour, convertImageDataToGrid } from 'gl-marching-squares';
// Get image data from Canvas
const canvas = document.getElementById('sourceCanvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Convert to grid data (using grayscale channel)
const { data, width, height } = convertImageDataToGrid(imageData, 'gray');
// Generate contours (threshold 128 for mid-brightness regions)
const contours = generateContour(data, width, height, 128, {
enableClosing: true,
enableSparse: true
});
// Draw results on canvas
const targetCtx = document.getElementById('targetCanvas').getContext('2d');
contours.forEach(([[x1, y1], [x2, y2]]) => {
targetCtx.beginPath();
targetCtx.moveTo(x1, y1);
targetCtx.lineTo(x2, y2);
targetCtx.stroke();
});
```
### 3. Browser Global Usage (IIFE)
```html
```
## API Documentation
### Data Conversion Functions
#### `convertToFloat32Array(grid: number[][]): ConvertResult`
Converts a 2D array to row-major Float32Array format.
#### `convertImageDataToGrid(imageData: ImageData, channel?: 'gray'|'r'|'g'|'b'|'a'): ConvertResult`
Converts Canvas image data to grid format:
- `imageData`: Image data object from Canvas
- `channel`: Specifies channel to extract (default: `'gray'`)
- `'gray'`: Grayscale (0.299*R + 0.587*G + 0.114*B)
- `'r'|'g'|'b'|'a'`: Corresponding RGBA channels
### Contour Generation Functions
#### `generateContour(data: Float32Array, width: number, height: number, threshold: number, options?: ContourOptions): ContourResult`
Generates contours for a single threshold value.
| Parameter | Type | Description |
|-------------|-----------------|---------------------------------|
| `data` | `Float32Array` | Grid data (from conversion functions) |
| `width` | `number` | Grid width |
| `height` | `number` | Grid height |
| `threshold` | `number` | Contour threshold value |
| `options` | `ContourOptions`| Optional configuration |
**Configuration Options**:
```typescript
interface ContourOptions {
skipValidation?: boolean; // Skip data validation (default: false)
returnFloat32?: boolean; // Return flat Float32Array (default: false)
epsilon?: number; // Interpolation precision (default: 1e-6)
enableSparse?: boolean; // Enable sparse optimization (default: true)
enableClosing?: boolean; // Enable contour closing (default: false)
closingEpsilon?: number; // Closing precision (default: epsilon)
}
```
#### `generateMultiContours(data: Float32Array, width: number, height: number, thresholds: number[], options?: ContourOptions): Record`
Batch-generates contours for multiple thresholds, reusing preprocessing for efficiency.
## Image Processing Use Cases
1. **Medical Imaging**: Extract organ contours from CT/MRI scans
2. **Remote Sensing**: Generate terrain contours from satellite imagery
3. **Computer Vision**: Object edge detection and region segmentation
4. **Image Editing**: Intelligent selection and edge highlighting
For image processing:
- Downscale high-resolution images first for better performance
- Enable `enableSparse: true` for images with solid color backgrounds
- Choose thresholds based on image brightness range (0-255)
## Performance Comparison
Test results on **1000x1000 dense grid** (Intel i7-13700K + Chrome 126):
| Library | Basic Extraction (ms) | With Contour Closing (ms) | Memory Usage (MB) |
|------------------------|-----------------------|----------------------------|-------------------|
| gl-marching-squares | 24.3 | 28.6 | 3.2 |
| Community Marching Squares | 89.2 | 128.4 | 9.5 |
| npm `marchingsquares` | 215.6 | Not Supported | 18.7 |
*For sparse grids (80% empty regions): gl-marching-squares is 3-5x faster than competitors*
## Compatibility
| Module Format | Supported Environments |
|---------------|-------------------------------------------------|
| ESM | Node.js 14+, Chrome 61+, Firefox 60+, Safari 11+ |
| CJS | Node.js 8+ |
| IIFE | IE 11+, all modern browsers (no build required) |
## License
[MIT License](LICENSE)