mtsatellite/common/basetilecreator.go

133 lines
2.7 KiB
Go
Raw Normal View History

// Copyright 2014 by Sascha L. Teichmann
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
package common
import (
"image/color"
"log"
"path/filepath"
"strconv"
)
const (
tileWidth = 18
tileHeight = 18
yOrderCapacity = 512
)
// To scan the whole height in terms of the y coordinate
// the database is queried in height units defined in the tileDepths table.
var tileDepths = [...][2]int16{
{1024, 1934},
{256, 1023},
{128, 255},
{64, 127},
{32, 63},
{16, 31},
{8, 15},
{4, 7},
{2, 3},
{0, 1},
{-1, 0},
{-4, -2},
{-8, -5},
{-16, -9},
{-32, -17},
{-64, -33},
{-128, -65},
{-256, -129},
{-1024, -257},
{-1934, -1025}}
type BaseTileCreator struct {
client *RedisClient
colors *Colors
renderer *Renderer
yOrder *YOrder
baseDir string
update bool
}
func NewBaseTileCreator(
client *RedisClient,
colors *Colors,
transparent bool,
baseDir string,
update bool) *BaseTileCreator {
renderer := NewRenderer(tileWidth, tileHeight, transparent)
return &BaseTileCreator{
client: client,
colors: colors,
renderer: renderer,
yOrder: NewYOrder(renderer, yOrderCapacity),
baseDir: baseDir,
update: update}
}
func (btc *BaseTileCreator) Close() error {
return btc.client.Close()
}
func (btc *BaseTileCreator) CreateTile(x, z int16, i, j int) error {
btc.renderer.Reset()
btc.renderer.SetPos(x, z)
btc.yOrder.Reset()
drawBlock := func(block *Block) {
if err := btc.yOrder.RenderBlock(block, btc.colors); err != nil {
log.Printf("WARN: rendering block failed: %s\n", err)
}
}
var c1, c2 Coord
nareas := make([]Area, 0, tileWidth*tileHeight/2)
oareas := make([]Area, 1, tileWidth*tileHeight/2)
oareas[0] = Area{
X1: 0, Z1: 0,
X2: int16(tileWidth) - 1, Z2: int16(tileHeight) - 1}
for _, yRange := range tileDepths {
c1.Y = yRange[0]
c2.Y = yRange[1]
nareas = btc.renderer.UncoveredAreas(nareas, oareas)
if len(nareas) == 0 {
break
}
for _, area := range nareas {
c1.X = area.X1 + x
c1.Z = area.Z1 + z
c2.X = area.X2 + x
c2.Z = area.Z2 + z
query := Cuboid{P1: c1, P2: c2}
if err := btc.client.QueryCuboid(query, drawBlock); err != nil {
return err
}
if err := btc.yOrder.Drain(btc.colors); err != nil {
log.Printf("WARN: rendering block failed: %s\n", err)
}
}
oareas, nareas = nareas, oareas[0:0]
}
image := btc.renderer.CreateShadedImage(
16, 16, (tileWidth-2)*16, (tileHeight-2)*16,
btc.colors, color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff})
2015-07-21 23:35:10 +02:00
path := filepath.Join(btc.baseDir, strconv.Itoa(i), strconv.Itoa(j)+".png")
log.Printf("Writing (%d, %d) to file %s\n", x, z, path)
if !btc.update {
return SaveAsPNG(path, image)
}
return SaveAsPNGAtomic(path, image)
}