Beginning tinyrender

This commit is contained in:
Carlos Sanchez 2024-07-23 19:00:19 -04:00
parent c7bd37c114
commit be3d3e4b25
4 changed files with 68 additions and 0 deletions

1
tinyrender1/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
tinyrender1

3
tinyrender1/go.mod Normal file
View File

@ -0,0 +1,3 @@
module tinyrender1
go 1.22.5

46
tinyrender1/image.go Normal file
View File

@ -0,0 +1,46 @@
package main
import (
"fmt"
"strings"
)
// Convert rgb to uint
func Col2Uint(r, g, b byte) uint {
return (uint(r) << 16) | (uint(g) << 8) | uint(b)
}
// 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
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),
Width: width,
Height: height,
}
}
// Given some image data, return a string that is the ppm of it
func (fb *Framebuffer) ExportPPM() string {
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()
}

18
tinyrender1/main.go Normal file
View File

@ -0,0 +1,18 @@
package main
import (
"fmt"
"log"
)
const (
Width = 512
Height = 512
)
func main() {
log.Printf("Program start")
fb := NewFramebuffer(Width, Height)
fmt.Print(fb.ExportPPM())
log.Printf("Program end")
}