-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
615 lines (387 loc) · 14.4 KB
/
data.py
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# -*- coding: utf-8 -*-
#
"""Module for data representation."""
import uuid
import collections
import logging
import multiprocessing as mp
from math import sqrt
# from decorators import print_time
from functions import generate_chunk
from functions import generate_chunk_mp
log = logging.getLogger(__name__)
class ChunkCreator(object):
def __init__(self, chunk_dict, workers=2):
self.orig_dict = chunk_dict
self.active_tasks = []
self.prepared_chunks = {}
self.ready_chunks = collections.deque()
self.pool = mp.Pool(workers)
def add_task(self, chunk_position):
log.debug("New ChunkCreator task: {}".format(chunk_position))
self.active_tasks.append(chunk_position)
def task_exists(self, position):
if position in self.active_tasks:
return True
else:
return False
def add_ready_chunk(self, position):
self.ready_chunks.append(position)
def add_blocks(self, chunk_type, position, blocks):
self.prepared_chunks[position] = chunk_type, blocks
def create(self, chunk_type, chunk_position):
"""
Args:
chunk_position (int, int): X and Z coordinates
"""
width = chunk_type.size
height = chunk_type.height
if self.task_exists(chunk_position):
return
self.add_task(chunk_position)
self.pool.apply_async(
generate_chunk_mp,
args=(chunk_type, chunk_position, width, height),
callback=self.chunk_done
)
def build_ready_chunks(self):
if len(self.ready_chunks) > 0:
chunk_position = self.ready_chunks.popleft()
chunk_type = self.prepared_chunks[chunk_position][0]
blocks = self.prepared_chunks[chunk_position][1]
self.build_chunk(chunk_type, chunk_position, blocks)
log.debug("ChunkCreator task {} done.".format(chunk_position))
def build_chunk(self, chunk_type, chunk_position, blocks):
position_point = Point(chunk_position[0], 0, chunk_position[1])
new_chunk = chunk_type(position_point, blocks=blocks)
self.active_tasks.remove(chunk_position)
self.orig_dict[chunk_position] = new_chunk
def chunk_done(self, data):
chunk_type = data[0]
chunk_position = data[1]
chunk_blocks = data[2]
self.add_blocks(chunk_type, chunk_position, chunk_blocks)
self.add_ready_chunk(chunk_position)
log.debug("chunk done")
def update(self):
log.debug("Active ChunkCreator tasks: {}".format(
len(self.active_tasks)))
self.build_ready_chunks()
def wait_for_procs(self):
self.pool.close()
self.pool.join()
class Point(object):
"""Store data for point in 3D space.
Args:
x (float): x position
y (float): y position
z (float): z position
"""
def __init__(self, x, y, z):
self.x = 0
self.y = 0
self.z = 0
self.set_position(x, y, z)
def __str__(self):
"""Return string representation."""
return "Position: x={}, y={}, z={}".format(self.x, self.y, self.z)
def __eq__(self, other):
if not isinstance(other, Point):
return False
if self.x == other.x and self.y == other.y and self.z == other.z:
return True
def __ne__(self, other):
return not self == other
def set_position(self, x, y, z):
"""Set point position."""
self.x = x
self.y = y
self.z = z
def chunk_distance(self, chunk_pos):
"""Return distance of chunk from self instance.
Args:
chunk_pos (Point): position of chunk
"""
x_dist = chunk_pos.x - self.x
z_dist = chunk_pos.z - self.z
distance = sqrt(pow(x_dist, 2) + pow(z_dist, 2))
return distance
class Block(object):
"""Data representation for block.
Attributes:
structure: block structure
parents (list): block's parents
children (list): block's children
"""
def __init__(self):
# real structure
self.structure = None
# lists of parents and children
self.parents = None
self.children = None
def __str__(self):
"""Return string representation."""
return 'Block'
def __repr__(self):
return self.__str__()
class BlockInfo(object):
"""Auxiliary mapping class.
Args:
chunk (Chunk): chunk object
position ((x, y, z)): position of block
Attributes:
position ((x, y, z)): position of block
chunk_id (str): ID of chunk
chunk_position (Point): position of chunk
"""
def __init__(self, chunk, position):
self.position = position
self.chunk_id = chunk.chunk_id
self.chunk_position = chunk.position
class Chunk(object):
"""Base class for chunks.
Args:
position (Point): position of chunk
Attributes:
position (Position): position of chunk
centre (Point): centre point of chunk
chunk_id (str): ID of chunk
dirty (bool): indicates changes in chunk
visible (bool): stores visibility for chunk
blocks (dict): dictionary of Block objects, key is (x, y, z) of int
"""
size = None
height = None
def __init__(self, position, blocks=None):
self.position = position
self.centre = Point(
position.x + self.size / 2,
0,
position.z + self.size / 2
)
self.chunk_id = str(uuid.uuid4())
self.dirty = False
self.visible = False
if blocks:
self.blocks = blocks
else:
self.blocks = self.generate_chunk()
def get_centre(self):
"""Return centre of chunk as a Point object."""
return self.centre
def generate_chunk(self):
"""Generate chunk data.
Return:
dict: {(x, y, z) of int: Block}
"""
blocks = generate_chunk(self.size, self.height)
return blocks
def block_collision(self, point):
"""Return collision block info.
Args:
point (Point): the collision point
Return:
BlockInfo or None: info about block
"""
selected_blocks = [] # (x, y, z)
for x in range(int(point.x - 2 - self.position.x),
int(point.x + 2 - self.position.x)):
for y in range(int(point.y - 2 - self.position.y),
int(point.y + 2 - self.position.y)):
for z in range(int(point.z - 2 - self.position.z),
int(point.z + 2 - self.position.z)):
if x < 0 or x >= self.size:
pass
elif y < 0 or y >= self.height:
pass
elif z < 0 or z >= self.size:
pass
else:
selected_blocks.append((x, y, z))
for block in selected_blocks:
if abs(block[0] + self.position.x - point.x) < 0.5:
if abs(block[1] + self.position.y - point.y) < 0.5:
if abs(block[2] + self.position.z - point.z) < 0.5:
if self.blocks[block] is not None:
return BlockInfo(self, block)
return None
def collision(self, point):
"""Return boolean value of collision for the point.
Args:
point (Point): check collision for this point
"""
# debug info
# counter = 0
# list of (x, y, z) of int
selected_blocks = []
for x in range(int(point.x - 2 - self.position.x),
int(point.x + 2 - self.position.x)):
for y in range(int(point.y - 2 - self.position.y),
int(point.y + 2 - self.position.y)):
for z in range(int(point.z - 2 - self.position.z),
int(point.z + 2 - self.position.z)):
if x < 0 or x >= self.size:
pass
elif y < 0 or y >= self.height:
pass
elif z < 0 or z >= self.size:
pass
else:
selected_blocks.append((x, y, z))
for block in selected_blocks:
if abs(block[0] + self.position.x - point.x) < 0.5:
if abs(block[1] + self.position.y - point.y) < 0.5:
if abs(block[2] + self.position.z - point.z) < 0.5:
if self.blocks[block] is not None:
# print("Collision: {}".format(block))
# print(counter)
return True
# counter += 1
return False
# if self.block_collision(point) != None:
#
# return True
#
# else:
#
# return False
def __str__(self):
"""String representation of chunk."""
return 'Chunk: ' + str(self.blocks)
def __repr__(self):
return self.__str__()
class SmallChunk(Chunk):
"""Small chunk - 2 x 2 x 128 blocks."""
# size of chunk side
size = 2
# height of chunk
height = 128
def __str__(self):
"""String representation of chunk."""
return 'SmallChunk: ' + str(self.blocks)
class NormalChunk(Chunk):
"""Normal chunk - 8 x 8 x 128 blocks."""
# size of chunk side
size = 8
# height of chunk
height = 128
def __str__(self):
"""String representation of chunk."""
return "NormalChunk: {} blocks".format(len(self.blocks))
class BlockWorld(object):
"""World encapsulates blocks in chunks."""
def __init__(self, chunk_type, width, depth):
self.chunk_type = chunk_type
self.chunk_size = self.chunk_type.size
self.chunk_offset = 0.5
self.width = width
self.depth = depth
self.chunks = {}
self.chunk_creator = ChunkCreator(self.chunks)
self.generate_world()
def in_chunk(self, point):
"""Return chunk key according the point.
Args:
point (Point): find chunk including this point
"""
for position, chunk in self.chunks.items():
x_dist = point.x - position[0] + self.chunk_offset
z_dist = point.z - position[1] + self.chunk_offset
if (0 < x_dist < chunk.size) and (0 < z_dist < chunk.size):
return position
def collision(self, point):
"""Return collision with a world as a boolean.
Args:
point (Point): check collision for the point
Return:
bool: point collision with the world
"""
# temporary solution
# TODO: change
point.z = -point.z
offset = 0.5
# counter = 0
for chunk in self.chunks:
if (chunk[0] < point.x + offset and
point.x - offset < chunk[0] + self.chunk_size):
if (chunk[1] < point.z + offset and
point.z - offset < chunk[1] + self.chunk_size):
if self.chunks[chunk].collision(point):
# print(counter)
return True
# counter += 1
return False
def __str__(self):
"""String representation for world."""
return "BlockWorld: {} chunks".format(len(self.chunks))
def generate_chunk(self, position, async=True):
"""Generate chunk.
Args:
position ((int, int)): position of chunk in a world
"""
if not self.chunk_exists(position):
# print("Creating new chunk: {}".format(position))
# create chunk with creator
if async:
self.chunk_creator.create(self.chunk_type, position)
else:
self.chunks[position] = self.chunk_type(
Point(position[0], 0, position[1]))
def update_chunks(self):
self.chunk_creator.update()
def chunk_exists(self, position):
"""Return chunk existence on the position.
Args:
position ((int, int)): chunk position/key (x, z)
"""
return position in self.chunks
def find_necessary_chunks(self, point, distance):
"""Find necessary chunks in the distance.
Args:
point (Point): centre point
distance (int): distance
Return:
list: list of necessary chunks positions
"""
offset = self.chunk_size / 2
min_x = int(point.x - distance) - offset
min_z = int(point.z - distance) - offset
max_x = int(point.x + distance) - offset
max_z = int(point.z + distance) - offset
positions = []
for x_pos in range(min_x, max_x):
for z_pos in range(min_z, max_z):
if (x_pos % self.chunk_size == 0 and
z_pos % self.chunk_size == 0):
if sqrt(pow((x_pos + offset) - point.x, 2)
+ pow((z_pos + offset) - point.z, 2)) > distance:
pass
else:
positions.append((x_pos, z_pos))
return positions
def find_nearest_chunks(self, point):
return self.find_necessary_chunks(point, 7)
def block_collision(self, point, chunks):
for chunk in chunks:
print(self.chunks[chunk].block_collision(point))
def generate_chunks(self, point, distance):
necessary_chunks = self.find_necessary_chunks(point, distance)
for position in necessary_chunks:
self.generate_chunk(position)
def set_visibility(self, point, distance):
"""Set chunks visibility.
Args:
point (Point): observer position
distance (int): max distance
"""
for position, chunk in self.chunks.items():
if point.chunk_distance(chunk.get_centre()) > distance:
chunk.visible = False
else:
chunk.visible = True
def generate_world(self):
"""Generate world from chunks."""
for x in range(0, self.width, self.chunk_size):
for z in range(0, self.depth, self.chunk_size):
# self.chunks[(x, z)] = self.chunk_type(Point(x, 0, z))
self.generate_chunk((x, z), async=False)