Signed Distance Functions (SDF's) for the Playdate

I thought I'd make a Lua library of Signed Distance Functions (SDF's) available.

It's a port of the GLSL shader SDF's from Inigo Quilez :: computer graphics, mathematics, shaders, fractals, demoscene and more to start.

I'm not sure how useful they'll be for others, but essentially these allow you to efficiently determine distance from a shape, which can be used for collision detection, among other things. I've only started playing with Lua since I received my Playdate last month so the code is probably fairly ugly :slight_smile: and I suspect creates more garbage to be collected than needed.

collisions
sprites
raymarch

9 Likes

Benchmarks

I placed each object sliightly inside a 100x100 box and ran 10k distance checks on device (recent model, firmware 2.4.x) for each function (thank you coroutines) to establish how many distance checks can be made for each within 1/50th second.

SDF v2 v1
sdCircle 306.7 (+150%) 123.1
sdRoundedBox 69.0 (+49%) 46.3
sdBox 74.8 (+43%) 52.3
sdOrientedBox 21.7 (-13%) 25.0
sdSegment 77.7 (+11%) 69.7
sdRhombus 32.3 (+21%) 26.7
sdTrapezoid 41.0 (+12%) 36.5
sdParallelogram 28.1 (+13%) 24.8
sdEquilateralTriangle 61.4 (+22%) 50.4
sdTriangleIsosceles 34.8 (+22%) 28.9
sdTriangle 15.7 (+11%) 14.2
sdPolygon (3) 17.6 (+18%) 14.9
sdUnevenCapsule 124.3 (+16%) 107.4
sdPentagon 33.3 (+6%) 31.4
sdRegularPolygon (5) 52.6 (+22%) 43.2
sdHexagon 48.1 (+13%) 42.5
sdRegularPolygon (6) 52.3 (+20%) 43.5
sdOctagon 32.2 (+7%) 30.1
sdRegularPolygon (8) 52.1 (+21%) 42.9
sdHexagram 32.4 (+5%) 31.0
sdStar5 23.8 (+2%) 23.4
sdPie 70.5 (+52%) 46.4
sdCutDisk 108.1 (+58%) 68.4
sdArc 116.8 (+65%) 70.9
sdRing 48.2 (+14%) 42.1
sdHorseshoe 33.0 (+8%) 30.5
sdVesica 86.7 (+26%) 68.6
sdOrientedVesica 24.3 (+1%) 24.1
sdMoon 81.1 (+33%) 60.9
sdCross 53.3 (+46%) 36.4
sdRoundedX 88.0 (+46%) 60.2
sdQuad 12.3 (+6%) 11.6
sdPolygon (4) 13.9 (+17%) 11.9
sdEllipse 6.6 (+47%) 4.5
sdParabola 67.4 (-4%) 70.2
sdTunnel 58.6 (+27%) 46.1

2024-03-07: baseline
2024-03-09: better bench marking (6x runs, better timing); better local variables in SDFs

Remember, readers! For efficiency, if only interested in collisions, you can just run a quick bounding box check (like Playdate's sprite AABB check) before the SDF itself.

2 Likes

Sped things up a bit and added a better benchmark.

1 Like

Just trying this and couldn't run some of the bundled examples. Have filed some github issues.

That said, I'm really excited to make a game using these.

Cheers!

Thanks, Ive fixed these problems caused by the last push.

I should also add a module of draw functions to make it more consumable since it takes some noodling to find the drawing commands for the shapes (e.g. use of apothem for n-gons). I'll get to that at some point.

I was intrigued by your peggle idea. Here's a quick sketch.

peggle

3 Likes

Nice! Is that 100% SDFs?

Added complex bezier example source to repo

1 Like

Experimenting.

koatari

koatari2

4 Likes