3dtrial/tinyrender1/obj.go

85 lines
1.9 KiB
Go
Raw Normal View History

2024-07-24 02:27:01 +00:00
package main
// This reads obj files?
import (
"bufio"
"fmt"
"io"
2024-07-24 02:53:18 +00:00
"log"
2024-07-24 02:27:01 +00:00
"strings"
)
type Vec3f struct {
X, Y, Z float32
}
type Facef [3]Vec3f
type ObjModel struct {
Vertices []Vec3f
Faces []Facef
}
2024-07-24 02:53:18 +00:00
// Parse an obj file at the given reader. Only handles v and f right now
2024-07-24 02:27:01 +00:00
func ParseObj(reader io.Reader) (*ObjModel, error) {
result := ObjModel{
Vertices: make([]Vec3f, 0),
Faces: make([]Facef, 0),
}
2024-07-24 02:53:18 +00:00
breader := bufio.NewReader(reader)
done := false
for !done {
2024-07-24 02:27:01 +00:00
// Scan a line
2024-07-24 02:53:18 +00:00
line, err := breader.ReadString('\n')
if err != nil {
if err == io.EOF {
done = true
} else {
log.Printf("NOT EOF ERR?")
return nil, err
}
}
line = strings.Trim(line, " \t\n\r")
if len(line) == 0 {
continue
}
2024-07-24 02:27:01 +00:00
// Find the first "item", whatever that is. This also gets rid of comments
// since we just don't use lines that start with # (no handler
var t string
2024-07-24 02:53:18 +00:00
_, err = fmt.Sscan(line, &t)
2024-07-24 02:27:01 +00:00
if err != nil {
2024-07-24 02:53:18 +00:00
log.Printf("SSCANF ERR")
2024-07-24 02:27:01 +00:00
return nil, err
}
line = line[len(t):]
if t == "v" {
// Read a vertex, should be just three floats
var vertex Vec3f
2024-07-24 02:53:18 +00:00
_, err := fmt.Sscan(line, &vertex.X, &vertex.Y, &vertex.Z)
2024-07-24 02:27:01 +00:00
if err != nil {
return nil, err
}
result.Vertices = append(result.Vertices, vertex)
} else if t == "f" {
// Read a face; in our example, it's always three sets.
// For THIS example, we throw away those other values
var face Facef
2024-07-24 03:01:31 +00:00
var vi [3]int
var ti int
_, err := fmt.Sscanf(line, "%d/%d/%d %d/%d/%d %d/%d/%d",
&vi[0], &ti, &ti, &vi[1], &ti, &ti, &vi[2], &ti, &ti)
if err != nil {
return nil, err
}
2024-07-24 02:27:01 +00:00
for i := range 3 {
2024-07-24 03:01:31 +00:00
if vi[i] > len(result.Vertices) || vi[i] < 1 {
return nil, fmt.Errorf("Face vertex index out of bounds: %d", vi[i])
2024-07-24 02:27:01 +00:00
}
2024-07-24 03:01:31 +00:00
face[i] = result.Vertices[vi[i]-1]
2024-07-24 02:27:01 +00:00
}
result.Faces = append(result.Faces, face)
}
}
return &result, nil
}