3dtrial/tinyrender1/render.go

95 lines
2.7 KiB
Go
Raw Normal View History

2024-07-23 23:37:02 +00:00
package main
2024-07-24 00:19:03 +00:00
import (
"math"
)
2024-07-23 23:37:02 +00:00
// Draw a line using dumb
func LineDumb(fb *Framebuffer, color uint, x0 uint, y0 uint, x1 uint, y1 uint) {
var t float32
for t = 0; t < 1; t += 0.01 {
// Very simple interpolation between x and y
x := x0 + uint(float32(x1-x0)*t)
y := y0 + uint(float32(y1-y0)*t)
fb.Set(x, y, color)
}
}
func LineDumb2(fb *Framebuffer, color uint, x0 uint, y0 uint, x1 uint, y1 uint) {
for x := x0; x < x1; x++ {
// For each pixel across, compute how far across we are and interpolate y
t := float32(x-x0) / float32(x1-x0)
y := uint(float32(y0)*(1-t) + float32(y1)*t)
fb.Set(x, y, color)
}
}
2024-07-24 00:19:03 +00:00
func LineDumb3(fb *Framebuffer, color uint, x0 int, y0 int, x1 int, y1 int) {
steep := false
// This one makes sure that going pixel by pixel will not make holes in the
// other direction by always moving in the less steep direction.
if math.Abs(float64(x0-x1)) < math.Abs(float64(y0-y1)) {
x0, y0 = y0, x0
x1, y1 = y1, x1
steep = true
}
// Don't let lines be invisible, always go left to right
if x0 > x1 { // need to be left to right
x0, x1 = x1, x0
y0, y1 = y1, y0 // Why are we swapping these? I guess because we're swapping the points...
}
// Same as dumb2, going across pixel by pixel. But "x" here might actually be y
// because of the inverted direction
for x := x0; x <= x1; x++ {
t := float32(x-x0) / float32(x1-x0)
y := uint(float32(y0)*(1-t) + float32(y1)*t)
if steep {
fb.Set(y, uint(x), color)
} else {
fb.Set(uint(x), y, color)
}
}
}
2024-07-24 00:48:49 +00:00
func LineDumb4(fb *Framebuffer, color uint, x0 int, y0 int, x1 int, y1 int) {
steep := false
// This one makes sure that going pixel by pixel will not make holes in the
// other direction by always moving in the less steep direction.
if math.Abs(float64(x1-x0)) < math.Abs(float64(y1-y0)) {
x0, y0 = y0, x0
x1, y1 = y1, x1
steep = true
}
// Don't let lines be invisible, always go left to right
if x0 > x1 { // need to be left to right
x0, x1 = x1, x0
y0, y1 = y1, y0 // Why are we swapping these? I guess because we're swapping the points...
}
dx := x1 - x0 // These MUST be POST calcs
dy := y1 - y0
// Delta error or something? Basically, as we move in one direction, we get farther
// and farther off course if we never move in the OTHER direction. This is the amount
// of that per x direction.
derror := math.Abs(float64(dy) / float64(dx))
y := uint(y0)
var err float64
// Same as dumb2, going across pixel by pixel. But "x" here might actually be y
// because of the inverted direction
for x := x0; x <= x1; x++ {
if steep {
fb.Set(y, uint(x), color)
} else {
fb.Set(uint(x), y, color)
}
err += derror
if err > 0.5 {
if y1 > y0 {
y += 1
} else {
y = y - 1
}
err -= 1
}
}
}