Create terrain generator with movable 3d camera in golang. You are not allowed to use…
- User
Create terrain generator with movable 3d camera in golang. You are not allowed to use any graphic libraries for 3d. Create everything from scratch. Create file structure for this project also. Implement all created methods and functions
Assistant
3D Terrain Generator with Movable Camera in Go
I'll create a complete 3D terrain generator with a movable camera from scratch in Go, without using any external graphics libraries. This will include the file structure, implementation of all necessary components, and a basic rendering system.
Project Structure
terrain-generator/ ├── main.go ├── pkg/ │ ├── camera/ │ │ └── camera.go │ ├── math/ │ │ ├── matrix.go │ │ ├── vector.go │ │ └── math.go │ ├── renderer/ │ │ ├── renderer.go │ │ └── screen.go │ ├── terrain/ │ │ └── terrain.go │ └── utils/ │ └── utils.go └── go.modImplementation
1. go.mod
module terrain-generator go 1.212. pkg/math/vector.go
package math import "math" type Vec3 struct { X, Y, Z float64 } func NewVec3(x, y, z float64) Vec3 { return Vec3{X: x, Y: y, Z: z} } func (v Vec3) Add(other Vec3) Vec3 { return Vec3{ X: v.X + other.X, Y: v.Y + other.Y, Z: v.Z + other.Z, } } func (v Vec3) Sub(other Vec3) Vec3 { return Vec3{ X: v.X - other.X, Y: v.Y - other.Y, Z: v.Z - other.Z, } } func (v Vec3) Mul(scalar float64) Vec3 { return Vec3{ X: v.X * scalar, Y: v.Y * scalar, Z: v.Z * scalar, } } func (v Vec3) Dot(other Vec3) float64 { return v.X*other.X + v.Y*other.Y + v.Z*other.Z } func (v Vec3) Cross(other Vec3) Vec3 { return Vec3{ X: v.Y*other.Z - v.Z*other.Y, Y: v.Z*other.X - v.X*other.Z, Z: v.X*other.Y - v.Y*other.X, } } func (v Vec3) Length() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y + v.Z*v.Z) } func (v Vec3) Normalize() Vec3 { length := v.Length() if length == 0 { return Vec3{} } return v.Mul(1.0 / length) }3. pkg/math/matrix.go
package math type Mat4 [4][4]float64 func NewIdentityMatrix() Mat4 { return Mat4{ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, } } func NewPerspectiveMatrix(fov, aspect, near, far float64) Mat4 { f := 1.0 / math.Tan(fov*0.5) m := NewIdentityMatrix() m[0][0] = f / aspect m[1][1] = f m[2][2] = (far + near) / (near - far) m[2][3] = -1 m[3][2] = (2 * far * near) / (near - far) m[3][3] = 0 return m } func NewTranslationMatrix(x, y, z float64) Mat4 { m := NewIdentityMatrix() m[0][3] = x m[1][3] = y m[2][3] = z return m } func NewRotationXMatrix(angle float64) Mat4 { c := math.Cos(angle) s := math.Sin(angle) m := NewIdentityMatrix() m[1][1] = c m[1][2] = -s m[2][1] = s m[2][2] = c return m } func NewRotationYMatrix(angle float64) Mat4 { c := math.Cos(angle) s := math.Sin(angle) m := NewIdentityMatrix() m[0][0] = c m[0][2] = s m[2][0] = -s m[2][2] = c return m } func NewRotationZMatrix(angle float64) Mat4 { c := math.Cos(angle) s := math.Sin(angle) m := NewIdentityMatrix() m[0][0] = c m[0][1] = -s m[1][0] = s m[1][1] = c return m } func (m Mat4) Multiply(other Mat4) Mat4 { result := NewIdentityMatrix() for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { result[i][j] = m[i][0]*other[0][j] + m[i][1]*other[1][j] + m[i][2]*other[2][j] + m[i][3]*other[3][j] } } return result } func (m Mat4) TransformVector(v Vec3) Vec3 { x := v.X*m[0][0] + v.Y*m[1][0] + v.Z*m[2][0] + m[3][0] y := v.X*m[0][1] + v.Y*m[1][1] + v.Z*m[2][1] + m[3][1] z := v.X*m[0][2] + v.Y*m[1][2] + v.Z*m[2][2] + m[3][2] w := v.X*m[0][3] + v.Y*m[1][3] + v.Z*m[2][3] + m[3][3] if w != 0 { x /= w y /= w z /= w } return Vec3{X: x, Y: y, Z: z} }4. pkg/camera/camera.go
package camera import ( "terrain-generator/pkg/math" ) type Camera struct { Position math.Vec3 Rotation math.Vec3 Fov float64 Near float64 Far float64 AspectRatio float64 } func NewCamera(position math.Vec3, fov, near, far, aspectRatio float64) *Camera { return &Camera{ Position: position, Rotation: math.Vec3{X: 0, Y: 0, Z: 0}, Fov: fov, Near: near, Far: far, AspectRatio: aspectRatio, } } func (c *Camera) GetViewMatrix() math.Mat4 { // Create rotation matrices rotX := math.NewRotationXMatrix(c.Rotation.X) rotY := math.NewRotationYMatrix(c.Rotation.Y) rotZ := math.NewRotationZMatrix(c.Rotation.Z) // Combine rotations rotation := rotX.Multiply(rotY).Multiply(rotZ) // Create translation matrix translation := math.NewTranslationMatrix(-c.Position.X, -c.Position.Y, -c.Position.Z) // Combine to get view matrix return rotation.Multiply(translation) } func (c *Camera) GetProjectionMatrix() math.Mat4 { return math.NewPerspectiveMatrix(c.Fov, c.AspectRatio, c.Near, c.Far) } func (c *Camera) MoveForward(distance float64) { // Calculate forward vector based on rotation forward := math.Vec3{ X: math.Sin(c.Rotation.Y) * math.Cos(c.Rotation.X), Y: math.Sin(c.Rotation.X), Z: math.Cos(c.Rotation.Y) * math.Cos(c.Rotation.X), }.Normalize() c.Position = c.Position.Add(forward.Mul(distance)) } func (c *Camera) MoveRight(distance float64) { // Calculate right vector based on rotation right := math.Vec3{ X: math.Sin(c.Rotation.Y - math.Pi/2), Y: 0, Z: math.Cos(c.Rotation.Y - math.Pi/2), }.Normalize() c.Position = c.Position.Add(right.Mul(distance)) } func (c *Camera) Rotate(x, y, z float64) { c.Rotation.X += x c.Rotation.Y += y c.Rotation.Z += z }5. pkg/terrain/terrain.go
package terrain import ( "math/rand" "terrain-generator/pkg/math" ) type Terrain struct { Width int Height int Scale float64 Grid [][]float64 } func NewTerrain(width, height int, scale float64) *Terrain { terrain := &Terrain{ Width: width, Height: height, Scale: scale, Grid: make([][]float64, width), } for i := range terrain.Grid { terrain.Grid[i] = make([]float64, height) } terrain.Generate() return terrain } func (t *Terrain) Generate() { // Simple Perlin-like noise for terrain generation for x := 0; x < t.Width; x++ { for z := 0; z < t.Height; z++ { // Generate some random height t.Grid[x][z] = t.generateHeight(x, z) } } } func (t *Terrain) generateHeight(x, z int) float64 { // Simple noise function - in a real implementation you'd use Perlin noise nx := float64(x) / float64(t.Width) * t.Scale nz := float64(z) / float64(t.Height) * t.Scale // Multiple octaves of noise height := 0.0 amplitude := 1.0 frequency := 1.0 for i := 0; i < 4; i++ { height += rand.Float64() * amplitude * math.Sin(nx*frequency)*math.Cos(nz*frequency) amplitude *= 0.5 frequency *= 2.0 } return height } func (t *Terrain) GetHeightAt(x, z float64) float64 { // Convert world coordinates to grid coordinates gridX := int(x / t.Scale) gridZ := int(z / t.Scale) if gridX < 0 || gridX >= t.Width || gridZ < 0 || gridZ >= t.Height { return 0 } return t.Grid[gridX][gridZ] } func (t *Terrain) GetNormalAt(x, z float64) math.Vec3 { // Get heights around the point h00 := t.GetHeightAt(x-t.Scale, z-t.Scale) h01 := t.GetHeightAt(x-t.Scale, z+t.Scale) h10 := t.GetHeightAt(x+t.Scale, z-t.Scale) h11 := t.GetHeightAt(x+t.Scale, z+t.Scale) // Calculate normal using central differences normal := math.Vec3{ X: h00 - h10 - h01 + h11, Y: 2 * t.Scale, Z: h00 + h10 - h01 - h11, } return normal.Normalize() }6. pkg/renderer/screen.go
package renderer import ( "image" "image/color" "image/png" "os" ) type Screen struct { Width int Height int Pixels []color.RGBA } func NewScreen(width, height int) *Screen { return &Screen{ Width: width, Height: height, Pixels: make([]color.RGBA, width*height), } } func (s *Screen) Clear() { for i := range s.Pixels { s.Pixels[i] = color.RGBA{0, 0, 0, 255} } } func (s *Screen) SetPixel(x, y int, c color.RGBA) { if x >= 0 && x < s.Width && y >= 0 && y < s.Height { s.Pixels[y*s.Width+x] = c } } func (s *Screen) SaveToFile(filename string) error { img := image.NewRGBA(image.Rect(0, 0, s.Width, s.Height)) img.Pix = s.PixelsToBytes() file, err := os.Create(filename) if err != nil { return err } defer file.Close() return png.Encode(file, img) } func (s *Screen) PixelsToBytes() []byte { bytes := make([]byte, len(s.Pixels)*4) for i, pixel := range s.Pixels { bytes[i*4] = pixel.R bytes[i*4+1] = pixel.G bytes[i*4+2] = pixel.B bytes[i*4+3] = pixel.A } return bytes }7. pkg/renderer/renderer.go
package renderer import ( "math" "terrain-generator/pkg/camera" "terrain-generator/pkg/math" "terrain-generator/pkg/terrain" ) type Renderer struct { Screen *Screen Camera *camera.Camera Terrain *terrain.Terrain } func NewRenderer(screen *Screen, camera *camera.Camera, terrain *terrain.Terrain) *Renderer { return &Renderer{ Screen: screen, Camera: camera, Terrain: terrain, } } func (r *Renderer) Render() { r.Screen.Clear() viewMatrix := r.Camera.GetViewMatrix() projectionMatrix := r.Camera.GetProjectionMatrix() transformMatrix := projectionMatrix.Multiply(viewMatrix) // Simple rendering - we'll just render the terrain as a grid of triangles for x := 0; x < r.Terrain.Width-1; x++ { for z := 0; z < r.Terrain.Height-1; z++ { // Get the four corners of the grid cell p0 := math.NewVec3(float64(x)*r.Terrain.Scale, r.Terrain.Grid[x][z], float64(z)*r.Terrain.Scale) p1 := math.NewVec3(float64(x+1)*r.Terrain.Scale, r.Terrain.Grid[x+1][z], float64(z)*r.Terrain.Scale) p2 := math.NewVec3(float64(x)*r.Terrain.Scale, r.Terrain.Grid[x][z+1], float64(z+1)*r.Terrain.Scale) p3 := math.NewVec3(float64(x+1)*r.Terrain.Scale, r.Terrain.Grid[x+1][z+1], float64(z+1)*r.Terrain.Scale) // Transform the points p0 = transformMatrix.TransformVector(p0) p1 = transformMatrix.TransformVector(p1) p2 = transformMatrix.TransformVector(p2) p3 = transformMatrix.TransformVector(p3) // Convert to screen coordinates p0 = r.toScreenCoordinates(p0) p1 = r.toScreenCoordinates(p1) p2 = r.toScreenCoordinates(p2) p3 = r.toScreenCoordinates(p3) // Draw the two triangles that make up the grid cell r.drawTriangle(p0, p1, p2) r.drawTriangle(p1, p3, p2) } } } func (r *Renderer) toScreenCoordinates(v math.Vec3) math.Vec3 { // Convert from NDC to screen coordinates x := (v.X + 1) * 0.5 * float64(r.Screen.Width) y := (1 - v.Y) * 0.5 * float64(r.Screen.Height) return math.NewVec3(x, y, v.Z) } func (r *Renderer) drawTriangle(p0, p1, p2 math.Vec3) { // Simple triangle rasterization using barycentric coordinates minX := math.Max(0, math.Min(math.Min(p0.X, p1.X), p2.X)) minY := math.Max(0, math.Min(math.Min(p0.Y, p1.Y), p2.Y)) maxX := math.Min(float64(r.Screen.Width-1), math.Max(math.Max(p0.X, p1.X), p2.X)) maxY := math.Min(float64(r.Screen.Height-1), math.Max(math.Max(p0.Y, p1.Y), p2.Y)) for y := int(minY); y <= int(maxY); y++ { for x := int(minX); x <= int(maxX); x++ { p := math.NewVec3(float64(x), float64(y), 0) // Calculate barycentric coordinates bary := r.calculateBarycentric(p, p0, p1, p2) if bary.X >= 0 && bary.Y >= 0 && bary.Z >= 0 { // Calculate depth depth := p0.Z*bary.X + p1.Z*bary.Y + p2.Z*bary.Z // Simple shading based on depth shade := uint8(255 * (1 - depth/2)) r.Screen.SetPixel(x, y, color.RGBA{shade, shade, shade, 255}) } } } } func (r *Renderer) calculateBarycentric(p, a, b, c math.Vec3) math.Vec3 { v0 := b.Sub(a) v1 := c.Sub(a) v2 := p.Sub(a) d00 := v0.Dot(v0) d01 := v0.Dot(v1) d11 := v1.Dot(v1) d20 := v2.Dot(v0) d21 := v2.Dot(v1) denom := d00*d11 - d01*d01 v := (d11*d20 - d01*d21) / denom w := (d00*d21 - d01*d20) / denom u := 1.0 - v - w return math.NewVec3(u, v, w) }8. main.go
package main import ( "fmt" "image/color" "math" "terrain-generator/pkg/camera" "terrain-generator/pkg/math" "terrain-generator/pkg/renderer" "terrain-generator/pkg/terrain" ) func main() { // Screen dimensions screenWidth := 800 screenHeight := 600 // Create screen screen := renderer.NewScreen(screenWidth, screenHeight) // Create camera cam := camera.NewCamera( math.NewVec3(0, 5, -10), math.Pi/3, // Field of view 0.1, // Near plane 100.0, // Far plane float64(screenWidth)/float64(screenHeight), ) // Create terrain terrain := terrain.NewTerrain(50, 50, 1.0) // Create renderer renderer := renderer.NewRenderer(screen, cam, terrain) // Render initial frame renderer.Render() screen.SaveToFile("output.png") fmt.Println("Initial frame rendered to output.png") // Simple interaction loop (in a real app, this would be event-driven) for i := 0; i < 10; i++ { // Move camera forward cam.MoveForward(0.5) // Render frame renderer.Render() screen.SaveToFile(fmt.Sprintf("frame_%d.png", i+1)) fmt.Printf("Rendered frame %d\n", i+1) } }How It Works
-
Math Package: Provides all the necessary vector and matrix operations for 3D transformations.
-
Camera: Implements a 3D camera with position and rotation that can be moved around the scene.
-
Terrain: Generates a heightmap using a simple noise function and provides methods to get heights and normals at any point.
-
Renderer: Handles the rendering pipeline including:
- View and projection transformations
- Triangle rasterization
- Simple shading based on depth
-
Main Program: Sets up the scene, creates the components, and renders a series of frames showing the camera moving forward.
Limitations
This is a basic implementation with several limitations:
- No proper lighting or shading
- Simple triangle rasterization without depth testing
- Basic terrain generation without proper noise functions
- No real-time rendering (frames are saved to files)
To improve this, you would want to:
- Add proper lighting calculations
- Implement a z-buffer for correct depth testing
- Use better noise functions for terrain generation
- Add texture mapping
- Implement proper input handling for real-time camera control
The implementation demonstrates the core concepts of 3D rendering from scratch in Go, including matrix transformations, camera movement, and basic terrain generation.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.