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
3 changes: 1 addition & 2 deletions arrays/nodes_new_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ func TestChunkRefusesASizeBelowOne(t *testing.T) {
wire(t, node, "Array", letters())
wire(t, node, "Size", nodes.ConstOutput[int]{Val: 0})

out := node.Outputs()["Out"].(nodes.ObservableExecution)
assert.NotEmpty(t, out.ExecutionReport().Errors, "a zero size would never terminate")
assert.NotEmpty(t, errorsOf(node, "Out"), "a zero size would never terminate")
}

func TestFlattenJoinsInnerArraysInOrder(t *testing.T) {
Expand Down
6 changes: 6 additions & 0 deletions arrays/nodes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ func wire(t *testing.T, node nodes.Node, port string, source nodes.OutputPort) {
require.NoError(t, input.Set(source))
}

func errorsOf(node nodes.Node, port string) []string {
out := node.Outputs()[port]
nodes.DynamicAnyValue(nil, out)
return out.(nodes.ObservableExecution).ExecutionReport().Errors
}

func wireAll(t *testing.T, node nodes.Node, port string, sources ...nodes.OutputPort) {
t.Helper()
input, ok := node.Inputs()[port].(nodes.ArrayValueInputPort)
Expand Down
12 changes: 4 additions & 8 deletions arrays/select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ func TestGatherNamesAnIndexOutsideTheArray(t *testing.T) {
wire(t, node, "Array", letters())
wire(t, node, "Indices", nodes.ConstOutput[[]int]{Val: []int{1, 5}})

out := node.Outputs()["Out"].(nodes.ObservableExecution)
assert.Contains(t, out.ExecutionReport().Errors, "index 5 is outside an array of 5 element(s)")
assert.Contains(t, errorsOf(node, "Out"), "index 5 is outside an array of 5 element(s)")
}

func TestFilterKeepsFlaggedElementsAndDropsTheRest(t *testing.T) {
Expand All @@ -40,8 +39,7 @@ func TestFilterRefusesFlagsOfTheWrongLength(t *testing.T) {
wire(t, node, "Array", letters())
wire(t, node, "Keep", nodes.ConstOutput[[]bool]{Val: []bool{true}})

out := node.Outputs()["Kept"].(nodes.ObservableExecution)
assert.Contains(t, out.ExecutionReport().Errors, "1 flag(s) for 5 element(s)")
assert.Contains(t, errorsOf(node, "Kept"), "1 flag(s) for 5 element(s)")
}

func TestSplitCutsConsecutiveRunsOfTheGivenLengths(t *testing.T) {
Expand All @@ -57,8 +55,7 @@ func TestSplitRefusesLengthsThatDoNotCoverTheArray(t *testing.T) {
wire(t, node, "Array", letters())
wire(t, node, "Lengths", nodes.ConstOutput[[]int]{Val: []int{2, 2}})

out := node.Outputs()["Out"].(nodes.ObservableExecution)
assert.Contains(t, out.ExecutionReport().Errors, "lengths add up to 4, not 5")
assert.Contains(t, errorsOf(node, "Out"), "lengths add up to 4, not 5")
}

func TestZipTurnsParallelPointArraysIntoOnePathEach(t *testing.T) {
Expand All @@ -79,6 +76,5 @@ func TestZipRefusesArraysOfDifferentLengths(t *testing.T) {
node := &nodes.Struct[arrays.ZipNode]{}
wireAll(t, node, "Arrays", letters(), nodes.ConstOutput[[]string]{Val: []string{"x"}})

out := node.Outputs()["Out"].(nodes.ObservableExecution)
assert.Contains(t, out.ExecutionReport().Errors, "arrays of 5 and 1 element(s) cannot be zipped")
assert.Contains(t, errorsOf(node, "Out"), "arrays of 5 and 1 element(s) cannot be zipped")
}
3 changes: 2 additions & 1 deletion cmd/polyform/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
_ "github.com/EliCDavis/polyform/drawing/texturing/pattern"

_ "github.com/EliCDavis/polyform/formats/colmap"
_ "github.com/EliCDavis/polyform/formats/gltf"
"github.com/EliCDavis/polyform/formats/gltf"
_ "github.com/EliCDavis/polyform/formats/obj"
_ "github.com/EliCDavis/polyform/formats/opensfm"
_ "github.com/EliCDavis/polyform/formats/ply"
Expand Down Expand Up @@ -74,6 +74,7 @@ import (

func main() {
nodeSerializer := &serialize.TypeSwitch[manifest.Entry]{}
gltf.RegisterOutputSerializers(nodeSerializer)

serialize.Register(nodeSerializer, func(i image.Image) manifest.Entry {
return manifest.Entry{Artifact: basics.Image{Image: i}}
Expand Down
19 changes: 19 additions & 0 deletions formats/gltf/gpu_instancing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,22 @@ func TestWrite_GpuInstancesOnAGroupWithNoMeshAreRefused(t *testing.T) {
assert.Contains(t, err.Error(), `"resistor"`)
assert.Contains(t, err.Error(), "has GPU instances but no mesh")
}

func TestWrite_AnEmptyInstanceListDrawsTheMeshNowhere(t *testing.T) {
cube := primitives.Cube{Width: 1, Height: 1, Depth: 1}.UnweldedQuads()
tank := &gltf.PolyformModel{Name: "tank", Mesh: &cube, GpuInstances: []trs.TRS{}}
once := &gltf.PolyformModel{Name: "once", Mesh: &cube}

var buf bytes.Buffer
require.NoError(t, gltf.WriteText(gltf.PolyformScene{Models: []*gltf.PolyformModel{tank, once}}, &buf, nil))
doc, err := gltf.ParseGLTF(&buf)
require.NoError(t, err)

for _, node := range doc.Nodes {
if node.Name == "tank" {
assert.Nil(t, node.Mesh, "an instance list with nothing in it places the mesh nowhere, not once at the origin")
} else {
assert.NotNil(t, node.Mesh)
}
}
}
25 changes: 25 additions & 0 deletions formats/gltf/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"image"
"image/color"
"image/png"
"reflect"

"github.com/EliCDavis/iter"
Expand Down Expand Up @@ -148,12 +149,36 @@ type PolyformOcclusion struct {
Strength *float64
}

type ImageCompression int

const (
ImageCompressionFast ImageCompression = iota
ImageCompressionBalanced
ImageCompressionSmallest
ImageCompressionNone
)

func (c ImageCompression) pngLevel() png.CompressionLevel {
switch c {
case ImageCompressionBalanced:
return png.DefaultCompression
case ImageCompressionSmallest:
return png.BestCompression
case ImageCompressionNone:
return png.NoCompression
}
return png.BestSpeed
}

type PolyformTexture struct {
URI string
Image image.Image
Sampler *Sampler
TexCoord int
Extensions []TextureExtension

// How Image is encoded when written; ignored for URI textures.
Compression ImageCompression
}

func (pt *PolyformTexture) canAddToGLTF() bool {
Expand Down
30 changes: 15 additions & 15 deletions formats/gltf/nodes.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ func (p *SamplerMinFilterNode) Outputs() map[string]nodes.OutputPort {
// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material

type MaterialNode struct {
Name nodes.Output[string] `description:"Name of the material"`
Name nodes.Output[string] `description:"Name of the material" advanced:"true"`

Color nodes.Output[coloring.Color] `description:"The factors for the base color of the material. This value defines linear multipliers for the sampled texels of the base color texture."`
ColorTexture nodes.Output[PolyformTexture] `description:"The base color texture. The first three components (RGB) MUST be encoded with the sRGB transfer function. They specify the base color of the material. If the fourth component (A) is present, it represents the linear alpha coverage of the material. Otherwise, the alpha coverage is equal to 1.0. The material.alphaMode property specifies how alpha is interpreted. The stored texels MUST NOT be premultiplied. When undefined, the texture MUST be sampled as having 1.0 in all components."`
Expand All @@ -394,22 +394,22 @@ type MaterialNode struct {
EmissiveTexture nodes.Output[PolyformTexture] `description:"The emissive texture. It controls the color and intensity of the light being emitted by the material. This texture contains RGB components encoded with the sRGB transfer function. If a fourth component (A) is present, it MUST be ignored. When undefined, the texture MUST be sampled as having 1.0 in RGB components."`
EmissiveFactor nodes.Output[coloring.Color] `description:"The factors for the emissive color of the material. This value defines linear multipliers for the sampled texels of the emissive texture."`
NormalTexture nodes.Output[PolyformNormal] `description:"The tangent space normal texture. The texture encodes RGB components with linear transfer function. Each texel represents the XYZ components of a normal vector in tangent space. The normal vectors use the convention +X is right and +Y is up. +Z points toward the viewer. If a fourth component (A) is present, it **MUST** be ignored. When undefined, the material does not have a tangent space normal texture."`
OcclusionTexture nodes.Output[PolyformOcclusion] `description:"Ambient occlusion map, darkening crevices under ambient light."`
AlphaMode nodes.Output[string] `description:"OPAQUE (default) ignores alpha, MASK cuts at Alpha Cutoff, BLEND blends by alpha. Alpha comes from Color and Color Texture."`
AlphaCutoff nodes.Output[float64] `description:"With alpha mode MASK: alpha below this is cut away. glTF's default is 0.5."`
Unlit nodes.Output[bool] `description:"Shows Color as is, ignoring lighting. Written as KHR_materials_unlit."`
OcclusionTexture nodes.Output[PolyformOcclusion] `description:"Ambient occlusion map, darkening crevices under ambient light." advanced:"true"`
AlphaMode nodes.Output[string] `description:"OPAQUE (default) ignores alpha, MASK cuts at Alpha Cutoff, BLEND blends by alpha. Alpha comes from Color and Color Texture." advanced:"true"`
AlphaCutoff nodes.Output[float64] `description:"With alpha mode MASK: alpha below this is cut away. glTF's default is 0.5." advanced:"true"`
Unlit nodes.Output[bool] `description:"Shows Color as is, ignoring lighting. Written as KHR_materials_unlit." advanced:"true"`

// Extensions
IndexOfRefraction nodes.Output[float64]
Transmission nodes.Output[PolyformTransmission]
Volume nodes.Output[PolyformVolume]
Anisotropy nodes.Output[PolyformAnisotropy]
Clearcoat nodes.Output[PolyformClearcoat]
Sheen nodes.Output[PolyformSheen]
Specular nodes.Output[PolyformSpecular]
Iridescence nodes.Output[PolyformIridescence]
Dispersion nodes.Output[PolyformDispersion]
EmissiveStrength nodes.Output[float64]
IndexOfRefraction nodes.Output[float64] `advanced:"true"`
Transmission nodes.Output[PolyformTransmission] `advanced:"true"`
Volume nodes.Output[PolyformVolume] `advanced:"true"`
Anisotropy nodes.Output[PolyformAnisotropy] `advanced:"true"`
Clearcoat nodes.Output[PolyformClearcoat] `advanced:"true"`
Sheen nodes.Output[PolyformSheen] `advanced:"true"`
Specular nodes.Output[PolyformSpecular] `advanced:"true"`
Iridescence nodes.Output[PolyformIridescence] `advanced:"true"`
Dispersion nodes.Output[PolyformDispersion] `advanced:"true"`
EmissiveStrength nodes.Output[float64] `advanced:"true"`
}

func (gmnd MaterialNode) Out(out *nodes.StructOutput[PolyformMaterial]) {
Expand Down
33 changes: 33 additions & 0 deletions formats/gltf/serialize.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package gltf

import (
"github.com/EliCDavis/polyform/generator/manifest"
"github.com/EliCDavis/polyform/generator/serialize"
"github.com/EliCDavis/polyform/modeling"
)

func RegisterOutputSerializers(ts *serialize.TypeSwitch[manifest.Entry]) {
serialize.Register(ts, func(m modeling.Mesh) manifest.Entry {
return glb([]*PolyformModel{{Name: "Mesh", Mesh: &m}})
})
serialize.Register(ts, func(ms []modeling.Mesh) manifest.Entry {
models := make([]*PolyformModel, 0, len(ms))
for i := range ms {
models = append(models, &PolyformModel{Name: "Mesh", Mesh: &ms[i]})
}
return glb(models)
})
serialize.Register(ts, func(m *PolyformModel) manifest.Entry {
if m == nil {
return glb(nil)
}
return glb([]*PolyformModel{m})
})
serialize.Register(ts, func(ms []*PolyformModel) manifest.Entry {
return glb(ms)
})
}

func glb(models []*PolyformModel) manifest.Entry {
return manifest.Entry{Artifact: Artifact{Scene: PolyformScene{Models: models}}}
}
37 changes: 37 additions & 0 deletions formats/gltf/serialize_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package gltf_test

import (
"bytes"
"testing"

"github.com/EliCDavis/polyform/formats/gltf"
"github.com/EliCDavis/polyform/generator/manifest"
"github.com/EliCDavis/polyform/generator/serialize"
"github.com/EliCDavis/polyform/modeling"
"github.com/EliCDavis/polyform/modeling/primitives"
"github.com/EliCDavis/polyform/nodes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestMeshAndModelOutputsSerializeAsGLB(t *testing.T) {
ts := &serialize.TypeSwitch[manifest.Entry]{}
gltf.RegisterOutputSerializers(ts)

cube := primitives.UnitCube()
ports := []nodes.OutputPort{
nodes.ConstOutput[modeling.Mesh]{Val: cube},
nodes.ConstOutput[[]modeling.Mesh]{Val: []modeling.Mesh{cube, cube}},
nodes.ConstOutput[*gltf.PolyformModel]{Val: &gltf.PolyformModel{Name: "Cube", Mesh: &cube}},
nodes.ConstOutput[[]*gltf.PolyformModel]{Val: []*gltf.PolyformModel{{Name: "Cube", Mesh: &cube}}},
}

for _, port := range ports {
entry := ts.Run(port)
assert.Equal(t, "model/gltf-binary", entry.Artifact.Mime())

var out bytes.Buffer
require.NoError(t, entry.Artifact.Write(&out))
assert.Equal(t, "glTF", out.String()[:4])
}
}
Loading
Loading