-
Notifications
You must be signed in to change notification settings - Fork 1
/
noise.py
546 lines (436 loc) · 17.3 KB
/
noise.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
import random
import math
import block
import logger
import net
class Random:
m = 4294967296
a = 1664525
c = 1
def __init__(self, seed: int):
self.values = {
-1: self._gen(seed + 1),
0: seed,
1: self._gen(seed)
}
self.min_gen = -1
self.max_gen = 1
def gen(self, i: int) -> float:
if i in self.values:
return self.values[i] / self.m
else:
if i > self.max_gen:
for j in range(self.max_gen, i+2):
self.values[j+1] = self._gen(self.values[j])
else:
# print('less', self.min_gen, i-2, list(range(self.min_gen, i-2)))
j = self.min_gen
while j != i-1:
self.values[j-1] = self._gen(self.values[j])
j -= 1
return self.values[i] / self.m
def _gen(self, seed):
seed = (self.a * seed + self.c) % self.m
return seed
def save(self):
return {
'values': self.values,
'min': self.min_gen,
'max': self.max_gen
}
def load(self, raw: dict):
# json does not allow int indexes?
self.values = {int(i): raw['values'][i] for i in raw['values']}
self.min_gen = raw['min']
self.max_gen = raw['max']
class generator:
def __init__(self, seed, floor=10, clamp=None):
self.seed = seed
self.clamp = clamp
self.generator = Random(self.seed)
# holes in the floor are a feature
# a start to generate more world next to
self.generated = {i: floor for i in range(-10, 11)}
self.min_gen = -10
self.min_gen_value = self.generated[self.min_gen]
self.min_gen_slope = 0
self.max_gen = 10
self.max_gen_value = self.generated[self.max_gen]
self.max_gen_slope = 0
def gen(self, i):
if i in self.generated:
return self.generated[i]
else:
if i < self.min_gen - 1:
for x in range(self.min_gen, i - 1, -1):
self._gen(x)
elif i > self.max_gen + 1:
for x in range(self.max_gen, i + 1):
self._gen(x)
else:
self._gen(i)
return self.generated[i]
def _gen(self, i):
if i in self.generated:
return self.generated[i]
else:
if i == self.min_gen - 1:
self.min_gen_slope = min(max(-1, self.min_gen_slope + int(self.generator.gen(i) * 3) - 1), 1)
self.min_gen_value += self.min_gen_slope
if self.clamp is not None:
self.min_gen_value = min(max(self.clamp[0], self.min_gen_value), self.clamp[1])
if self.min_gen_value in self.clamp:
self.min_gen_slope = 0
self.generated[i] = self.min_gen_value
self.min_gen = i
elif i == self.max_gen + 1:
self.max_gen_slope = min(max(-1, self.max_gen_slope + int(self.generator.gen(i) * 3) - 1), 1)
self.max_gen_value += self.max_gen_slope
if self.clamp is not None:
self.max_gen_value = min(max(self.clamp[0], self.max_gen_value), self.clamp[1])
if self.max_gen_value in self.clamp:
self.max_gen_slope = 0
self.generated[i] = self.max_gen_value
self.max_gen = i
else:
logger.warn(f"generating default value 10 for index {i}")
self.generated[i] = 10
if self.clamp is not None:
self.generated[i] = min(max(self.clamp[0], self.generated[i]), self.clamp[1])
return self.generated[i]
def load(self, raw: dict):
self.seed = raw['seed']
self.generated = raw['gen']
self.min_gen = raw['min_gen']
self.min_gen_value = raw['min_gen_value']
self.min_gen_slope = raw['min_gen_slope']
self.max_gen = raw['max_gen']
self.max_gen_value = raw['max_gen_value']
self.max_gen_slope = raw['max_gen_slope']
self.generator.load(raw['generator'])
def save(self):
return {
'seed': self.seed,
'gen': self.generated,
'min_gen': self.min_gen,
'min_gen_value': self.min_gen_value,
'min_gen_slope': self.min_gen_slope,
'max_gen': self.max_gen,
'max_gen_value': self.max_gen_value,
'max_gen_slope': self.max_gen_slope,
'generator': self.generator.save()
}
class Perlin_generator:
def __init__(self, seed, scale):
self.scale = scale
generator = Random(seed)
small_seed = generator._gen(seed + 2)
self.small_generator = Random(small_seed)
big_seed = generator._gen(seed + 4)
self.big_generator = Random(big_seed)
def gen(self, i):
x = i // self.scale
# + self.big_generator.gen((x + 1) // self.scale) * self.scale * self.scale
a = (i - x * self.scale) / self.scale
out = self._interp(
self.small_generator.gen(x) * self.scale,
self.small_generator.gen(x + 1) * self.scale,
a
)
i = i / self.scale
x = int(i // self.scale)
a = (i - x * self.scale) / self.scale
out += self._interp(
self.big_generator.gen(x) * self.scale,
self.big_generator.gen(x + 1) * self.scale,
a
) * self.scale
return round(out)
def _interp(self, a, b, x):
mu = math.cos(x * math.pi) / 2 + .5
return a * mu + b * (1 - mu)
def save(self):
return {
'scale': self.scale,
'big': self.big_generator.save(),
'small': self.small_generator.save()
}
def load(self, raw: dict):
self.scale = raw['scale']
self.big_generator.load(raw['big'])
self.small_generator.load(raw['small'])
class Perlin_filtered:
def __init__(self, seed, scale, floor):
self.perlin = Perlin_generator(seed, scale)
self.min_gen = -20
self.min_gen_value = floor
self.max_gen = 20
self.max_gen_value = floor
self.values = {i: floor for i in range(-20, 21)}
def gen(self, i):
if i in self.values:
return self.values[i]
else:
if i > self.max_gen:
for j in range(self.max_gen, i+1):
d = self.perlin.gen(j)
if d == self.max_gen_value:
pass
elif d > self.max_gen_value:
self.max_gen_value += 1
else:
self.max_gen_value -= 1
self.max_gen += 1
self.values[self.max_gen] = self.max_gen_value
else:
if self.min_gen < i:
logger.warn(f'warning: discrepancy between min_gen and max_gen, returning min_gen_value')
return self.min_gen_value
j = self.min_gen
while j != i:
d = self.perlin.gen(j)
if d == self.min_gen_value:
pass
elif d > self.min_gen_value:
self.min_gen_value += 1
else:
self.min_gen_value -= 1
self.min_gen -= 1
self.values[self.min_gen] = self.min_gen_value
j -= 1
return self.values[i]
def load(self, raw: dict):
self.min_gen = raw['min_gen']
self.min_gen_value = raw['min_gen_value']
self.max_gen = raw['max_gen']
self.max_gen_value = raw['max_gen_value']
self.perlin.load(raw['generator'])
def save(self):
return {
'min_gen': self.min_gen,
'min_gen_value': self.min_gen_value,
'max_gen': self.max_gen,
'max_gen_value': self.max_gen_value,
'generator': self.perlin.save()
}
class world:
def __init__(self, seed: int, floor: int, game, gen_new=True, server=None, serving=False):
self.gen = Perlin_filtered(seed, 40, floor)
self.temperature_gen = generator(seed, 20, (-50, 50))
self.cloud_gen = generator(seed + 1, floor=0, clamp=(0, 5))
self.world = {}
self.game = game
self.gen_new = gen_new
self.server = server
self.serving = serving
self.blocks = block.load()
self.to_update = [] # TODO: make this update entire chunks instead of blocks
self.to_append = []
self.filename = None
if self.serving and self.server is None:
assert False, 'you did it wrong'
if self.server is not None:
if type(self.server) is not net.Server and type(self.server) is not net.client:
print(self.server)
raise ValueError('???????????????????')
def gen_chunk(self, x, y):
# print('chunk', x)
# if self.filename is not None:
# with open('saves/' + self.filename, 'r') as file:
# w = json.load(file)
# if x in w:
# return w[x]
if (x, y) in self.world:
return
c = []
for dy in range(40):
line = []
for dx in range(40):
line.append(block.block('air', self.blocks))
c.append(line)
if y <= 0:
temperature = self.temperature_gen.gen(x) + y
for i in range(40):
height = self.gen.gen(i + x * 40) + y * 40
for dy in range(min(height, 40)):
if temperature > 40:
bn = 'sand'
elif temperature > 30:
bn = 'dirt'
elif temperature > 3:
bn = 'grass'
elif temperature > 0:
bn = 'dirt'
else:
bn = 'ice'
if dy == 0 and y == 0:
b = block.block('bedrock', self.blocks)
elif dy == height - 1:
b = block.block(bn, self.blocks)
elif dy == height - 2:
b = block.block(bn, self.blocks)
elif dy == height - 3:
if temperature > 41:
bn = 'sand'
elif temperature > -10:
bn = 'dirt'
else:
bn = 'ice'
b = block.block(bn, self.blocks)
elif dy == height - 4:
if temperature > 42:
bn = 'sand'
elif temperature > -20:
bn = 'dirt'
else:
bn = 'ice'
b = block.block(bn, self.blocks)
elif dy == height - 5:
if temperature > 43:
bn = 'sand'
elif temperature > -30:
bn = 'dirt'
else:
bn = 'ice'
b = block.block(bn, self.blocks)
else:
if height - dy - 1 > 100 and random.random() > max(.99, 1 - (height - dy - 101) / 10):
b = block.block('diamond', self.blocks)
elif height - dy - 1 > 100 and random.random() > .9 - (height - dy - 101) / 50:
b = block.block('coal', self.blocks)
else:
b = block.block('stone', self.blocks)
b.x = i + x * 40
b.y = 39 - dy + y * 40
b.support = height - dy - 1
b.on_floor = True
c[39 - dy][i % 40] = b
for i in range(40):
if y * 40 == -800:
if c[0][i % 40].name == 'air':
for j in range(self.cloud_gen.gen(i + x * 40)):
c[j][i % 40] = block.block('cloud', self.blocks)
self.world[(x, y)] = c
def get(self, x, y):
if (x // 40, y // 40) in self.world:
return self.world[(x // 40, y // 40)][y % 40][x % 40]
else:
if self.gen_new:
self.gen_chunk(x // 40, y // 40)
else:
if self.server is not None:
self.server.get_chunk(x // 40, y // 40)
else:
raise ValueError('if world.gen_new == False, you should give net.client')
if (x // 40, y // 40) in self.world:
return self.get(x, y)
else:
return block.block('air', self.blocks)
def set(self, x, y, value: block.block, update=True, block_update=True):
value.x = x
value.y = y
if y < 40:
if self.gen_new and block_update:
self.to_append += [self.get(value.x - 1, value.y), self.get(value.x, value.y - 1),
self.get(value.x + 1, value.y), self.get(value.x, value.y + 1),
self.get(value.x + 1, value.y + 1), self.get(value.x + 1, value.y - 1),
self.get(value.x - 1, value.y + 1), self.get(value.x - 1, value.y - 1), value]
if (x // 40, y // 40) in self.world:
self.world[(x // 40, y // 40)][y % 40][x % 40] = value
if self.server is not None and self.serving and update:
self.server.send_all('AP' + str(x) + ' ' + str(y) + ' ' + value.name)
elif self.server is not None and not self.serving and update: # multiplayer client
self.server.set_block(x, y, value)
else:
self.get(x, y) # load the chunk
def update(self, tick: int) -> int:
update_amount = 0
for b in self.to_update:
if b.y is not None:
if b.y < 40:
if b.last_update_tick != tick:
update_amount += 1
self.to_append += b.update(self)
b.last_update_tick = tick
self.to_update = self.to_append
self.to_append = []
return update_amount
# TODO: chunk unloading
def save(self):
w = {}
for i in self.world:
c = []
for j in self.world[i]:
row = []
for b in j:
if type(b) != block.block:
logger.warn(f"block {b} in chunk {i[0]}, {i[1]} is not a Block")
# print('error:', b)
row.append({'name': 'air', 'support': 0})
else:
row.append({'name': b.name, 'support': b.support})
c.append(row)
w[str(i[0]) + ' ' + str(i[1])] = c
w['data'] = {}
w['data']['gen'] = self.gen.save()
return w
def load(self, raw: dict):
# TODO: this is really slow
self.world = {}
logger.log(f'world chunks size {len(raw.keys())}')
for i in raw:
if i != 'data':
c = []
y = int(i.split(' ')[1]) * 40
for j in raw[i]:
row = []
x = int(i.split(' ')[0]) * 40
for ib in j:
b = block.block(ib['name'], self.blocks)
b.support = ib['support']
b.x = x
b.y = y
b.on_floor = True
row.append(b)
x += 1
y += 1
c.append(row)
# print(i)
self.world[(int(i.split(' ')[0]), int(i.split(' ')[1]))] = c
else:
self.gen.load(raw[i]['gen'])
# TODO: also load other players if multiplayer server
logger.log('Loaded!')
def serialize_chunk(self, x, y):
# TODO: a way to make client and server agree on block ids and send binary data instead of csv
out = ''
if (x, y) not in self.world:
self.gen_chunk(x, y)
chunk = self.world[(x, y)]
for row in chunk:
for b in row:
out += b.name + ','
return out
def deserialise_chunk(self, data: str):
chunk = []
split = data.split(' ')
if len(split) != 3:
raise Exception('chunk incorrectly formatted')
x = 0
y = 0
row = []
for b in split[2].split(','):
b = block.block(b, self.blocks)
b.x = x
b.y = y
row.append(b)
x += 1
if x == 40:
chunk.append(row)
row = []
x = 0
y += 1
logger.warn(f'deserialised chunk {int(split[0])} {int(split[1])}, size: {len(chunk[0])}, {len(chunk)}')
self.world[(int(split[0]), int(split[1]))] = chunk
# warn(self.world[(int(split[0]), int(split[1]))][39][20].name)
# warn(str([c for c in self.world]))