Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Last active February 28, 2021 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unixpickle/917fdb17d9b434461620f569030098ab to your computer and use it in GitHub Desktop.
Save unixpickle/917fdb17d9b434461620f569030098ab to your computer and use it in GitHub Desktop.
Minimize the maximum of a mesh's SDF
module github.com/unixpickle/heart3d
go 1.15
require (
github.com/unixpickle/essentials v1.3.0
github.com/unixpickle/ffmpego v0.1.3
github.com/unixpickle/model3d v0.2.12
)
package main
import (
"log"
"math"
"github.com/unixpickle/essentials"
"github.com/unixpickle/ffmpego"
"github.com/unixpickle/model3d/model2d"
"github.com/unixpickle/model3d/model3d"
"github.com/unixpickle/model3d/toolbox3d"
)
func main() {
mesh2d := model2d.MustReadBitmap("outline.png", nil).Mesh()
tolerance := mesh2d.Min().Dist(mesh2d.Max()) * 0.1
stepSize := tolerance * 0.3
rast := model2d.Rasterizer{
Scale: 0.5,
Subsamples: 2,
Bounds: &model2d.Rect{MinVal: mesh2d.Min(), MaxVal: mesh2d.Max()},
}
firstFrame := rast.Rasterize(mesh2d)
size := firstFrame.Bounds()
vw, err := ffmpego.NewVideoWriter("out.mp4", size.Dx(), size.Dy(), 24)
essentials.Must(err)
defer vw.Close()
essentials.Must(vw.WriteFrame(firstFrame))
for i := 0; i < 100; i++ {
center, maxSDF := MaxPoint(mesh2d)
mesh2d = mesh2d.MapCoords(func(c model2d.Coord) model2d.Coord {
dist := c.Dist(center)
direction := center.Sub(c).Normalize()
step := stepSize * math.Exp(-dist*dist/(tolerance*tolerance))
return c.Add(direction.Scale(step))
})
log.Printf("iter %d: max_sdf=%f", i, maxSDF)
img := rast.Rasterize(mesh2d)
essentials.Must(vw.WriteFrame(img))
}
essentials.Must(vw.Close())
}
func MaxPoint(mesh *model2d.Mesh) (model2d.Coord, float64) {
sdf := model2d.MeshToSDF(mesh)
search := toolbox3d.GridSearch2D{
XStops: 30,
YStops: 30,
Recursions: 3,
}
return search.Maximize(sdf.Min(), sdf.Max(), sdf.SDF)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment