-
Notifications
You must be signed in to change notification settings - Fork 2
/
world.lua
135 lines (100 loc) · 2.46 KB
/
world.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
local bitser = require "lib.bitser"
local Chunk = require "chunk"
local World = {}
function World:new()
self.chunks = {}
self:load()
self._generated = false
return self
end
function World:save()
local chunks = {}
for i, v in pairs(self.chunks) do
for j, c in pairs(v) do
table.insert(chunks, {i, j, c.blocks})
end
end
bitser.dumpLoveFile("world.dat", chunks)
end
function World:load()
local chunks = bitser.loadLoveFile("world.dat")
for i, v in pairs(chunks) do
local x, z, blocks = v[1], v[2], v[3]
local chunk = Chunk(x, 0, z, self)
chunk.blocks = blocks
if self.chunks[x] == nil then self.chunks[x] = {} end
self.chunks[x][z] = chunk
end
end
function World:generateChunk(wx, wz)
if self._generated then return end
-- only allow one chunk to be generated at a time
self._generated = true
local x = math.floor((wx-1) / CHUNK_SIZE)
local z = math.floor((wz-1) / CHUNK_SIZE)
local chunk = Chunk(x, 0, z, self)
if self.chunks[x] == nil then self.chunks[x] = {} end
self.chunks[x][z] = chunk
end
function World:getChunk(x, z)
-- convert to chunk coordinates
local nx = math.floor((x-1) / CHUNK_SIZE)
local nz = math.floor((z-1) / CHUNK_SIZE)
local c = self.chunks[nx]
if c then return c[nz] end
return nil
end
function World:getBlock(x, y, z)
local chunk = self:getChunk(x, z)
if chunk then
return chunk:getBlock(x, y, z)
end
return 0
end
function World:setBlock(x, y, z, block)
local chunk = self:getChunk(x, z)
if chunk then
chunk:setBlock(x, y, z, block)
end
end
function World:updateBlockMesh(x, y, z)
for dx = -1, 1 do
for dz = -1, 1 do
local ix, iz = x + dx, z + dz
local chunk = self:getChunk(ix, iz)
chunk:updateBlockMesh(ix, y, iz)
chunk:updateBlockMesh(ix, y - 1, iz)
chunk:updateBlockMesh(ix, y + 1, iz)
end
end
end
function World:loadChunk(x, z)
local chunk = self:getChunk(x, z)
if chunk then
chunk.loaded = true
if not chunk.done and not chunk.thread:isRunning() then
chunk:load()
end
else
self:generateChunk(x, z)
end
end
function World:update(dt)
self._generated = false
for i, v in pairs(self.chunks) do
for j, chunk in pairs(v) do
if chunk.loaded then
chunk:update(dt)
end
chunk.loaded = false
end
end
end
function World:draw()
for i, v in pairs(self.chunks) do
for j, chunk in pairs(v) do
chunk:draw()
end
end
end
return World