#image #sdf #gamedev #vector

distance-field

Generate distance fields from images for pseudo-vector rendering

10 releases

0.2.0 Oct 10, 2022
0.1.8 Oct 9, 2022
0.1.7 Jul 29, 2019
0.1.6 Jan 6, 2018
0.1.5 Dec 28, 2017

#63 in Rendering

Download history 6/week @ 2023-08-01 9/week @ 2023-08-08 20/week @ 2023-08-15 16/week @ 2023-08-22 17/week @ 2023-08-29 23/week @ 2023-09-05 9/week @ 2023-09-12 5/week @ 2023-09-19 10/week @ 2023-09-26 11/week @ 2023-10-03 7/week @ 2023-10-10 15/week @ 2023-10-17 10/week @ 2023-10-24 19/week @ 2023-10-31 12/week @ 2023-11-07 11/week @ 2023-11-14

53 downloads per month
Used in omt

GPL-3.0 license

175KB
80 lines

distance-field

A Rust library/executable for generating distance field bitmaps to render as pseudo-vector images in a shader

CI Version Rust Documentation License

Generator binary

Checkout the repository and cd into it; then run:

cargo run --example generator -- img/input.png output.png 64 64

This will take the following image as input:

Rust logo

And generate a 64x64 distance field:

Distance field

Now we can use the generated distance field to create a vector image.

Using the distance field

First we need to scale it up with a linear interpolation:

Upscaled linear

Then we apply a treshold function:

Treshold

You can see that we have something which looks very similar to the original input image and that just from a 64x64 image! But it's still very pixelated and doesn't look like a vector image. This can be fixed by not doing a hard treshold but allowing some shades of gray.

Library

An example usecase for the library would be to automatically convert asset images. You can achieve this by having a build.rs similar to this:

extern crate image;
extern crate distance_field;

use std::fs::File;
use distance_field::DistanceFieldExt;

fn convert_image_to_dfield(input: &str, output: &str) {
    // Load the 'input' image
    let img = image::open(input).unwrap();

    // Generate a distance field from the image
    let outbuf = img.grayscale().distance_field(distance_field::Options {
        size: (128, 128),
        max_distance: 256,
        ..Default::default()
    });

    // Save it to 'output' as a PNG
    image::DynamicImage::ImageLuma8(outbuf).save(output).unwrap();
}

fn main() {
    convert_image_to_dfield("img/input.png", "output.png");
}

And adding the following to Cargo.toml:

[packages]
build = "build.rs"

[build-dependencies]
distance-field = "0.1"
image = "0.22"

Dependencies

~6.5MB
~89K SLoC