From 27874d042f2b9898242ef594e4ca506d562d2132 Mon Sep 17 00:00:00 2001 From: Carlos Sanchez Date: Sun, 4 Aug 2024 09:35:47 -0400 Subject: [PATCH] Beginning clipspace --- renderer3/.gitignore | 3 + renderer3/generation.go | 168 +++++++++++++++++ renderer3/go.mod | 11 ++ renderer3/go.sum | 8 + renderer3/hrend/frametime.go | 27 +++ renderer3/hrend/image.go | 195 ++++++++++++++++++++ renderer3/hrend/math.go | 345 +++++++++++++++++++++++++++++++++++ renderer3/hrend/obj.go | 108 +++++++++++ renderer3/hrend/render.go | 214 ++++++++++++++++++++++ renderer3/main.go | 295 ++++++++++++++++++++++++++++++ renderer3/raybuffer.go | 64 +++++++ renderer3/runopengl21.sh | 3 + 12 files changed, 1441 insertions(+) create mode 100644 renderer3/.gitignore create mode 100644 renderer3/generation.go create mode 100644 renderer3/go.mod create mode 100644 renderer3/go.sum create mode 100644 renderer3/hrend/frametime.go create mode 100644 renderer3/hrend/image.go create mode 100644 renderer3/hrend/math.go create mode 100644 renderer3/hrend/obj.go create mode 100644 renderer3/hrend/render.go create mode 100644 renderer3/main.go create mode 100644 renderer3/raybuffer.go create mode 100755 renderer3/runopengl21.sh diff --git a/renderer3/.gitignore b/renderer3/.gitignore new file mode 100644 index 0000000..61a37db --- /dev/null +++ b/renderer3/.gitignore @@ -0,0 +1,3 @@ +renderer3 +renderer2 +renderer diff --git a/renderer3/generation.go b/renderer3/generation.go new file mode 100644 index 0000000..08822e2 --- /dev/null +++ b/renderer3/generation.go @@ -0,0 +1,168 @@ +package main + +import ( + "image" + "image/color" + "renderer3/hrend" +) + +func Checkerboard(cols []color.Color, size int) image.Image { + result := image.NewRGBA(image.Rect(0, 0, size, size)) + for y := range size { + for x := range size { + result.Set(x, y, cols[(x+y)%len(cols)]) + } + } + return result +} + +// Returns a sizexsize*3 texture where the top is the top color, +// bottom is bottom color, middle is gradient +func Gradient(bottom color.Color, top color.Color, size int) image.Image { + result := image.NewRGBA(image.Rect(0, 0, size, size*3)) + br, bg, bb, ba := bottom.RGBA() + tr, tg, tb, ta := top.RGBA() + for y := range size { + for x := range size { + lerp := float32(y) / float32(size-1) + result.Set(x, y, top) + result.Set(x, y+size, color.RGBA{ + R: byte(float32(tr>>8)*(1-lerp) + float32(br>>8)*lerp), + G: byte(float32(tg>>8)*(1-lerp) + float32(bg>>8)*lerp), + B: byte(float32(tb>>8)*(1-lerp) + float32(bb>>8)*lerp), + A: byte(float32(ta>>8)*(1-lerp) + float32(ba>>8)*lerp), + }) + result.Set(x, y+size*2, bottom) + } + } + return result +} + +// Returns a 1px wide gradient where top is top color, bottom is bottom color +func Gradient1px(bottom color.Color, top color.Color, size int) image.Image { + result := image.NewRGBA(image.Rect(0, 0, 1, size)) + br, bg, bb, ba := bottom.RGBA() + tr, tg, tb, ta := top.RGBA() + for y := range size { + lerp := float32(y) / float32(size-1) + result.Set(0, y, color.RGBA{ + R: byte(float32(tr>>8)*(1-lerp) + float32(br>>8)*lerp), + G: byte(float32(tg>>8)*(1-lerp) + float32(bg>>8)*lerp), + B: byte(float32(tb>>8)*(1-lerp) + float32(bb>>8)*lerp), + A: byte(float32(ta>>8)*(1-lerp) + float32(ba>>8)*lerp), + }) + } + return result +} + +// Skybox for now assumes a 1px gradient +func Skybox() *hrend.ObjModel { + v := make([]hrend.Vec3f, 8) + vt := make([]hrend.Vec3f, 2) + f := make([]hrend.Facef, 12) + // Assuming 1px gradient, these are the only two texture points you need + vt[0] = hrend.Vec3f{X: 0, Y: 0, Z: 0} + vt[1] = hrend.Vec3f{X: 0, Y: 1, Z: 0} + vvt := []hrend.Vec3f{ + vt[0], vt[0], vt[0], vt[0], vt[1], vt[1], vt[1], vt[1], + } + // Cube faces are weird, I guess just manually do them? ugh + // First 4 are the bottom vertices. We can make two faces out of these + v[0] = hrend.Vec3f{X: float32(-1), Y: float32(-1), Z: float32(-1)} + v[1] = hrend.Vec3f{X: float32(1), Y: float32(-1), Z: float32(-1)} + v[2] = hrend.Vec3f{X: float32(1), Y: float32(-1), Z: float32(1)} + v[3] = hrend.Vec3f{X: float32(-1), Y: float32(-1), Z: float32(1)} + // Now the top 4 vertices, same order as bottom + v[4] = hrend.Vec3f{X: float32(-1), Y: float32(1), Z: float32(-1)} + v[5] = hrend.Vec3f{X: float32(1), Y: float32(1), Z: float32(-1)} + v[6] = hrend.Vec3f{X: float32(1), Y: float32(1), Z: float32(1)} + v[7] = hrend.Vec3f{X: float32(-1), Y: float32(1), Z: float32(1)} + // These are our 12 faces + fv := [][3]int{ + {0, 2, 1}, // bottom + {1, 2, 3}, + {4, 5, 6}, // top + {6, 7, 4}, + {0, 1, 5}, // south + {5, 4, 0}, + {1, 2, 6}, // east + {6, 5, 1}, + {2, 3, 7}, // North + {7, 6, 2}, + {3, 0, 4}, // west + {4, 7, 3}, + } + for i, face := range fv { + for j := range 3 { + f[i][j] = hrend.Vertex{Pos: v[face[j]], Tex: vvt[face[j]]} + } + } + // Now the bottom 2 faces + // f[0] = hrend.Facef{ + // hrend.Vertex{Pos: v[0], Tex: vt[0]}, + // hrend.Vertex{Pos: v[1], Tex: vt[0]}, + // hrend.Vertex{Pos: v[2], Tex: vt[0]}, + // } + // f[1] = hrend.Facef{ + // hrend.Vertex{Pos: v[2], Tex: vt[0]}, + // hrend.Vertex{Pos: v[3], Tex: vt[0]}, + // hrend.Vertex{Pos: v[0], Tex: vt[0]}, + // } + // // Top 2 faces + // f[3] = hrend.Facef{ + // hrend.Vertex{Pos: v[4], Tex: vt[1]}, + // hrend.Vertex{Pos: v[5], Tex: vt[1]}, + // hrend.Vertex{Pos: v[6], Tex: vt[1]}, + // } + // f[4] = hrend.Facef{ + // hrend.Vertex{Pos: v[6], Tex: vt[1]}, + // hrend.Vertex{Pos: v[7], Tex: vt[1]}, + // hrend.Vertex{Pos: v[4], Tex: vt[1]}, + // } + // Ugh and now the sides... so complicated + return &hrend.ObjModel{ + Vertices: v, + VTexture: vt, + Faces: f, + } +} + +func FlatTerrain(size int) *hrend.ObjModel { + result := hrend.ObjModel{ + Vertices: make([]hrend.Vec3f, 0), + VTexture: make([]hrend.Vec3f, 4), + Faces: make([]hrend.Facef, 0), + } + // For the simple square terrain, there aren't a lot of texture coords... + result.VTexture[0] = hrend.Vec3f{X: 0, Y: 0, Z: 0} + result.VTexture[1] = hrend.Vec3f{X: 1, Y: 0, Z: 0} + result.VTexture[2] = hrend.Vec3f{X: 0, Y: 1, Z: 0} + result.VTexture[3] = hrend.Vec3f{X: 1, Y: 1, Z: 0} + // Generate all the simple vertices along the plane at y=0 + for z := -size; z <= size; z++ { + for x := -size; x <= size; x++ { + result.Vertices = append(result.Vertices, hrend.Vec3f{X: float32(x), Y: 0, Z: float32(z)}) + } + } + width := size + size + 1 + // Faces are slightly different; we generate two for every "cell" inside the vertices + for z := 0; z < width-1; z++ { + for x := 0; x < width-1; x++ { + topleft := x + z*width + topright := x + 1 + z*width + bottomleft := x + (z+1)*width + bottomright := x + 1 + (z+1)*width + // remember to wind counter-clockwise + result.Faces = append(result.Faces, hrend.Facef{ + hrend.Vertex{Pos: result.Vertices[topleft], Tex: result.VTexture[0]}, + hrend.Vertex{Pos: result.Vertices[bottomleft], Tex: result.VTexture[2]}, + hrend.Vertex{Pos: result.Vertices[topright], Tex: result.VTexture[1]}, + }, hrend.Facef{ + hrend.Vertex{Pos: result.Vertices[topright], Tex: result.VTexture[1]}, + hrend.Vertex{Pos: result.Vertices[bottomleft], Tex: result.VTexture[2]}, + hrend.Vertex{Pos: result.Vertices[bottomright], Tex: result.VTexture[3]}, + }) + } + } + return &result +} diff --git a/renderer3/go.mod b/renderer3/go.mod new file mode 100644 index 0000000..4cab5bb --- /dev/null +++ b/renderer3/go.mod @@ -0,0 +1,11 @@ +module renderer3 + +go 1.22.5 + +require github.com/gen2brain/raylib-go/raylib v0.0.0-20240628125141-62016ee92fc0 + +require ( + github.com/ebitengine/purego v0.7.1 // indirect + golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect + golang.org/x/sys v0.20.0 // indirect +) diff --git a/renderer3/go.sum b/renderer3/go.sum new file mode 100644 index 0000000..d39cac3 --- /dev/null +++ b/renderer3/go.sum @@ -0,0 +1,8 @@ +github.com/ebitengine/purego v0.7.1 h1:6/55d26lG3o9VCZX8lping+bZcmShseiqlh2bnUDiPA= +github.com/ebitengine/purego v0.7.1/go.mod h1:ah1In8AOtksoNK6yk5z1HTJeUkC1Ez4Wk2idgGslMwQ= +github.com/gen2brain/raylib-go/raylib v0.0.0-20240628125141-62016ee92fc0 h1:mhWZabwn9WvzqMBgiuW8ewuQ4Zg+PfW+XbNnTtIX1FY= +github.com/gen2brain/raylib-go/raylib v0.0.0-20240628125141-62016ee92fc0/go.mod h1:BaY76bZk7nw1/kVOSQObPY1v1iwVE1KHAGMfvI6oK1Q= +golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM= +golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/renderer3/hrend/frametime.go b/renderer3/hrend/frametime.go new file mode 100644 index 0000000..cd61fca --- /dev/null +++ b/renderer3/hrend/frametime.go @@ -0,0 +1,27 @@ +package hrend + +import ( + "time" +) + +// Sum up and average frame times at desired intervals. Average and sum +// should be seconds +type FrameTimer struct { + Sum time.Duration + TotalTime time.Duration + Count int + TotalCount int + LastAverage time.Duration +} + +func (ft *FrameTimer) Add(t time.Duration, avgcount int) { + ft.Sum += t + ft.TotalTime += t + ft.Count += 1 + ft.TotalCount += 1 + if ft.Count%avgcount == 0 { + ft.LastAverage = ft.Sum / time.Duration(ft.Count) + ft.Sum = 0 + ft.Count = 0 + } +} diff --git a/renderer3/hrend/image.go b/renderer3/hrend/image.go new file mode 100644 index 0000000..33617ca --- /dev/null +++ b/renderer3/hrend/image.go @@ -0,0 +1,195 @@ +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) +} + +// A simple buffer where you can set pixels +type Framebuffer interface { + Set(x uint, y uint, r byte, g byte, b byte) + Get(x uint, y uint) (byte, byte, byte) + GetUv(u float32, v float32) (byte, byte, byte) + Dims() (uint, uint) +} + +// Turn framebuffer into image, useful for processing into individual frames +func ToImage(fb Framebuffer) *image.RGBA { + width, height := fb.Dims() + result := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) + for y := range height { + for x := range width { + c := color.RGBA{A: 255} + c.R, c.G, c.G = fb.Get(x, y) + result.Set(int(x), int(y), c) + } + } + return result +} + +// Color is in RGB (alpha not used right now) +type SimpleFramebuffer struct { + Data []byte + Width uint + Height uint +} + +func (fb *SimpleFramebuffer) Dims() (uint, uint) { + return fb.Width, fb.Height +} + +// Sure hope this gets inlined... +func (fb *SimpleFramebuffer) Set(x uint, y uint, r byte, g byte, b byte) { + if x >= fb.Width || y >= fb.Height { + return + } + fb.Data[(x+y*fb.Width)*3] = r + fb.Data[(x+y*fb.Width)*3+1] = g + fb.Data[(x+y*fb.Width)*3+2] = b +} + +func (fb *SimpleFramebuffer) Get(x uint, y uint) (byte, byte, byte) { + if x >= fb.Width || y >= fb.Height { + return 0, 0, 0 + } + return fb.Data[(x+y*fb.Width)*3], + fb.Data[(x+y*fb.Width)*3+1], + fb.Data[(x+y*fb.Width)*3+2] +} + +func (fb *SimpleFramebuffer) GetUv(u float32, v float32) (byte, byte, byte) { + 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)*3], + fb.Data[(x+y*fb.Width)*3+1], + fb.Data[(x+y*fb.Width)*3+2] +} + +func NewSimpleFramebuffer(width uint, height uint) *SimpleFramebuffer { + return &SimpleFramebuffer{ + Data: make([]byte, width*height*3), + Width: width, + Height: height, + } +} + +type RenderBuffer struct { + Data Framebuffer + 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 NewRenderbuffer(d Framebuffer, width uint, height uint) RenderBuffer { + return RenderBuffer{ + Data: d, + ZBuffer: make([]float32, width*height), + Width: width, + Height: height, + } +} + +func NewTexture(texture image.Image, stride int) *SimpleFramebuffer { + bounds := texture.Bounds() + width := bounds.Dx() / stride + height := bounds.Dy() / stride + result := NewSimpleFramebuffer(uint(width), uint(height)) + wlog := math.Log2(float64(width)) + hlog := math.Log2(float64(height)) + if wlog != math.Floor(wlog) || hlog != math.Floor(hlog) { + panic("Texture must be power of two") + } + for y := bounds.Min.Y; y < bounds.Max.Y; y += stride { + for x := bounds.Min.X; x < bounds.Max.X; x += stride { + col := texture.At(x, y) + r, g, b, _ := col.RGBA() + result.Set(uint(x/stride), uint(y/stride), byte(r>>8), byte(g>>8), byte(b>>8)) + } + } + return result +} + +// Fill zbuffer with pixels that are max distance away +func (fb *RenderBuffer) ResetZBuffer() { + for i := range fb.ZBuffer { + fb.ZBuffer[i] = 65535 //math.MaxFloat32 + } +} + +// Given some image data, return a string that is the ppm of it +func (fb *RenderBuffer) 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 := fb.Data.Get(x, y) + result.WriteString(fmt.Sprintf("%d %d %d\t", r, g, b)) + } + result.WriteRune('\n') + } + return result.String() +} + +func (fb *RenderBuffer) 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 y := range fb.Height { + for x := range fb.Width { + r, g, b := fb.Data.Get(x, y) + 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 *RenderBuffer) 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/renderer3/hrend/math.go b/renderer3/hrend/math.go new file mode 100644 index 0000000..aeeddff --- /dev/null +++ b/renderer3/hrend/math.go @@ -0,0 +1,345 @@ +package hrend + +// This is the linear algebra junk? Vectors, matrices, etc +import ( + //"log" + "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 + } +} + +// Multiply the entire matrix by the given value +func (m *Mat44f) MultiplySelf(f float32) { + for i := range m { + m[i] *= f + } +} + +// Copied from https://github.com/go-gl/mathgl/blob/master/mgl32/matrix.go +func (m *Mat44f) Determinant() float32 { + return m[0]*m[5]*m[10]*m[15] - m[0]*m[5]*m[11]*m[14] - m[0]*m[6]*m[9]*m[15] + m[0]*m[6]*m[11]*m[13] + m[0]*m[7]*m[9]*m[14] - m[0]*m[7]*m[10]*m[13] - m[1]*m[4]*m[10]*m[15] + m[1]*m[4]*m[11]*m[14] + m[1]*m[6]*m[8]*m[15] - m[1]*m[6]*m[11]*m[12] - m[1]*m[7]*m[8]*m[14] + m[1]*m[7]*m[10]*m[12] + m[2]*m[4]*m[9]*m[15] - m[2]*m[4]*m[11]*m[13] - m[2]*m[5]*m[8]*m[15] + m[2]*m[5]*m[11]*m[12] + m[2]*m[7]*m[8]*m[13] - m[2]*m[7]*m[9]*m[12] - m[3]*m[4]*m[9]*m[14] + m[3]*m[4]*m[10]*m[13] + m[3]*m[5]*m[8]*m[14] - m[3]*m[5]*m[10]*m[12] - m[3]*m[6]*m[8]*m[13] + m[3]*m[6]*m[9]*m[12] +} + +// Copied from https://github.com/go-gl/mathgl/blob/master/mgl32/matrix.go +func (m *Mat44f) Inverse() *Mat44f { + det := m.Determinant() + + if det == float32(0.0) { + return &Mat44f{} + } + + // How the hell am I supposed to know if this is correct? Oh well... + result := Mat44f{ + -m[7]*m[10]*m[13] + m[6]*m[11]*m[13] + m[7]*m[9]*m[14] - m[5]*m[11]*m[14] - m[6]*m[9]*m[15] + m[5]*m[10]*m[15], + m[3]*m[10]*m[13] - m[2]*m[11]*m[13] - m[3]*m[9]*m[14] + m[1]*m[11]*m[14] + m[2]*m[9]*m[15] - m[1]*m[10]*m[15], + -m[3]*m[6]*m[13] + m[2]*m[7]*m[13] + m[3]*m[5]*m[14] - m[1]*m[7]*m[14] - m[2]*m[5]*m[15] + m[1]*m[6]*m[15], + m[3]*m[6]*m[9] - m[2]*m[7]*m[9] - m[3]*m[5]*m[10] + m[1]*m[7]*m[10] + m[2]*m[5]*m[11] - m[1]*m[6]*m[11], + m[7]*m[10]*m[12] - m[6]*m[11]*m[12] - m[7]*m[8]*m[14] + m[4]*m[11]*m[14] + m[6]*m[8]*m[15] - m[4]*m[10]*m[15], + -m[3]*m[10]*m[12] + m[2]*m[11]*m[12] + m[3]*m[8]*m[14] - m[0]*m[11]*m[14] - m[2]*m[8]*m[15] + m[0]*m[10]*m[15], + m[3]*m[6]*m[12] - m[2]*m[7]*m[12] - m[3]*m[4]*m[14] + m[0]*m[7]*m[14] + m[2]*m[4]*m[15] - m[0]*m[6]*m[15], + -m[3]*m[6]*m[8] + m[2]*m[7]*m[8] + m[3]*m[4]*m[10] - m[0]*m[7]*m[10] - m[2]*m[4]*m[11] + m[0]*m[6]*m[11], + -m[7]*m[9]*m[12] + m[5]*m[11]*m[12] + m[7]*m[8]*m[13] - m[4]*m[11]*m[13] - m[5]*m[8]*m[15] + m[4]*m[9]*m[15], + m[3]*m[9]*m[12] - m[1]*m[11]*m[12] - m[3]*m[8]*m[13] + m[0]*m[11]*m[13] + m[1]*m[8]*m[15] - m[0]*m[9]*m[15], + -m[3]*m[5]*m[12] + m[1]*m[7]*m[12] + m[3]*m[4]*m[13] - m[0]*m[7]*m[13] - m[1]*m[4]*m[15] + m[0]*m[5]*m[15], + m[3]*m[5]*m[8] - m[1]*m[7]*m[8] - m[3]*m[4]*m[9] + m[0]*m[7]*m[9] + m[1]*m[4]*m[11] - m[0]*m[5]*m[11], + m[6]*m[9]*m[12] - m[5]*m[10]*m[12] - m[6]*m[8]*m[13] + m[4]*m[10]*m[13] + m[5]*m[8]*m[14] - m[4]*m[9]*m[14], + -m[2]*m[9]*m[12] + m[1]*m[10]*m[12] + m[2]*m[8]*m[13] - m[0]*m[10]*m[13] - m[1]*m[8]*m[14] + m[0]*m[9]*m[14], + m[2]*m[5]*m[12] - m[1]*m[6]*m[12] - m[2]*m[4]*m[13] + m[0]*m[6]*m[13] + m[1]*m[4]*m[14] - m[0]*m[5]*m[14], + -m[2]*m[5]*m[8] + m[1]*m[6]*m[8] + m[2]*m[4]*m[9] - m[0]*m[6]*m[9] - m[1]*m[4]*m[10] + m[0]*m[5]*m[10], + } + + result.MultiplySelf(1 / det) + //log.Print(m) + //log.Print(result) + + return &result +} + +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, aspect 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)) + // OK apparently I suck, let's use somebody else's projection matrix: + m.ZeroFill() + + // fov = fov / 180 * math.Pi // Convert to radians + // e := float32(1 / math.Tan(float64(fov/2))) + + // m.Set(0, 0, e/aspect) + // m.Set(1, 1, e) + // m.Set(2, 2, (far+near)/(near-far)) + // m.Set(2, 3, 2*far*near/(near-far)) + // m.Set(3, 2, -1) // Might need to be swapped + + DEG2RAD := math.Acos(-1.0) / 180.0 + tangent := math.Tan(float64(fov/2.0) * DEG2RAD) // tangent of half fovY + top := near * float32(tangent) // half height of near plane + right := top * aspect // half width of near plane + // Column major maybe??? + // n/r 0 0 0 + // 0 n/t 0 0 + // 0 0 -(f+n)/(f-n) -1 + // 0 0 -(2fn)/(f-n) 0 + + m.Set(0, 0, near/right) + m.Set(1, 1, near/top) + m.Set(2, 2, -(far+near)/(far-near)) + //m.Set(2, 2, -(far)/(far-near)) + m.Set(3, 2, -1) + m.Set(2, 3, -(2*far*near)/(far-near)) + //m.Set(2, 3, -(far*near)/(far-near)) +} + +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, 1) //(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) +} + +// Convert the point to a viewport point +func (v *Vec3f) ViewportSelf(width, height int) { + v.X = (v.X + 1) / 2 * float32(width) + v.Y = (1 - (v.Y+1)/2) * float32(height) + // Don't touch Z +} + +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) +} + +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) ScaleSelf(scale float32) { + m.Set(0, 0, m.Get(0, 0)*scale) + m.Set(1, 1, m.Get(1, 1)*scale) + m.Set(2, 2, m.Get(2, 2)*scale) +} + +func (m *Mat44f) SetRotationX(radang float32) { + m.SetIdentity() + m[5] = float32(math.Cos(float64(radang))) + m[10] = m[5] + m[6] = float32(math.Sin(float64(radang))) + m[9] = -m[6] +} + +func (m *Mat44f) SetRotationY(radang float32) { + m.SetIdentity() + m[0] = float32(math.Cos(float64(radang))) + m[10] = m[0] + m[8] = float32(math.Sin(float64(radang))) + m[2] = -m[8] +} + +func (m *Mat44f) SetRotationZ(radang float32) { + m.SetIdentity() + m[0] = float32(math.Cos(float64(radang))) + m[5] = m[0] + m[4] = float32(math.Sin(float64(radang))) + m[2] = -m[4] +} + +// Camera is easier to deal with using yaw and pitch, since we're not supporting roll +func (m *Mat44f) SetCamera(loc *Vec3f, yaw float32, pitch float32, up *Vec3f) Vec3f { + // Use sphere equation to compute lookat vector through the two + // player-controled angles (pitch and yaw) + lookvec := Vec3f{ + Z: float32(-math.Sin(float64(pitch)) * math.Cos(float64(yaw))), + X: float32(math.Sin(float64(pitch)) * math.Sin(float64(yaw))), + Y: float32(math.Cos(float64(pitch))), + } + m.SetLookAt(loc, loc.Add(&lookvec), up) + return lookvec +} + +// Note: use {0,1,0} for up for normal use +func (m *Mat44f) SetLookAt(from *Vec3f, to *Vec3f, up *Vec3f) { + forward := from.Sub(to).Normalize() + // IDK if you have to normalize but whatever + right := up.CrossProduct(forward).Normalize() + realup := forward.CrossProduct(right) + m.SetIdentity() + m.Set(0, 0, right.X) + m.Set(1, 0, right.Y) + m.Set(2, 0, right.Z) + m.Set(0, 1, realup.X) + m.Set(1, 1, realup.Y) + m.Set(2, 1, realup.Z) + m.Set(0, 2, forward.X) + m.Set(1, 2, forward.Y) + m.Set(2, 2, forward.Z) + m.Set(0, 3, from.X) + m.Set(1, 3, from.Y) + m.Set(2, 3, from.Z) +} + +// 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). May +// mess with garbage collector?? IDK +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 +} + +// Multiply two matrices, storing the result in the first one +// func (m *Mat44f) MultiplyInto(m2 *Mat44f) { +// var orig Mat44f +// for i := 0; i < 16; i++ { +// orig[i] = m[i] +// } +// // This is the x and y of our resulting matrix +// for y := 0; y < 4; y++ { +// for x := 0; x < 4; x++ { +// m[x+y*4] = 0 +// for i := 0; i < 4; i++ { +// m[x+y*4] += orig[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) Add(v1 *Vec3f) *Vec3f { + return &Vec3f{ + X: v0.X + v1.X, + Y: v0.Y + v1.Y, + Z: v0.Z + v1.Z, + } +} + +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 +} + +func Clamp[t float32 | int](v, minv, maxv t) t { + if v < minv { + return minv + } else if v > maxv { + return maxv + } else { + return v + } +} diff --git a/renderer3/hrend/obj.go b/renderer3/hrend/obj.go new file mode 100644 index 0000000..06220f2 --- /dev/null +++ b/renderer3/hrend/obj.go @@ -0,0 +1,108 @@ +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), + VTexture: 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/renderer3/hrend/render.go b/renderer3/hrend/render.go new file mode 100644 index 0000000..374a13b --- /dev/null +++ b/renderer3/hrend/render.go @@ -0,0 +1,214 @@ +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)} +} + +func ComputeBoundingBoxF(v0, v1, v2 Vec3f) (Vec3f, Vec3f) { + return Vec3f{min(v0.X, v1.X, v2.X), min(v0.Y, v1.Y, v2.Y), min(v0.Z, v1.Z, v2.Z)}, + Vec3f{max(v0.X, v1.X, v2.X), max(v0.Y, v1.Y, v2.Y), max(v0.Z, v1.Z, v2.Z)} +} + +// 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 Vec3f) 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 Vec3f) (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 ZClip(v0f Vec3f, v1f Vec3f, v2f Vec3f) bool { + maxz := max(v0f.Z, v1f.Z, v2f.Z) + return maxz < -1 || maxz > 1 +} + +func TriangleFlat(fb *RenderBuffer, color uint, v0f Vec3f, v1f Vec3f, v2f Vec3f) { + if ZClip(v0f, v1f, v2f) { + return + } + v0 := v0f.ToVec2i() + v1 := v1f.ToVec2i() + v2 := v2f.ToVec2i() + r, g, b := Uint2Col(color) + boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2) + if boundsBR.X < 0 || boundsBR.Y < 0 || boundsTL.X >= int(fb.Width) || boundsTL.Y >= int(fb.Height) { + 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} + 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 { + 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] { + fb.ZBuffer[x+y*fb.Width] = pz + fb.Data.Set(x, y, r, g, b) + } + } + w0 += w0_xi + w1 += w1_xi + w2 += w2_xi + } + w0_y += w0_yi + w1_y += w1_yi + w2_y += w2_yi + } +} + +func TriangleTextured(fb *RenderBuffer, texture Framebuffer, intensity float32, v0v Vertex, v1v Vertex, v2v Vertex) { + // if ZClip(v0v.Pos, v1v.Pos, v2v.Pos) { + // return + // } + // min, max + boundsTLf, boundsBRf := ComputeBoundingBoxF(v0v.Pos, v1v.Pos, v2v.Pos) + // The triangle is fully out of bounds + if boundsBRf.Y < 0 || boundsBRf.X < 0 || boundsTLf.X >= float32(fb.Width) || boundsTLf.Y >= float32(fb.Height) { //|| + //boundsBRf.Z < 0 || boundsTLf.Z > 1 { + return + } + if boundsBRf.Z < 0 || boundsTLf.Z > 1 { + //log.Print(boundsTLf, boundsBRf) + return + } + v0 := v0v.Pos.ToVec2i() + v1 := v1v.Pos.ToVec2i() + v2 := v2v.Pos.ToVec2i() + //boundsTL, boundsBR := ComputeBoundingBox(v0, v1, v2) + parea := EdgeFunctioni(v0, v1, v2) + // Disable back face culling + // if parea < 0 { + // v1, v2 = v2, v1 + // parea = EdgeFunctioni(v0, v1, v2) + // } + if parea == 0 { + return + } + boundsTL := Vec2i{ + X: int(max(boundsTLf.X, 0)), //0, float32(fb.Width))), + Y: int(max(boundsTLf.Y, 0)), //Clamp(boundsTLf.Y, 0, float32(fb.Height))), + } + boundsBR := Vec2i{ + X: int(min(boundsBRf.X, float32(fb.Width-1))), + Y: int(min(boundsBRf.Y, float32(fb.Height-1))), + } + /*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) + + // //v0f := v0v.Pos + // parea := EdgeFunction(v0v.Pos, v1v.Pos, v2v.Pos) + // // Disable back face culling + // // if parea < 0 { + // // v1, v2 = v2, v1 + // // parea = EdgeFunctioni(v0, v1, v2) + // // } + // if parea == 0 { + // return + // } + // pstart := Vec3f{X: float32(boundsTL.X), Y: float32(boundsTL.Y)} + // invarea := 1 / float32(parea) + // w0_y := EdgeFunction(v1v.Pos, v2v.Pos, pstart) + // w1_y := EdgeFunction(v2v.Pos, v0v.Pos, pstart) + // w2_y := EdgeFunction(v0v.Pos, v1v.Pos, pstart) + // w0_xi, w0_yi := EdgeIncrement(v1v.Pos, v2v.Pos) + // w1_xi, w1_yi := EdgeIncrement(v2v.Pos, v0v.Pos) + // w2_xi, w2_yi := EdgeIncrement(v0v.Pos, v1v.Pos) + + 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 { + //if w0 >= 0 && w1 >= 0 && 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 + r, g, b := 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), + ) + fb.Data.Set(x, y, byte(float32(r)*intensity), byte(float32(g)*intensity), byte(float32(b)*intensity)) + } + } + w0 += w0_xi + w1 += w1_xi + w2 += w2_xi + } + w0_y += w0_yi + w1_y += w1_yi + w2_y += w2_yi + } +} diff --git a/renderer3/main.go b/renderer3/main.go new file mode 100644 index 0000000..f12c74f --- /dev/null +++ b/renderer3/main.go @@ -0,0 +1,295 @@ +package main + +import ( + "flag" + "fmt" + "image" + "image/color" + "log" + "math" + "os" + "path/filepath" + "renderer3/hrend" + "runtime/pprof" // For performance profiling (unnecessary) + "time" + + _ "image/jpeg" + + rl "github.com/gen2brain/raylib-go/raylib" +) + +const ( + NearClip = 0.0001 + FarClip = 10 + Movement = 1.0 + Rotation = 0.25 + LookLock = math.Pi / 32 +) + +func must(err error) { + if err != nil { + panic(err) + } +} + +type ObjectDef struct { + Model *hrend.ObjModel + Texture hrend.Framebuffer // This needs to go somewhere else eventually! + Pos hrend.Vec3f + LookVec hrend.Vec3f + Scale float32 + Lighting bool +} + +func NewObjectDef(model *hrend.ObjModel, texture hrend.Framebuffer) *ObjectDef { + result := ObjectDef{ + Model: model, + Texture: texture, + LookVec: hrend.Vec3f{X: 0, Y: 0, Z: -1}, + Scale: 1, + Lighting: true, + } + return &result +} + +func loadObject(name string) (*hrend.ObjModel, hrend.Framebuffer) { + ofile := filepath.Join("../", name+".obj") + tfile := filepath.Join("../", name+".jpg") + log.Printf("Loading obj %s, texture %s", ofile, tfile) + + of, err := os.Open(ofile) + must(err) + defer of.Close() + o, err := hrend.ParseObj(of) + must(err) + + jf, err := os.Open(tfile) + must(err) + defer jf.Close() + timg, _, err := image.Decode(jf) + must(err) + texture := hrend.NewTexture(timg, 4) + + return o, texture +} + +// However flag works... idk +var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") +var width = flag.Int("width", 640, "width of window or frame") +var height = flag.Int("height", 480, "height of window or frame") +var renderout = flag.String("renderout", "", "If set, rendering is done to a file instead of realtime") +var renderinput = flag.String("renderinput", "", "If not realtime, the inputs are taken from here.") +var xofs = flag.Float64("xofs", 0, "starting x-offset") +var zofs = flag.Float64("zofs", 0, "starting z-offset") +var yofs = flag.Float64("yofs", 0.5, "starting y-offset") +var fov = flag.Float64("fov", 90, "the horizontal fov") +var fps = flag.Int("fps", 60, "fps to run (realtime only)") +var minlight = flag.Float64("minlight", 0.5, "Minimum light level") + +// var renderconfig = flag.String("renderconfig", "", "if set, rendering is written out") + +func IsRealtime() bool { + return *renderout == "" +} + +// Do next inputs, whether they come from raylib or a file +func CameraInput(yaw, pitch float32) (float32, float32, hrend.Vec3f) { + + Fps := float32(*fps) + mouse := rl.GetMouseDelta() + pitch += Rotation * mouse.Y / Fps + yaw += Rotation * mouse.X / Fps + pitch = hrend.Clamp(pitch, LookLock, math.Pi-LookLock) + + newcamtrans := hrend.Vec3f{X: 0, Y: 0, Z: 0} + if rl.IsKeyDown(rl.KeyD) { + newcamtrans.X += Movement / Fps + } + if rl.IsKeyDown(rl.KeyA) { + newcamtrans.X -= Movement / Fps + } + // Moving forward moves in the negative z direction, since we FACE + // the -z axis (the camera does anyway) + if rl.IsKeyDown(rl.KeyW) { + newcamtrans.Z -= Movement / Fps + } + if rl.IsKeyDown(rl.KeyS) { + newcamtrans.Z += Movement / Fps + } + if rl.IsKeyDown(rl.KeySpace) { + newcamtrans.Y += Movement / Fps + } + if rl.IsKeyDown(rl.KeyLeftShift) { + newcamtrans.Y -= Movement / Fps + } + + // translate the new camera movement based on the yaw + var moverot hrend.Mat44f + moverot.SetRotationY(-yaw) + newcamtrans = moverot.MultiplyPoint3(newcamtrans) + + return yaw, pitch, newcamtrans +} + +// -------------------------------------------- +// +// MAIN +// +// -------------------------------------------- +func main() { + 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() + } + + Width := uint(*width) + Height := uint(*height) + + var timer hrend.FrameTimer + var fb hrend.Framebuffer + var drawFunc func() + + if IsRealtime() { + rl.InitWindow(int32(Width), int32(Height), "Simple renderer with raylib") + defer rl.CloseWindow() + rl.SetTargetFPS(int32(*fps)) + rl.DisableCursor() + rfb := NewRaylibBuffer(Width, Height) + defer rl.UnloadTexture(rfb.Texture) + defer rl.UnloadImageColors(rfb.Data) + defer rl.UnloadImage(rfb.Image) + fb = rfb + drawFunc = func() { + rl.UpdateTexture(rfb.Texture, rfb.Data) + rl.BeginDrawing() + rl.ClearBackground(rl.RayWhite) + rl.DrawTexture(rfb.Texture, 0, 0, rl.White) + rl.DrawText(fmt.Sprintf("Frame: %.2fms", timer.LastAverage.Seconds()*1000), 5, 5, 20, rl.Red) + rl.EndDrawing() + } + } else { + } + + rb := hrend.NewRenderbuffer(fb, Width, Height) + + // Generate world + wtexraw := Checkerboard([]color.Color{color.RGBA{R: 0, G: 255, B: 0, A: 255}, color.RGBA{R: 50, G: 150, B: 0, A: 255}}, 32) + wtex := hrend.NewTexture(wtexraw, 1) + world := FlatTerrain(1) + + // Generate skybox + skyraw := Gradient1px(color.RGBA{R: 100, G: 100, B: 255, A: 255}, color.RGBA{R: 255, G: 255, B: 255, A: 255}, 32) + skytex := hrend.NewTexture(skyraw, 1) + sky := Skybox() + + // Some static models we could put in the scene + modnames := []string{"head", "diablo"} + models := make([]*hrend.ObjModel, len(modnames)) + textures := make([]hrend.Framebuffer, len(modnames)) + for i, name := range modnames { + models[i], textures[i] = loadObject(name) + } + + // And the actual objects for the scene. We also put the world in there + objects := make([]*ObjectDef, 0) + objects = append(objects, NewObjectDef(world, wtex)) + objects = append(objects, NewObjectDef(sky, skytex)) // the actual skybox + skyobj := objects[len(objects)-1] + skyobj.Scale = 50 + skyobj.Lighting = false + objects = append(objects, NewObjectDef(models[1], textures[1])) + objects[len(objects)-1].Pos.Y += 1 + objects[len(objects)-1].Pos.Z -= 2 + + // These don't really change + var projection hrend.Mat44f //, viewport hrend.Mat44f + projection.SetProjection(float32(*fov), float32(Width)/float32(Height), NearClip, FarClip) + //viewport.SetViewportSimple(int(Width), int(Height), 1) //65535) + + var camera hrend.Mat44f + var newcamtrans hrend.Vec3f + camtrans := hrend.Vec3f{X: float32(*xofs), Y: float32(*yofs), Z: float32(*zofs)} + camup := hrend.Vec3f{X: 0, Y: 1, Z: 0} + lightang := -math.Pi / 4 // Angle offset from "straight down" + light := hrend.Vec3f{X: 0, Y: float32(-math.Cos(lightang)), Z: float32(math.Sin(lightang))} + + // In our system, 0 degree yaw is facing -Z, into the scene + yaw := float32(0) + pitch := float32(math.Pi / 2) // Start looking flat + + log.Printf("Starting render loop") + for !rl.WindowShouldClose() { + + start := time.Now() + + yaw, pitch, newcamtrans = CameraInput(yaw, pitch) + camtrans = *camtrans.Add(&newcamtrans) + _ = camera.SetCamera(&camtrans, yaw, pitch, &camup) + screenmat := camera.Inverse().Multiply(&projection) + //screenmat = screenmat.Multiply(&viewport) + + rb.ResetZBuffer() + for y := range Height { + for x := range Width { + fb.Set(x, y, 0, 0, 0) + } + } + + var sc [3]hrend.Vertex + var modelmat hrend.Mat44f + var intensity float32 + var minz = float32(math.MaxFloat32) + var maxz = float32(-math.MaxFloat32) + for _, o := range objects { + // Create the final matrix + modelmat.SetLookAt(&o.Pos, o.Pos.Add(&o.LookVec), &camup) + modelmat.ScaleSelf(o.Scale) + matrix3d := modelmat.Multiply(screenmat) + for _, f := range o.Model.Faces { + for i := range 3 { + sc[i] = f[i] + sc[i].Pos = matrix3d.MultiplyPoint3(f[i].Pos) + minz = min(minz, sc[i].Pos.Z) + maxz = max(maxz, sc[i].Pos.Z) + } + log.Print(o.Model.Faces[0][0].Pos, o.Model.Faces[0][1].Pos, o.Model.Faces[0][2].Pos) + log.Print(sc[0].Pos, sc[1].Pos, sc[2].Pos) + log.Print(matrix3d) + for i := range 3 { + // Perspective divide (?) and screen coord + sc[i].Pos.ViewportSelf(*width, *height) + } + //log.Print(sc[0].Pos, sc[1].Pos, sc[2].Pos, matrix3d) + if o.Lighting { + l1 := f[2].Pos.Sub(&f[0].Pos) + n := l1.CrossProduct(f[1].Pos.Sub(&f[0].Pos)) + n = n.Normalize() + // light = lookvec // use this for weird things + intensity = n.MultSimp(&light) + if intensity < 0 { + intensity = 0 + } + intensity = (intensity + float32(*minlight)) / (1 + float32(*minlight)) + } else { + intensity = 1.0 + } + hrend.TriangleTextured(&rb, o.Texture, intensity, sc[0], sc[1], sc[2]) + break // only render one face + //hrend.TriangleFlat(&rb, hrend.Col2Uint(byte(255*intensity), byte(255*intensity), byte(255*intensity)), sc[0].Pos, sc[1].Pos, sc[2].Pos) + } + break // only render one object + } + //log.Print(minz, maxz) + + timer.Add(time.Since(start), 10) + drawFunc() + } +} diff --git a/renderer3/raybuffer.go b/renderer3/raybuffer.go new file mode 100644 index 0000000..6a6cc32 --- /dev/null +++ b/renderer3/raybuffer.go @@ -0,0 +1,64 @@ +package main + +import ( + rl "github.com/gen2brain/raylib-go/raylib" + "log" +) + +type RaylibBuffer struct { + Data []rl.Color + Image *rl.Image + Texture rl.Texture2D + Width uint + Height uint +} + +func NewRaylibBuffer(width uint, height uint) *RaylibBuffer { + log.Printf("Creating new raylib framebuffer using texture + image") + //rl.NewTexture2D(1, Width, Height, 0, ) + rlimage := rl.GenImageColor(int(width), int(height), rl.Black) + rl.ImageFormat(rlimage, rl.UncompressedR8g8b8a8) + log.Printf("Generated baseline image: %v", rlimage) + rltexture := rl.LoadTextureFromImage(rlimage) + log.Printf("Generated texture from image") + data := rl.LoadImageColors(rlimage) + log.Printf("Generated pixel data from image") + return &RaylibBuffer{ + Data: data, + Image: rlimage, + Texture: rltexture, + Width: width, + Height: height, + } +} + +func (fb *RaylibBuffer) Dims() (uint, uint) { + return fb.Width, fb.Height +} + +// Sure hope this gets inlined... +func (fb *RaylibBuffer) Set(x uint, y uint, r byte, g byte, b byte) { + if x >= fb.Width || y >= fb.Height { + return + } + fb.Data[x+y*fb.Width].R = r + fb.Data[x+y*fb.Width].G = g + fb.Data[x+y*fb.Width].B = b +} + +func (fb *RaylibBuffer) Get(x uint, y uint) (byte, byte, byte) { + if x >= fb.Width || y >= fb.Height { + return 0, 0, 0 + } + return fb.Data[x+y*fb.Width].R, + fb.Data[x+y*fb.Width].G, + fb.Data[x+y*fb.Width].B +} + +func (fb *RaylibBuffer) GetUv(u float32, v float32) (byte, byte, byte) { + 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].R, + fb.Data[x+y*fb.Width].G, + fb.Data[x+y*fb.Width].B +} diff --git a/renderer3/runopengl21.sh b/renderer3/runopengl21.sh new file mode 100755 index 0000000..5ea8c2f --- /dev/null +++ b/renderer3/runopengl21.sh @@ -0,0 +1,3 @@ +#!/bin/sh +go build -tags opengl21 -o renderer +./renderer