From 4f4885aebbdd6994fe730b7520763b82d9338a2c Mon Sep 17 00:00:00 2001 From: Carlos Sanchez Date: Fri, 2 Aug 2024 15:35:30 -0400 Subject: [PATCH] Setting up new renderer for testing --- renderer2/.gitignore | 1 + renderer2/go.mod | 11 ++ renderer2/go.sum | 8 + renderer2/hrend/frametime.go | 27 +++ renderer2/hrend/image.go | 195 ++++++++++++++++++++ renderer2/hrend/imagebuffer.go | 49 +++++ renderer2/hrend/math.go | 324 +++++++++++++++++++++++++++++++++ renderer2/hrend/obj.go | 107 +++++++++++ renderer2/hrend/render.go | 177 ++++++++++++++++++ renderer2/main.go | 222 ++++++++++++++++++++++ renderer2/raybuffer.go | 64 +++++++ renderer2/texturegen.go | 17 ++ 12 files changed, 1202 insertions(+) create mode 100644 renderer2/.gitignore create mode 100644 renderer2/go.mod create mode 100644 renderer2/go.sum create mode 100644 renderer2/hrend/frametime.go create mode 100644 renderer2/hrend/image.go create mode 100644 renderer2/hrend/imagebuffer.go create mode 100644 renderer2/hrend/math.go create mode 100644 renderer2/hrend/obj.go create mode 100644 renderer2/hrend/render.go create mode 100644 renderer2/main.go create mode 100644 renderer2/raybuffer.go create mode 100644 renderer2/texturegen.go diff --git a/renderer2/.gitignore b/renderer2/.gitignore new file mode 100644 index 0000000..9fa139f --- /dev/null +++ b/renderer2/.gitignore @@ -0,0 +1 @@ +renderer2 diff --git a/renderer2/go.mod b/renderer2/go.mod new file mode 100644 index 0000000..693692a --- /dev/null +++ b/renderer2/go.mod @@ -0,0 +1,11 @@ +module renderer1 + +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/renderer2/go.sum b/renderer2/go.sum new file mode 100644 index 0000000..d39cac3 --- /dev/null +++ b/renderer2/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/renderer2/hrend/frametime.go b/renderer2/hrend/frametime.go new file mode 100644 index 0000000..cd61fca --- /dev/null +++ b/renderer2/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/renderer2/hrend/image.go b/renderer2/hrend/image.go new file mode 100644 index 0000000..686c742 --- /dev/null +++ b/renderer2/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, skip int) *SimpleFramebuffer { + bounds := texture.Bounds() + width := bounds.Dx() / skip + height := bounds.Dy() / skip + 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 += skip { + for x := bounds.Min.X; x < bounds.Max.X; x += skip { + col := texture.At(x, y) + r, g, b, _ := col.RGBA() + result.Set(uint(x/skip), uint(y/skip), 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/renderer2/hrend/imagebuffer.go b/renderer2/hrend/imagebuffer.go new file mode 100644 index 0000000..3044455 --- /dev/null +++ b/renderer2/hrend/imagebuffer.go @@ -0,0 +1,49 @@ +/*package hrend + +import ( + "image" +) + +// Color is in RGB (alpha not used right now) +type ImageFramebuffer struct { + Data image.Image + Width uint + Height uint +} + +// Sure hope this gets inlined... +func (fb *ImageFramebuffer) Set(x uint, y uint, r byte, g byte, b byte) { + if x >= fb.Width || y >= fb.Height { + return + } + image.New + fb.Data. + 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, + } +}*/ diff --git a/renderer2/hrend/math.go b/renderer2/hrend/math.go new file mode 100644 index 0000000..b84d40a --- /dev/null +++ b/renderer2/hrend/math.go @@ -0,0 +1,324 @@ +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() + + 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(3, 2, -1) + m.Set(2, 3, -(2*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) 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) + //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) + 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) +} + +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). 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(v, minv, maxv float32) float32 { + if v < minv { + return minv + } else if v > maxv { + return maxv + } else { + return v + } +} diff --git a/renderer2/hrend/obj.go b/renderer2/hrend/obj.go new file mode 100644 index 0000000..6d48355 --- /dev/null +++ b/renderer2/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/renderer2/hrend/render.go b/renderer2/hrend/render.go new file mode 100644 index 0000000..97ded37 --- /dev/null +++ b/renderer2/hrend/render.go @@ -0,0 +1,177 @@ +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 ZClip(v0f Vec3f, v1f Vec3f, v2f Vec3f) bool { + maxz := max(v0f.Z, v1f.Z, v2f.Z) + return maxz < 0 || 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.Y < 0 || boundsBR.X < 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) + // 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.Data.Set(x, y, r, g, b) + } + // 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 *RenderBuffer, texture Framebuffer, intensity float32, v0v Vertex, v1v Vertex, v2v Vertex) { + if ZClip(v0v.Pos, v1v.Pos, v2v.Pos) { + return + } + 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 + 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/renderer2/main.go b/renderer2/main.go new file mode 100644 index 0000000..574f162 --- /dev/null +++ b/renderer2/main.go @@ -0,0 +1,222 @@ +package main + +import ( + "flag" + "fmt" + "image" + "log" + "math" + "os" + "renderer1/hrend" + "runtime/pprof" // For performance profiling (unnecessary) + "time" + + _ "image/jpeg" + + rl "github.com/gen2brain/raylib-go/raylib" +) + +const ( + NearClip = 0.1 + FarClip = 100 + FOV = 90.0 + ZOffset = 1.5 + Movement = 1.0 + Rotation = 0.25 + LookLock = math.Pi / 32 + Fps = 60 + //ObjectFile = "../head.obj" + //TextureFile = "../head.jpg" +) + +func must(err error) { + if err != nil { + panic(err) + } +} + +// func loadDefault() (*hrend.ObjModel, hrend.Framebuffer) { +// log.Printf("Loading obj %s, texture %s", ObjectFile, TextureFile) +// +// of, err := os.Open(ObjectFile) +// must(err) +// defer of.Close() +// o, err := hrend.ParseObj(of) +// must(err) +// +// jf, err := os.Open(TextureFile) +// 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("width", 480, "height of window or frame") + +// var renderconfig = flag.String("renderconfig", "", "if set, rendering is written out") +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.") + +func IsRealtime() bool { + return *renderout == "" +} + +// 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") + +// Do next inputs, whether they come from raylib or a file +func CameraInput(yaw, pitch float32) (float32, float32, hrend.Vec3f) { + + 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 pitch, yaw, newcamtrans +} + +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 fb hrend.Framebuffer + + if IsRealtime() { + rl.InitWindow(int32(Width), int32(Height), "Simple renderer with raylib") + defer rl.CloseWindow() + rl.SetTargetFPS(Fps) + rl.DisableCursor() + rfb := NewRaylibBuffer(Width, Height) + defer rl.UnloadTexture(rfb.Texture) + defer rl.UnloadImageColors(rfb.Data) + defer rl.UnloadImage(rfb.Image) + fb = rfb + } + + rb := hrend.NewRenderbuffer(fb, Width, Height) + //o, texture := loadDefault() + + var thing hrend.Vec2i + log.Print(thing) + + var projection, viewport hrend.Mat44f + + // These don't really change + projection.SetProjection(float32(FOV), float32(Width)/float32(Height), NearClip, FarClip) + viewport.SetViewportSimple(int(Width), int(Height), 1) //65535) + + var timer hrend.FrameTimer + + camtrans := hrend.Vec3f{X: 0, Y: 0, Z: ZOffset} + var newcamtrans hrend.Vec3f + camup := hrend.Vec3f{X: 0, Y: 1, Z: 0} + + // In our system, 0 degree yaw is facing -Z, into the scene + yaw := float32(0) + pitch := float32(math.Pi / 2) // Start looking flat + + var camera hrend.Mat44f + + log.Printf("Starting render loop") + for !rl.WindowShouldClose() { + + start := time.Now() + + yaw, pitch, newcamtrans = CameraInput(yaw, pitch) + camtrans = *camtrans.Add(&newcamtrans) + lookvec := 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 + for _, f := range o.Faces { + // Precompute perspective for vertices to save time. Notice Z + // is not considered: is this orthographic projection? Yeah probably... + for i := range 3 { // Triangles, bro + sc[i] = f[i] + sc[i].Pos = screenmat.MultiplyPoint3(f[i].Pos) + } + + l1 := f[2].Pos.Sub(&f[0].Pos) + n := l1.CrossProduct(f[1].Pos.Sub(&f[0].Pos)) + n = n.Normalize() + intensity := n.MultSimp(&lookvec) + if intensity < 0 { + intensity = 0 + } + hrend.TriangleTextured(&rb, texture, intensity, sc[0], sc[1], sc[2]) + //hrend.TriangleFlat(&rb, hrend.Col2Uint(byte(255*intensity), byte(255*intensity), byte(255*intensity)), sc[0].Pos, sc[1].Pos, sc[2].Pos) + } + + rl.UpdateTexture(fb.Texture, fb.Data) + + timer.Add(time.Since(start), 10) + + if IsRealtime() { + rl.BeginDrawing() + rl.ClearBackground(rl.RayWhite) + rl.DrawTexture(fb.Texture, 0, 0, rl.White) + rl.DrawText(fmt.Sprintf("Frame: %.2fms", timer.LastAverage.Seconds()*1000), 5, 5, 20, rl.Red) + rl.EndDrawing() + } else { + + } + } +} diff --git a/renderer2/raybuffer.go b/renderer2/raybuffer.go new file mode 100644 index 0000000..6a6cc32 --- /dev/null +++ b/renderer2/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/renderer2/texturegen.go b/renderer2/texturegen.go new file mode 100644 index 0000000..156f9a3 --- /dev/null +++ b/renderer2/texturegen.go @@ -0,0 +1,17 @@ +package main + +import ( + "image" + "image/color" + //"renderer1/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 +}