Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: CI

on:
push:
branches: ["**"]
pull_request:

jobs:
build-and-test:
name: Build & test (${{ matrix.os }} / ${{ matrix.cxx }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
cxx: [g++, clang++]
exclude:
# macOS g++ is an alias for clang; one clang job there is enough.
- os: macos-latest
cxx: g++
steps:
- uses: actions/checkout@v4

- name: Build (dependency-free, single recipe)
run: make CXX=${{ matrix.cxx }}

- name: Run test suite
run: ./tests/run_tests.sh ./flatland

- name: Smoke-test the committed time-series example
run: |
./flatland examples/sphere_areas/sphere_coarse.obj \
-b examples/with_fields/timeseries_demo/timeseries.txt -j > /dev/null

cmake-build:
name: CMake build (Ubuntu)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure & build with CMake
run: |
cmake -S src -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release
- name: Run test suite against CMake binary
run: ./tests/run_tests.sh ./build/flatland
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Build artifacts
/build/
src/build/
/flatland
*.o
*.ppm

# OS cruft
.DS_Store
26 changes: 26 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# FlatLand — dependency-free build.
#
# No CMake, no third-party libraries: just a C++17 compiler. Ideal for airgapped
# or minimal systems.
#
# make # build ./flatland
# make test # build, then run the test suite
# make clean # remove build artifacts
#
# Override the compiler if needed: make CXX=clang++

CXX ?= c++
CXXFLAGS ?= -std=c++17 -O2 -Wall
LDFLAGS ?= -pthread
SRC = src/main.cpp
BIN = flatland

$(BIN): $(SRC)
$(CXX) $(CXXFLAGS) $(SRC) -o $(BIN) $(LDFLAGS)

.PHONY: test clean
test: $(BIN)
./tests/run_tests.sh ./$(BIN)

clean:
rm -f $(BIN)
271 changes: 154 additions & 117 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,156 +1,193 @@
# FlatLand
FlatLand is a modular C++ utility designed for the geometric analysis and visualization of 3D models via orthographic projection and rasterization.

While primarily focused on computing the projected silhouette and visible surface area of 3D meshes (OBJ format), the latest version introduces scalar field mapping. This allows users to project arbitrary data (e.g., temperature, stress, pressure) defined on nodes or faces onto the 2D viewing plane, generating average value statistics and heatmap visualizations.
FlatLand is a small, dependency-free C++ utility for the geometric analysis of 3D
meshes (OBJ and STL) via orthographic projection and software rasterization.

The tool features a custom Z-buffer implementation for depth testing and edge-function rasterization for high-fidelity coverage calculations. It is optimized for batch processing, supporting runtime precision switching (Float vs Double) and per-view resolution settings.
Its core job is computing the **projected (visible) surface area** of a mesh from
arbitrary viewing angles. On top of that it can map a **scalar field** (defined per
node or per face — temperature, pressure, radiance, stress, …) onto the visible
projection and report per-view statistics: average, min, max, and the **area
integral** `∫ f dA`. The integral is deliberately generic: supply a radiance field
and it is radiant intensity; supply pressure and it is a force; FlatLand itself
stays domain-agnostic.

## Key Features
- **Projected Area Analysis**: Accurate calculation of visible surface area from arbitrary viewing angles.
- **Scalar Data Mapping**: Load external data files (node-based or face-based) to compute visible average values and generate heatmap images.
- **Flexible Batch Mode**: Process thousands of views with a single load of the mesh geometry. Supports overriding resolution and data files per-view.
- **Runtime Precision**: Switch between float (speed) and double (accuracy) arithmetic via CLI flags.
- **Visual Output**: export .ppm heatmaps of the projected mesh.
- **JSON Integration**: Structured output for easy parsing in automated pipelines.
It is built for **time-dependent batches** — sweep thousands of timesteps with a
changing view direction *and* a changing field over a fixed mesh, in seconds.

## Build Instructions
The tool relies on standard C++17 and CMake (3.14+). No third-party dependencies are required.
## Design goals
- **Reliable** — clean error handling (no crashes on bad input), a test suite, and CI.
- **Fast** — multi-threaded batch processing; ~1000 changing-field/changing-view
timesteps on a 70k-triangle mesh in a couple of seconds.
- **Dependency-free** — standard C++17 and nothing else. Builds with a single
compiler invocation, which matters on minimal or airgapped systems.

## Build

FlatLand is a single `.cpp` file. No third-party libraries.

**Simplest recipe (airgapped-friendly):**
```shell
# Clone the repository
git clone https://github.com/Interfluo/flatland.git
cd flatland
make # produces ./flatland
```

# Build using the provided helper script
./run_build.sh
**Or a single compiler call, no build system at all:**
```shell
c++ -std=c++17 -O2 -pthread src/main.cpp -o flatland
```
Alternatively, you can build manually via CMake:

**Or via CMake (3.14+):**
```shell
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Release
cmake -S src -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
```

To verify the build:
Verify:
```shell
./build/flatland --help
./flatland --help
make test # build + run the test suite
```

> The only system requirement is a C++17 compiler with threads (`-pthread`),
> available out of the box with stock GCC or Clang.

## Usage
```shell
./flatland <mesh.obj> [options]
```
### Core options
| Flag | Arguments | Description |
| :--- | :-------- | :---------- |
| -v | x y z | Add a single view direction. Can be repeated multiple times. |
| -b | file | Load views from a batch file (see format below). |
| -o | prefix | "Save heatmap images with this filename prefix (e.g., out_0000.ppm)." |
| -j | none | Output results as structured JSON to stdout. |
| -h | none | Show help message. |

### Simulation Parameters
### Meshes
OBJ and STL (binary or ASCII) are accepted, auto-detected by file extension. STL
triangles carry no shared vertices, so STL fields are face-based.

### Options
| Flag | Arguments | Description |
| :--- | :-------- | :---------- |
| -r | val | Set default pixel resolution (default: 0.001). Used if a batch entry doesn't specify one.|
| -d | file | "Path to a default scalar data file (text file, one value per line)."|
| -p | mode | "Set math precision: float (default, faster) or double (higher accuracy)."|
| --no-cull |none | Disable backface culling (renders all matching faces).|
| `-v, --view` | x y z | Add a view direction (vector). Repeatable. |
| `-a, --angle` | az el | Add a view by azimuth/elevation in degrees. Repeatable. |
| `-b, --batch` | file | Load views/timesteps from a file (see format below). Additive with `-v`/`-a`. |
| `-r, --res` | val | Default pixel resolution (default `0.001`). |
| `-d, --data` | file[@col] | Default scalar field file (see [Field files](#field-files)). |
| `--field-mode` | node\|face\|auto | Force field interpretation (default `auto`, inferred from row count). |
| `-p, --precision` | mode | `float` (default, faster) or `double` (more accurate). |
| `-t, --threads` | n | Worker threads for batch views (default: auto / all cores). |
| `--no-cull` | — | Disable backface culling (render all faces). |
| `-o, --out` | prefix | Save PPM heatmaps as `<prefix>_<idx>.ppm`. |
| `-j, --json` | — | Emit structured JSON to stdout. |
| `-h, --help` | — | Show help. |

### Views
A view is a direction the camera looks along. Specify it as a raw vector (`-v x y z`)
or by **azimuth/elevation in degrees** (`-a az el`), where azimuth sweeps around `+Z`
from `+X` and elevation rises from the XY-plane. Both forms are repeatable and can be
mixed with a batch file.

### Field files
A field file is a matrix: **one row per mesh entity** (vertex or face), and **one or
more whitespace-separated columns**. Each column is a timestep, so an entire time
series can live in a single file. Append `@<col>` to a data path to pick a column
(default `0`), e.g. `fields.txt@7`. A classic one-value-per-line file is just the
single-column case. Node-vs-face is inferred from the row count; use `--field-mode`
to force it when the vertex and face counts coincide.

### Per-view outputs
| Field | Meaning |
| :--- | :--- |
| `area` | Visible projected area = `covered_pixels × resolution²`. |
| `average` | Mean field value over visible pixels (requires a data file). |
| `integral` | Area integral of the field: `Σ value × pixel_area` (= radiant intensity, force, …). |
| `min` / `max` | Field extremes over visible pixels. |

> **Accuracy note:** coverage is computed by point-sampling pixel centers with edge
> functions and a Z-buffer. Area therefore converges as resolution increases; choose
> a resolution fine enough to resolve thin features (use `-o` to inspect).

## Time-dependent / batch workflow

The batch file is the time-series interface: **one line per timestep**. Each line is
either a direction vector or an azimuth/elevation angle, followed by an optional
resolution and/or field selector:

### Batch File Format
The batch file (-b) allows for defining mixed-resolution or mixed-data jobs. Each line represents a view.
```text
<nx> <ny> <nz> [resolution] [data_file_path]
<nx> <ny> <nz> [resolution] [data[@col]] # direction vector
a <az> <el> [resolution] [data[@col]] # azimuth / elevation (degrees)
```
- resolution and data_file_path are optional.
- If omitted, the global defaults (set via -r and -d) are used.

**Example** views.txt:
- `resolution` and `data` are optional and order-independent — a pure number is read
as a resolution, anything else as a data-file path. Omitted values fall back to
`-r` / `-d`.
- Pair a single field matrix with `@<col>` to advance the field per timestep
(`field.txt@0`, `field.txt@1`, …) without one file per step.
- Relative data paths resolve against the **batch file's directory**, so a case folder
is portable and runs from any working directory.
- Lines starting with `#` are comments.

Each distinct field file is loaded once into a shared, read-only cache; workers extract
their timestep's column concurrently, so a single shared matrix is never re-parsed
per thread.

**Example** `timeseries.txt` (orbit in azimuth, advancing one field column per step):
```text
# Standard view using global defaults
1.0 0.0 0.0

# High-resolution view (0.005 pixel size)
0.0 1.0 0.0 0.005
# a <azimuth> <elevation> <resolution> field.txt@<timestep>
a 0 20 0.002 field.txt@0
a 15 20 0.002 field.txt@1
a 30 20 0.002 field.txt@2
```
```shell
./flatland part.obj -b timeseries.txt -j > results.json
```

# View with specific scalar data file overlay
0.0 0.0 1.0 0.002 ./pressure_load_case_2.txt
### Generating a time series
`examples/with_fields/generate_field.py` builds an orbiting-view / evolving-field case
using **only the Python standard library** (no numpy/pyvista). It writes a single
multi-column field file plus an angle-based batch:
```shell
python3 examples/with_fields/generate_field.py bunny.obj data 1000 0.002
./flatland bunny.obj -b data/timeseries.txt -j > results.json
```
A small ready-to-run demo (two files: one matrix + one batch) is committed at
`examples/with_fields/timeseries_demo/`:
```shell
./flatland examples/sphere_areas/sphere_coarse.obj \
-b examples/with_fields/timeseries_demo/timeseries.txt
```

### Examples
**1. Basic Area Calculation**: Calculate the projected area of bunny.obj from the X-axis using default settings.
## Examples
**1. Basic area** — projected area of the bunny down the X axis:
```shell
./flatland bunny.obj -v 1 0 0
```
**2. Heatmap Generation with Double Precision**: Map values from temps.txt onto the mesh, render a heatmap to heat_0000.ppm, using high-precision math.
**2. STL + angle view** — an STL part viewed from azimuth 45°, elevation 30°:
```shell
./flatland part.stl -a 45 30
```
**3. Field heatmap, double precision** — map `temps.txt`, render to `heat_0000.ppm`:
```shell
./flatland engine.obj -v 0 1 1 -d temps.txt -p double -o heat
```
**3. JSON Pipeline**: Run a batch of views defined in views.txt, outputting strict JSON for a Python script to ingest.
**4. Time series from one matrix** — orbit views, one field column per step, to JSON:
```shell
./flatland part.obj -b views.txt -j > results.json
./flatland part.obj -b timeseries.txt -j > results.json
```

## Benchmarks

### Benchmark 1: Bunny
In this benchmark, we test the impact of varying resolution (pixel area) against computed projected area and note execution times. We use the [Stanford Bunny](https://docs.pyvista.org/api/examples/_autosummary/pyvista.examples.downloads.download_bunny.html#pyvista.examples.downloads.download_bunny) geometry.

<div align="center" style="background-color: white; padding: 10px;">
<img src="https://github.com/user-attachments/assets/eaefb062-e3fc-403a-8bed-a19a79b1a1dd" width="80%" />
<p>Pixel size vs image quality</p>
</div>

The projected area calculation converges as expected, and execution times remain fast even for the highest resolution cases.

<table align="center" style="background-color: white; border-collapse: collapse; border: none;">
<tr>
<!-- Left Image -->
<td align="center" style="background-color: white; border: none; padding: 10px; width: 50%;">
<img src="https://github.com/user-attachments/assets/a425288f-d986-4660-914c-7a2a5031622b" width="100%" />
<p style="color: black; margin-top: 10px;">Projected Area error for Bunnyn</p>
</td>
<!-- Right Image -->
<td align="center" style="background-color: white; border: none; padding: 10px; width: 50%;">
<img src="https://github.com/user-attachments/assets/2c9f6436-a825-4480-8ccc-06277a2f9989" width="100%" />
<p style="color: black; margin-top: 10px;">Execution time for Bunny</p>
</td>
</tr>
</table>

*Note, that the lowest resolution image is 4x4 pixels while highest resolution image is 12070x15402 pixels.*

### Benchmark 2: Sphere
This benchmark exercises the tool on an [Icosphere](https://docs.pyvista.org/api/utilities/_autosummary/pyvista.icosphere
) of varying subdivision levels. This is a vital validation case since the area of a unit sphere is known to be $\pi$ from any view angle.

<div align="center" style="background-color: white; padding: 10px;">
<img src="https://github.com/user-attachments/assets/de64a054-27bb-41b9-83e1-f89fdeecfbec" width="80%" />
<p>Varying Icosphere subdivision levels</p>
</div>
## Validation

The results demonstrate exponential convergence towards the correct analytical answer as mesh and pixel resolution increase.

<table align="center" style="background-color: white; border-collapse: collapse; border: none;">
<tr>
<!-- Left Image -->
<td align="center" style="background-color: white; border: none; padding: 10px; width: 50%;">
<img src="https://github.com/user-attachments/assets/8c09d227-fee3-42be-9b14-3b63958bc537" width="100%" />
<p style="color: black; margin-top: 10px;">Projected Area error for Icosphere</p>
</td>
<!-- Right Image -->
<td align="center" style="background-color: white; border: none; padding: 10px; width: 50%;">
<img src="https://github.com/user-attachments/assets/17a51518-9d43-4bd4-857f-b6e737c47705" width="100%" />
<p style="color: black; margin-top: 10px;">Execution time for Icosphere</p>
</td>
</tr>
</table>


## Notes / Tips

1. **Batch Processing**: For large datasets, always use the batch file (-b) option. Repeatedly calling the tool from the CLI incurs overhead from re-loading and parsing the OBJ file every time.

2. **Resolution**: Use the image output (-o) to perform a sweep of pixel sizes when setting up a new case. Ensure you are not under-resolving thin geometry features.

3. **Culling**: Running without back-face culling (--no-cull) is supported but rarely necessary unless you are dealing with non-manifold or open surface meshes where "inside" faces contribute to the silhouette.
Two analytical checks (also enforced by the test suite):
- **Cube** — the projected area of a unit cube along an axis is exactly `1`.
- **Sphere** — the projected area of a unit sphere is `π` from any direction; FlatLand
converges to `π` as mesh and pixel resolution increase.

Run the suite (dependency-free, bash + awk):
```shell
make test # or: ./tests/run_tests.sh
```
CI builds with GCC and Clang (Linux + macOS) and via CMake on every push — see
`.github/workflows/ci.yml`.

## Tips
1. **Batch over repeated CLI calls** — one `-b` run loads and parses the mesh once;
repeatedly invoking the binary re-parses the OBJ every time.
2. **Pick resolution deliberately** — sweep `-r` with `-o` image output when setting up
a new case so thin geometry isn't under-resolved.
3. **Threads** — batch views run in parallel automatically; cap with `-t` if you need
to leave cores free.
4. **Culling** — `--no-cull` is for non-manifold or open surfaces where "inside" faces
should still contribute to the silhouette.
Loading
Loading