change: Started rewriting parts of the project in Go

This commit is contained in:
Nicholas Novak
2023-10-28 21:40:29 -07:00
parent 7419412be4
commit c73a555b04
8 changed files with 275 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
package storage
import (
"encoding/json"
"os"
"git.nicholasnovak.io/nnovak/spatial-db/world"
)
func ReadChunkFromFile(chunkFile *os.File) (world.ChunkData, error) {
var chunkData world.ChunkData
if err := json.NewDecoder(chunkFile).Decode(&chunkData); err != nil {
return chunkData, err
}
return chunkData, nil
}

79
storage/simple_server.go Normal file
View File

@@ -0,0 +1,79 @@
package storage
import (
"encoding/json"
"errors"
"io/fs"
"os"
"git.nicholasnovak.io/nnovak/spatial-db/world"
)
const fileCacheSize = 8
type SimpleServer struct {
}
// Filesystem operations
func (s *SimpleServer) FetchChunk(pos world.ChunkPos) (world.ChunkData, error) {
chunkFileName := pos.ToFileName()
var chunkData world.ChunkData
chunkFile, err := os.Open(chunkFileName)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// There was no chunk that exists, create a blank one
chunkFile, err = os.Create(chunkFileName)
if err != nil {
return chunkData, err
}
// Initilize the file with some blank data
if err := json.NewEncoder(chunkFile).Encode(chunkData); err != nil {
return chunkData, err
}
} else {
return chunkData, err
}
}
return ReadChunkFromFile(chunkFile)
}
// Voxel server implementation
func (s *SimpleServer) ChangeBlock(
worldPosition world.BlockPos,
targetState world.BlockID,
) error {
chunk, err := s.FetchChunk(worldPosition.ToChunkPos())
if err != nil {
return err
}
chunk.SectionFor(worldPosition).UpdateBlock(worldPosition, targetState)
return nil
}
func (s *SimpleServer) ChangeBlockRange(
targetState world.BlockID,
start, end world.BlockPos,
) error {
panic("ChangeBlockRange is unimplemented")
}
func (s *SimpleServer) ReadBlockAt(pos world.BlockPos) (world.BlockID, error) {
chunk, err := s.FetchChunk(pos.ToChunkPos())
if err != nil {
return world.Empty, err
}
return chunk.SectionFor(pos).FetchBlock(pos), nil
}
func (s *SimpleServer) ReadChunkAt(pos world.ChunkPos) (world.ChunkData, error) {
return s.FetchChunk(pos)
}

13
storage/storage_server.go Normal file
View File

@@ -0,0 +1,13 @@
package storage
import "git.nicholasnovak.io/nnovak/spatial-db/world"
type StorageServer interface {
// Individual block-level interactions
ChangeBlock(targetState world.BlockID, world_position world.BlockPos) error
ChangeBlockRange(targetState world.BlockID, start, end world.BlockPos) error
ReadBlockAt(pos world.BlockPos) error
// Network-level operations
ReadChunkAt(pos world.ChunkPos) error
}