diff --git a/renderer1/hrend/image.go b/renderer1/hrend/image.go new file mode 100644 index 0000000..8731ba6 --- /dev/null +++ b/renderer1/hrend/image.go @@ -0,0 +1,142 @@ +package hrend + +import ( + "bytes" + "fmt" + "image" + "image/color" + "log" + "math" + "strings" +) + +// Convert rgb to uint +func Col2Uint(r, g, b byte) uint { + return (uint(r) << 16) | (uint(g) << 8) | uint(b) +} + +func Color2Uint(col color.Color) uint { + r, g, b, _ := col.RGBA() + //log.Print(r, g, b) + return uint(((r & 0xff00) << 8) | (g & 0xff00) | ((b & 0xff00) >> 8)) +} + +// Convert uint to rgb (in that order) +func Uint2Col(col uint) (byte, byte, byte) { + return byte((col >> 16) & 0xFF), byte((col >> 8) & 0xFF), byte(col & 0xFF) +} + +// Color is in ARGB (alpha not used right now) +type Framebuffer struct { + Data []uint + ZBuffer []float32 //uint16 // Apparently 16 bit z-buffers are used + Width uint + Height uint +} + +// Create a new framebuffer for the given width and height. +func NewFramebuffer(width uint, height uint) Framebuffer { + return Framebuffer{ + Data: make([]uint, width*height), + ZBuffer: make([]float32, width*height), + Width: width, + Height: height, + } +} + +func NewTexture(texture image.Image, skip int) Framebuffer { + bounds := texture.Bounds() + width := bounds.Dx() / skip + height := bounds.Dy() / skip + result := Framebuffer{ + Data: make([]uint, width*height), + Width: uint(width), + Height: uint(height), + } + for y := bounds.Min.Y; y < bounds.Max.Y; y += skip { + for x := bounds.Min.X; x < bounds.Max.X; x += skip { + col := texture.At(x, y) + result.Set(uint(x/skip), uint(y/skip), Color2Uint(col)) + } + } + return result +} + +// Fill zbuffer with pixels that are max distance away +func (fb *Framebuffer) ResetZBuffer() { + for i := range fb.ZBuffer { + fb.ZBuffer[i] = 65535 //math.MaxFloat32 + } +} + +func (fb *Framebuffer) GetUv(u float32, v float32) uint { + x := uint(float32(fb.Width)*u) & (fb.Width - 1) + y := uint(float32(fb.Height)*(1-v)) & (fb.Height - 1) + return fb.Data[x+y*fb.Width] +} + +// Sure hope this gets inlined... +func (fb *Framebuffer) Set(x uint, y uint, color uint) { + fb.Data[x+y*fb.Width] = color +} + +func (fb *Framebuffer) SetSafe(x uint, y uint, color uint) { + if x >= fb.Width || y >= fb.Height { + return + } + fb.Data[x+y*fb.Width] = color +} + +// Given some image data, return a string that is the ppm of it +func (fb *Framebuffer) ExportPPM() string { + log.Printf("ExportPPM called for framebuffer %dx%d", fb.Width, fb.Height) + var result strings.Builder + result.WriteString(fmt.Sprintf("P3\n%d %d\n255\n", fb.Width, fb.Height)) + for y := range fb.Height { + for x := range fb.Width { + r, g, b := Uint2Col(fb.Data[x+y*fb.Width]) + result.WriteString(fmt.Sprintf("%d %d %d\t", r, g, b)) + } + result.WriteRune('\n') + } + return result.String() +} + +func (fb *Framebuffer) ExportPPMP6() []byte { + log.Printf("ExportPPM6 called for framebuffer %dx%d", fb.Width, fb.Height) + var result bytes.Buffer + result.WriteString(fmt.Sprintf("P6\n%d %d\n255\n", fb.Width, fb.Height)) + for i := range fb.Data { + r, g, b := Uint2Col(fb.Data[i]) + result.Write([]byte{r, g, b}) + //result.WriteString(fmt.Sprintf("%d %d %d\t", r, g, b)) + } + //result.WriteRune('\n') + return result.Bytes() +} + +func (fb *Framebuffer) ZBuffer_ExportPPM() string { + var result strings.Builder + mini := float32(math.MaxFloat32) + maxi := float32(-math.MaxFloat32) + for _, f := range fb.ZBuffer { + if f == math.MaxFloat32 { + continue + } + mini = min(f, mini) + maxi = max(f, maxi) + } + result.WriteString(fmt.Sprintf("P2\n%d %d\n255\n", fb.Width, fb.Height)) + for y := range fb.Height { + for x := range fb.Width { + if fb.ZBuffer[x+y*fb.Width] == math.MaxFloat32 { + result.WriteString("0 ") + } else { + zp := byte(math.Abs(float64(255 * fb.ZBuffer[x+y*fb.Width] / (maxi - mini)))) + result.WriteString(fmt.Sprintf("%d ", zp)) + } + } + result.WriteRune('\n') + } + return result.String() +} diff --git a/renderer1/hrend/math.go b/renderer1/hrend/math.go new file mode 100644 index 0000000..d89f08c --- /dev/null +++ b/renderer1/hrend/math.go @@ -0,0 +1,159 @@ +package hrend + +// This is the linear algebra junk? Vectors, matrices, etc +import ( + "math" +) + +type Vec3f struct { + X, Y, Z float32 +} + +type Vec2i struct { + X, Y int +} + +type Vec2f struct { + X, Y float32 +} + +// A ROW MAJOR matrix +type Mat44f [16]float32 + +func (m *Mat44f) Set(x int, y int, val float32) { + m[x+y*4] = val +} +func (m *Mat44f) Get(x int, y int) float32 { + return m[x+y*4] +} +func (m *Mat44f) ZeroFill() { + for i := range m { + m[i] = 0 + } +} +func (m *Mat44f) SetIdentity() { + m.ZeroFill() + for i := range 4 { + m.Set(i, i, 1) + } +} + +// NOTE: we use "Set" instead of "Create" for all these so we reuse the matrix +// instead of creating a new one all the time (garbage collection) + +// Compute the projection matrix, filling the given matrix. FOV is in degrees +func (m *Mat44f) SetProjection(fov float32, near float32, far float32) { + // Projection matrix is (ROW MAJOR!) + // S 0 0 0 + // 0 S 0 0 + // 0 0 -f/(f-n) -1 + // 0 0 -fn/(f-n) 0 + // where S (scale) is 1 / tan(fov / 2) (assuming fov is radians) + // NOTE: -1 there is actually -1/c, where c is distance from viewer to + // projection plane. We fix it at 1 for now but... + m.ZeroFill() + scale := float32(1 / math.Tan(float64(fov)*0.5*math.Pi/180)) + m.Set(0, 0, scale) + m.Set(1, 1, scale) + m.Set(2, 2, -far/(far-near)) + m.Set(3, 2, -1) + m.Set(2, 3, -far*near/(far-near)) +} + +func (m *Mat44f) SetTranslation(x, y, z float32) { + m.SetIdentity() + m.Set(0, 3, x) // Let user decide how to offset x + m.Set(1, 3, y) // Let user decide how to offset x + m.Set(2, 3, z) // Get farther away from the face (user) +} + +func (m *Mat44f) SetViewport(tl Vec3f, br Vec3f) { //width, height, depth int) { + m.ZeroFill() + m.Set(0, 0, (br.X-tl.X)/2) + m.Set(1, 1, (tl.Y-br.Y)/2) // Inverted because screen funny + m.Set(2, 2, (br.Z-tl.Z)/2) + m.Set(3, 3, 1) + m.Set(0, 3, (br.X+tl.X)/2) + m.Set(1, 3, (br.Y+tl.Y)/2) + m.Set(2, 3, (br.Z+tl.Z)/2) +} + +func (m *Mat44f) SetViewportSimple(width, height, depth int) { + var tl Vec3f // All zero + br := Vec3f{ + X: float32(width), + Y: float32(height), + Z: float32(depth), + } + m.SetViewport(tl, br) +} + +// Multiply the given point by our vector. Remember this is row-major order +func (m *Mat44f) MultiplyPoint3(p Vec3f) Vec3f { + var out Vec3f + // We hope very much that Go will optimize the function calls for us, + // along with computing the constants. + out.X = p.X*m.Get(0, 0) + p.Y*m.Get(0, 1) + p.Z*m.Get(0, 2) + m.Get(0, 3) + out.Y = p.X*m.Get(1, 0) + p.Y*m.Get(1, 1) + p.Z*m.Get(1, 2) + m.Get(1, 3) + out.Z = p.X*m.Get(2, 0) + p.Y*m.Get(2, 1) + p.Z*m.Get(2, 2) + m.Get(2, 3) + w := p.X*m.Get(3, 0) + p.Y*m.Get(3, 1) + p.Z*m.Get(3, 2) + m.Get(3, 3) + if w != 1 { + out.X /= w + out.Y /= w + out.Z /= w + } + return out +} + +// Multiply two 4x4 matrices together (not optimized) +func (m *Mat44f) Multiply(m2 *Mat44f) Mat44f { + var result Mat44f + // This is the x and y of our resulting matrix + for y := 0; y < 4; y++ { + for x := 0; x < 4; x++ { + for i := 0; i < 4; i++ { + result[x+y*4] += m[i+y*4] * m2[x+i*4] + } + } + } + return result +} + +func (vi *Vec2i) ToF() Vec2f { + return Vec2f{float32(vi.X), float32(vi.Y)} +} + +func (vi *Vec3f) ToVec2i() Vec2i { + return Vec2i{int(vi.X), int(vi.Y)} +} + +func (v0 *Vec3f) Sub(v1 Vec3f) Vec3f { + return Vec3f{ + X: v0.X - v1.X, + Y: v0.Y - v1.Y, + Z: v0.Z - v1.Z, + } +} + +func (v0 *Vec3f) CrossProduct(v1 Vec3f) Vec3f { + return Vec3f{ + X: v0.Y*v1.Z - v0.Z*v1.Y, + Y: v0.Z*v1.X - v0.X*v1.Z, + Z: v0.X*v1.Y - v0.Y*v1.X, + } +} + +//func (v + +func (v *Vec3f) Normalize() Vec3f { + l := float32(math.Sqrt(float64(v.MultSimp(v)))) + return Vec3f{ + X: v.X / l, + Y: v.Y / l, + Z: v.Z / l, + } +} + +func (v0 *Vec3f) MultSimp(v1 *Vec3f) float32 { + return v0.X*v1.X + v0.Y*v1.Y + v0.Z*v1.Z +} diff --git a/renderer1/hrend/obj.go b/renderer1/hrend/obj.go new file mode 100644 index 0000000..6d48355 --- /dev/null +++ b/renderer1/hrend/obj.go @@ -0,0 +1,107 @@ +package hrend + +// This reads obj files? +import ( + "bufio" + "fmt" + "io" + "log" + "strings" +) + +// A single vertex generally has multiple items associated with it +// when it's part of a face. +type Vertex struct { + Pos Vec3f + Tex Vec3f +} + +type Facef [3]Vertex + +// struct { +// Vertices [3]Vec3f +// TextureCoords [3]Vec2i +// } + +type ObjModel struct { + Vertices []Vec3f + VTexture []Vec3f + Faces []Facef +} + +// Parse an obj file at the given reader. Only handles v and f right now +func ParseObj(reader io.Reader) (*ObjModel, error) { + result := ObjModel{ + Vertices: make([]Vec3f, 0), + Faces: make([]Facef, 0), + } + breader := bufio.NewReader(reader) + done := false + for !done { + // Scan a line + 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 + } + // 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 + _, err = fmt.Sscan(line, &t) + if err != nil { + log.Printf("SSCANF ERR") + return nil, err + } + line = line[len(t):] + if t == "v" { + // Read a vertex, should be just three floats + var v Vec3f + _, err := fmt.Sscan(line, &v.X, &v.Y, &v.Z) + if err != nil { + return nil, err + } + result.Vertices = append(result.Vertices, v) + } else if t == "vt" { + // Read a vertex tex coord, should be just three floats too + var vt Vec3f + _, err := fmt.Sscan(line, &vt.X, &vt.Y, &vt.Z) + if err != nil { + return nil, err + } + result.VTexture = append(result.VTexture, vt) + } 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 + var vi [3]int + var vti [3]int + var ti int + _, err := fmt.Sscanf(line, "%d/%d/%d %d/%d/%d %d/%d/%d", + &vi[0], &vti[0], &ti, &vi[1], &vti[1], &ti, &vi[2], &vti[2], &ti) + if err != nil { + return nil, err + } + for i := range 3 { + if vi[i] > len(result.Vertices) || vi[i] < 1 { + return nil, fmt.Errorf("Face vertex index out of bounds: %d", vi[i]) + } + face[i].Pos = result.Vertices[vi[i]-1] + if vti[i] > len(result.VTexture) || vti[i] < 1 { + return nil, fmt.Errorf("Face vertex texture index out of bounds: %d", vti[i]) + } + face[i].Tex = result.VTexture[vti[i]-1] + } + result.Faces = append(result.Faces, face) + } + } + log.Printf("Obj had %d vertices, %d faces", len(result.Vertices), len(result.Faces)) + return &result, nil +} diff --git a/renderer1/hrend/render.go b/renderer1/hrend/render.go new file mode 100644 index 0000000..db8a85c --- /dev/null +++ b/renderer1/hrend/render.go @@ -0,0 +1,163 @@ +package hrend + +import ( +// "log" +) + +// Figure out the minimum bounding box for a triangle defined by +// these vertices. Returns the top left and bottom right points, +// inclusive +func ComputeBoundingBox(v0, v1, v2 Vec2i) (Vec2i, Vec2i) { + return Vec2i{min(v0.X, v1.X, v2.X), min(v0.Y, v1.Y, v2.Y)}, + Vec2i{max(v0.X, v1.X, v2.X), max(v0.Y, v1.Y, v2.Y)} +} + +// The generic edge function, returning positive if P is on the right side of +// the line drawn between v1 and v2. This is counter clockwise +func EdgeFunction(v1, v2, p Vec2f) float32 { + return (p.X-v1.X)*(v2.Y-v1.Y) - (p.Y-v1.Y)*(v2.X-v1.X) +} + +// This computes the x and y per-pixel increment for the line going +// between v1 and v2 (also counter clockwise) +func EdgeIncrement(v1, v2 Vec2f) (float32, float32) { + return (v2.Y - v1.Y), -(v2.X - v1.X) +} + +// The generic edge function, returning positive if P is on the right side of +// the line drawn between v1 and v2. This is counter clockwise +func EdgeFunctioni(v1, v2, p Vec2i) int { + return (p.X-v1.X)*(v2.Y-v1.Y) - (p.Y-v1.Y)*(v2.X-v1.X) +} + +// This computes the x and y per-pixel increment for the line going +// between v1 and v2 (also counter clockwise) +func EdgeIncrementi(v1, v2 Vec2i) (int, int) { + return (v2.Y - v1.Y), -(v2.X - v1.X) +} + +func TriangleFlat(fb *Framebuffer, color uint, v0f Vec3f, v1f Vec3f, v2f Vec3f) { + v0 := v0f.ToVec2i() + v1 := v1f.ToVec2i() + v2 := v2f.ToVec2i() + boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2) + if boundsTL.Y < 0 { + boundsTL.Y = 0 + } + if boundsTL.X < 0 { + boundsTL.X = 0 + } + if boundsBR.Y >= int(fb.Height) { + boundsBR.Y = int(fb.Height - 1) + } + if boundsBR.X >= int(fb.Width) { + boundsBR.X = int(fb.Width - 1) + } + // Where to start our scanning + pstart := Vec2i{boundsTL.X, boundsTL.Y} + parea := EdgeFunctioni(v0, v1, v2) + // if parea < 0 { + // v1, v2 = v2, v1 + // v1f, v2f = v2f, v1f + // parea = EdgeFunctioni(v0, v1, v2) + // } + invarea := 1 / float32(parea) + w0_y := EdgeFunctioni(v1, v2, pstart) + w1_y := EdgeFunctioni(v2, v0, pstart) + w2_y := EdgeFunctioni(v0, v1, pstart) + w0_xi, w0_yi := EdgeIncrementi(v1, v2) + w1_xi, w1_yi := EdgeIncrementi(v2, v0) + w2_xi, w2_yi := EdgeIncrementi(v0, v1) + + for y := uint(boundsTL.Y); y <= uint(boundsBR.Y); y++ { + w0 := w0_y + w1 := w1_y + w2 := w2_y + for x := uint(boundsTL.X); x <= uint(boundsBR.X); x++ { + if (w0 | w1 | w2) >= 0 { + //fb.Data[di] = color + //done = true + w0a := float32(w0) * invarea + w1a := float32(w1) * invarea + w2a := float32(w2) * invarea + pz := w0a*v0f.Z + w1a*v1f.Z + w2a*v2f.Z + if pz < fb.ZBuffer[x+y*fb.Width] { + //log.Print(pz) + fb.ZBuffer[x+y*fb.Width] = pz + fb.Set(x, y, color) + } + // fb.Set(x, y, Col2Uint(byte(255*w0a), byte(255*w1a), byte(255*w2a))) + } + w0 += w0_xi + w1 += w1_xi + w2 += w2_xi + } + w0_y += w0_yi + w1_y += w1_yi + w2_y += w2_yi + } +} + +func TriangleTextured(fb *Framebuffer, texture *Framebuffer, intensity float32, v0v Vertex, v1v Vertex, v2v Vertex) { + v0 := v0v.Pos.ToVec2i() + v1 := v1v.Pos.ToVec2i() + v2 := v2v.Pos.ToVec2i() + boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2) + if boundsBR.Y < 0 || boundsBR.X < 0 || boundsTL.X >= int(fb.Width) || boundsTL.Y >= int(fb.Height) { + return + } + parea := EdgeFunctioni(v0, v1, v2) + if parea == 0 { + return + } + if boundsTL.Y < 0 { + boundsTL.Y = 0 + } + if boundsTL.X < 0 { + boundsTL.X = 0 + } + if boundsBR.Y >= int(fb.Height) { + boundsBR.Y = int(fb.Height - 1) + } + if boundsBR.X >= int(fb.Width) { + boundsBR.X = int(fb.Width - 1) + } + // Where to start our scanning + pstart := Vec2i{boundsTL.X, boundsTL.Y} + invarea := 1 / float32(parea) + w0_y := EdgeFunctioni(v1, v2, pstart) + w1_y := EdgeFunctioni(v2, v0, pstart) + w2_y := EdgeFunctioni(v0, v1, pstart) + w0_xi, w0_yi := EdgeIncrementi(v1, v2) + w1_xi, w1_yi := EdgeIncrementi(v2, v0) + w2_xi, w2_yi := EdgeIncrementi(v0, v1) + + for y := uint(boundsTL.Y); y <= uint(boundsBR.Y); y++ { + w0 := w0_y + w1 := w1_y + w2 := w2_y + for x := uint(boundsTL.X); x <= uint(boundsBR.X); x++ { + if (w0 | w1 | w2) >= 0 { + w0a := float32(w0) * invarea + w1a := float32(w1) * invarea + w2a := float32(w2) * invarea + pz := w0a*v0v.Pos.Z + w1a*v1v.Pos.Z + w2a*v2v.Pos.Z + if pz < fb.ZBuffer[x+y*fb.Width] { + fb.ZBuffer[x+y*fb.Width] = pz + col := texture.GetUv( + (w0a*v0v.Tex.X + w1a*v1v.Tex.X + w2a*v2v.Tex.X), + (w0a*v0v.Tex.Y + w1a*v1v.Tex.Y + w2a*v2v.Tex.Y), + ) + r, g, b := Uint2Col(col) + fb.Set(x, y, Col2Uint(byte(float32(r)*intensity), byte(float32(g)*intensity), byte(float32(b)*intensity))) //uint(texture.Bounds().Dx()) + } + } + w0 += w0_xi + w1 += w1_xi + w2 += w2_xi + } + w0_y += w0_yi + w1_y += w1_yi + w2_y += w2_yi + } +} diff --git a/renderer1/main.go b/renderer1/main.go index 9868f30..12ddc5d 100644 --- a/renderer1/main.go +++ b/renderer1/main.go @@ -1,15 +1,64 @@ package main import ( + "flag" + "log" + "os" + "renderer1/hrend" + "runtime/pprof" // For performance profiling (unnecessary) + rl "github.com/gen2brain/raylib-go/raylib" ) +const ( + Width = 640 + Height = 480 + NearClip = 0.1 + FarClip = 100 + FOV = 90.0 + ZOffset = -1.5 + ObjectFile = "head.obj" + TextureFile = "../head.jpg" +) + +func must(err error) { + if err != nil { + panic(err) + } +} + +// However flag works... idk +var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") + +// var dozbuf = flag.Bool("zbuffer", false, "Write zbuffer instead of image") +// var p6file = flag.String("p6file", "", "Output binary ppm to given file instead") +// var fov = flag.Float64("fov", 90, "Horizontal FOV in degrees") +// var xofs = flag.Float64("xofs", 0, "Offset image by x") +// var zofs = flag.Float64("zofs", -1.5, "Offset image by z (should be negative)") +// var repeat = flag.Int("repeat", 60, "Amount of times to repeat render") + func main() { - rl.InitWindow(800, 450, "raylib [core] example - basic window") + log.Printf("Program start") + + flag.Parse() + if *cpuprofile != "" { + log.Printf("CPU profiling requested, write to %s", *cpuprofile) + f, err := os.Create(*cpuprofile) + must(err) + defer f.Close() + err = pprof.StartCPUProfile(f) + must(err) + defer pprof.StopCPUProfile() + } + + rl.InitWindow(Width, Height, "Simple renderer with raylib") defer rl.CloseWindow() rl.SetTargetFPS(60) + var thing hrend.Vec2i + log.Print(thing) + for !rl.WindowShouldClose() { rl.BeginDrawing()