-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLayeredWorldGeneratorUpdated.gd
379 lines (312 loc) · 12.8 KB
/
LayeredWorldGeneratorUpdated.gd
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
# Generates an infinite world using a layered approach, allowing each layer to
# access the previous layers' data. Each layer is smaller than the next, so they
# can also access their neighbors' data.
class_name LayeredWorldGenerator
extends WorldGenerator
const PLANET_BASE_SIZE := 96
const MOON_BASE_SIZE := 32
const ASTEROID_BASE_SIZE := 16
var start_time
# Used to calculate the 8 neighbors around any one sector.
const NEIGHBORS := [
Vector2(1, 0),
Vector2(1, 1),
Vector2(0, 1),
Vector2(-1, 1),
Vector2(-1, 0),
Vector2(-1, -1),
Vector2(0, -1),
Vector2(1, -1)
]
const LAYERS = {
seeds = [],
planet = {},
moons = [],
travel_lanes = [],
asteroids = [],
}
## Hides or shows the grid and the planetary seeding points.
export var show_debug := false setget _set_show_debug
## Percentage to keep the planetary seeding points away from the sector edges.
export var sector_margin_proportion := 0.1
## The maximum area covered by the three seeding vertices for a planet to form.
export var planet_generation_area_threshold := 5000.0
## The probability of a moon being generated next to a planet.
export var moon_generation_chance := 1.1 / 3.0
export var max_moon_count := 5
## The probability of asteroids being generated next to a planet.
export var asteroid_generation_chance := 3.0 / 4.0
## The maximum number of asteroids we can generate in one sector.
export var max_asteroid_count := 10
## The pixel value of the margin calculated from the margin percentage
onready var _sector_margin := sector_size * sector_margin_proportion
onready var _player := $Player
onready var _grid_drawer := $GridDrawer
export var generate_on_cloud := true
func _ready() -> void:
if not generate_on_cloud:
generate()
_grid_drawer.setup(sector_size, sector_axis_count)
_grid_drawer.visible = show_debug
else:
pass
func convertStringToVector2(pair: String) -> Vector2:
var vector2key = pair
vector2key.erase(vector2key.find("("),1)
vector2key.erase(vector2key.find(")"),1)
vector2key.erase(vector2key.find(","),1)
var x = vector2key.left(vector2key.find(" "))
var y = vector2key.right(vector2key.find(" "))
return Vector2(x,y)
func _on_HTTPRequest_request_completed( result, response_code, headers, body):
_sectors = parse_json(body.get_string_from_utf8())
for key in _sectors.keys():
var vector2key = convertStringToVector2(key)
_sectors[vector2key] = _sectors[key]
_sectors.erase(key)
for value in _sectors.values():
if "seeds" in value:
for i in range(value.seeds.size()):
value.seeds[i] = Vector2(value.seeds[i][0], value.seeds[i][1])
if "planet" in value:
value.planet.position = Vector2(value.planet.position[0], value.planet.position[1])
if "moons" in value:
for moon in value.moons:
value.moons.moon.position = Vector2(value.moons.moon.position[0], value.moons.moon.position[1])
if "travel_lanes" in value:
for lane in value.travel_lanes:
value.travel_lanes.lane.position = Vector2(value.travel_lanes.lane.position[0], value.travel_lanes.lane.position[1])
if "asteroids" in value:
for asteroid in value.asteroids:
value.asteroids.asteroid.position = Vector2(value.asteroids.asteroid.position[0], value.asteroids.asteroid.position[1])
update()
_grid_drawer.setup(sector_size, sector_axis_count)
_grid_drawer.visible = show_debug
## Generates the world with a layered approach. Each layer requires another
## layer before it to already be generated. Seeds are generated first and
## furthest from the center, then planets one row/column less, then moons one
## row/column less, then travel lanes, then asteroids nearest to the player.
## This creates our world's layers, each one smaller than the one before it, but
## all contained within the player's view (normally.)
func generate() -> void:
start_time = OS.get_ticks_msec()
var index := -1
for layer in LAYERS:
index += 1
for x in range(
_current_sector.x - _half_sector_count + index,
_current_sector.x + _half_sector_count - index
):
for y in range(
_current_sector.y - _half_sector_count + index,
_current_sector.y + _half_sector_count - index
):
var sector = Vector2(x, y)
match layer:
"seeds":
# Initialize the sector's data at the start.
if not _sectors.has(sector):
_sectors[sector] = LAYERS.duplicate(true)
_generate_seeds_at(sector)
"planet":
_generate_planets_at(sector)
"moons":
_generate_moons_at(sector)
"travel_lanes":
_generate_travel_lanes_at(sector)
"asteroids":
_generate_asteroids_at(sector)
var end_time = OS.get_ticks_msec()
print((end_time - start_time))
update()
# Draws the generated data.
func _draw() -> void:
for data in _sectors.values():
# Draw seeding points.
if "seeds" in data:
if show_debug and data.seeds:
for point in data.seeds:
draw_circle(point, 12, Color(0.5, 0.5, 0.5, 0.5))
if "planet" in data:
if data.planet:
draw_circle(data.planet.position, PLANET_BASE_SIZE * data.planet.scale, Color.bisque)
if "moons" in data:
for moon in data.moons:
draw_circle(moon.position, MOON_BASE_SIZE * moon.scale, Color.aquamarine)
if "travel_lanes" in data:
for path in data.travel_lanes:
var start: Vector2 = path.source
var end: Vector2 = path.destination
draw_line(start, end, Color.cornflower, 6.0)
if "asteroids" in data:
for asteroid in data.asteroids:
draw_circle(asteroid.position, ASTEROID_BASE_SIZE * asteroid.scale, Color.orangered)
# Whenever the player changes sector, erase those that fall out of scope and generate new ones
func _physics_process(_delta: float) -> void:
var sector_offset := Vector2.ZERO
var sector_location := _current_sector * sector_size
if _player.global_position.distance_squared_to(sector_location) > _total_sector_count:
sector_offset = (_player.global_position - sector_location) / sector_size
sector_offset.x = int(sector_offset.x)
sector_offset.y = int(sector_offset.y)
_update_sectors(sector_offset)
_grid_drawer.move_grid_to(_current_sector)
# Erases old sectors by difference, and generates new ones. Since our generation
# algorithm is more complex than the default generation, we override _update_along_axis
# to only delete and then call generate again to fill in any created gaps in the layers.
func _update_sectors(difference: Vector2) -> void:
_update_along_axis(AXIS_X, difference.x)
_update_along_axis(AXIS_Y, difference.y)
generate()
## Seeds a triangle inside of the `sector`. The next layer can use these to make
## planets. Their overall density and proximity to one another may or may not
## birth a planet.
func _generate_seeds_at(sector: Vector2) -> void:
if _sectors[sector].seeds:
return
# Create a seed for the current sector's triangular seeds
_rng.seed = make_seed_for(sector.x, sector.y, "seeds")
# Find the boundaries of the sector +/- some padding
var half_size := Vector2(_half_sector_size, _half_sector_size)
var margin := Vector2(_sector_margin, _sector_margin)
var top_left := sector * sector_size - half_size + margin
var bottom_right := sector * sector_size + half_size - margin
# Generates 3 points to create a triangle using white noise.
# These points' 'density' will be used to decide in the next layer whether
# there should be a planet in this sector.
var seeds := []
for _i in range(3):
var seed_position := Vector2(
_rng.randf_range(top_left.x, bottom_right.x),
_rng.randf_range(top_left.y, bottom_right.y)
)
seeds.append(seed_position)
_sectors[sector].seeds = seeds
# Potentially generate a planet in a given sector. They can only be one planet
# in a sector.
func _generate_planets_at(sector: Vector2) -> void:
if _sectors[sector].planet:
return
# Calculate the area created by the 3 seeded points.
var vertices: Array = _sectors[sector].seeds
var area := _calculate_triangle_area(vertices[0], vertices[1], vertices[2])
# If the area is less than the generation threshold, create a planet appropriate
# to the seeds' area.
if area < planet_generation_area_threshold:
_sectors[sector].planet = {
position = _calculate_triangle_epicenter(vertices[0], vertices[1], vertices[2]),
scale = 0.5 + area / (planet_generation_area_threshold / 2.0)
}
# If there is a planet inside of a given sector, a loop begins and there is a
# chance of a moon being generated. The dice is rolled until it comes up
# negative.
func _generate_moons_at(sector: Vector2) -> void:
if _sectors[sector].moons != []:
return
# Get the sector's planet layer and check if there is a planet. If there is
# not, cancel and move on.
var planet: Dictionary = _sectors[sector].planet
if not planet:
return
# Generate a seed for moons in the sector
_rng.seed = make_seed_for(sector.x, sector.y, "moons")
# Keeps track of the number of generated moons.
var moon_count := 0
# If we roll below the moon chance, generate a moon in an orbit's distance of the planet
while _rng.randf() < moon_generation_chance or moon_count == max_moon_count:
var random_offset: Vector2 = (
Vector2.UP.rotated(_rng.randf_range(-PI, PI))
* planet.scale
* PLANET_BASE_SIZE
* 3.0
)
moon_count += 1
_sectors[sector].moons.append(
{position = planet.position + random_offset, scale = planet.scale / 3.0}
)
# If this sector has a planet, checks the 8 _sectors around it for neighbors.
# If there are planets in those _sectors, creates a lane between the two of them.
func _generate_travel_lanes_at(sector: Vector2) -> void:
if _sectors[sector].travel_lanes:
return
# If there is no planet, don't generate anything.
var planet: Dictionary = _sectors[sector].planet
if not planet:
return
# Check each neighbor for a planet. If there is one, create a dictionary that
# links the two worlds together with a line to indicate a trading partner.
for neighbor in NEIGHBORS:
var neighbor_sector: Vector2 = sector + neighbor
if not _sectors[neighbor_sector].planet:
continue
var neighbor_position: Vector2 = _sectors[neighbor_sector].planet.position
_sectors[sector].travel_lanes.append(
{source = planet.position, destination = neighbor_position}
)
# If this sector has a planet, does not have a moon and does not have any trade
# lanes (because they'd have been cleared out by the traders/miners),
# then a loop begins and there is 75% chance to generate a random asteroid around it.
func _generate_asteroids_at(sector: Vector2) -> void:
if _sectors[sector].asteroids:
return
# Check for planet, moons and travel lanes. If there is a planet and neither
# moon or travel lane, begin generating an asteroid belt in an orbit.
var planet: Dictionary = _sectors[sector].planet
if not planet or _sectors[sector].moons or _sectors[sector].travel_lanes:
return
_rng.seed = make_seed_for(sector.x, sector.y, "asteroids")
# Keep rolling the dice until it comes up greater than 75%, creating a new
# asteroid within an orbit's range of the planet
var count := 0
while _rng.randf() < asteroid_generation_chance and count < max_asteroid_count:
count += 1
var random_offset: Vector2 = (
Vector2.UP.rotated(_rng.randf_range(-PI, PI))
* planet.scale
* PLANET_BASE_SIZE
* _rng.randf_range(3.0, 4.0)
)
_sectors[sector].asteroids.append(
{position = planet.position + random_offset, scale = planet.scale / 5.0}
)
# Erases old _sectors. New ones are generated by the subsequent call to generate()
func _update_along_axis(axis: int, difference: float) -> void:
if difference == 0 or (axis != AXIS_X and axis != AXIS_Y):
return
# Find the current sector's row/column
var axis_current := _current_sector.x if axis == AXIS_X else _current_sector.y
# Find the edges of the row/column, perpendicular to the axis we're updating
var other_axis_min := (
(_current_sector.y if axis == AXIS_X else _current_sector.x)
- _half_sector_count
)
var other_axis_max := (
(_current_sector.y if axis == AXIS_X else _current_sector.x)
+ _half_sector_count
)
var axis_modifier: int = difference <= 0
# For each row/column between where we were and where we are now
for sector_index in range(1, abs(difference) + 1):
var axis_key := int(axis_current + (_half_sector_count - axis_modifier) * -sign(difference))
# Erase the entire row/column.
for other in range(other_axis_min, other_axis_max):
var key := Vector2(
axis_key if axis == AXIS_X else other, other if axis == AXIS_X else axis_key
)
_sectors.erase(key)
# Update the current sector for later reference
if axis == AXIS_X:
_current_sector.x += difference
else:
_current_sector.y += difference
func _set_show_debug(value: bool) -> void:
show_debug = value
if not is_inside_tree():
yield(self, "ready")
_grid_drawer.visible = show_debug
update()
## Returns the area of a triangle.
func _calculate_triangle_area(a: Vector2, b: Vector2, c: Vector2) -> float:
return abs(a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)) / 2.0
func _calculate_triangle_epicenter(a: Vector2, b: Vector2, c: Vector2) -> Vector2:
return (a + b + c) / 3.0