-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcity.lua
More file actions
1633 lines (1453 loc) · 60.4 KB
/
city.lua
File metadata and controls
1633 lines (1453 loc) · 60.4 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local Queue = require("queue")
local Constants = require("constants")
local Consumption = require("consumption")
local GridUtil = require("grid-util")
local Util = require("util")
local FloorUpgradesQueue = require("floor-upgrades-queue")
--- @class Coordinates
--- @field x number
--- @field y number
--- @alias Direction
---| "south"
---| "east"
---| "north"
---| "west"
--- @alias BuildingType
---| "simple"
---| "residential"
---| "highrise"
---| "tycoon-treasury"
---| "garden"
--- @class BuildingConstruction
--- @field buildingType BuildingType
--- @field constructionTimeInTicks number
--- @class RoadEnd
--- @field direction Direction
--- @field coordinates Coordinates
--- @field additionalWeight number | nil
--- @alias CellType
---| "road"
---| "building"
---| "unused"
--- @class Cell
--- @field type CellType
--- @field roadSockets Direction[] | nil
--- @field entity any | nil
--- @field buildingType BuildingType | nil
--- @field createdAtTick number | nil
--- @alias RoadConnectionCount
---| "1"
---| "2"
---| "3"
--- @class ExcavationPit
--- @field coordinates Coordinates
--- @field createdAtTick number
--- @field buildingConstruction BuildingConstruction
--- @class City
--- @field id number
--- @field roadEnds Queue
--- @field grid (Cell)[][]
--- @field center Coordinates
--- @field buildingLocationQueue Queue
--- @field gardenLocationQueue Queue
--- @field excavationPits ExcavationPit[]
--- @field buildingCounts { BuildingType: number }
--- @field houseLocations Coordinates[]
--- @alias CollidableStatus
---| "free"
---| "only-straight-rail"
---| "blocked"
-- --- @param coordinates Coordinates
-- --- @return string key
-- local function buildCoordinatesKey(coordinates)
-- return coordinates.y .. "/" .. coordinates.x
-- end
-- local cachedDistances = {}
--- @param coordinates Coordinates
--- @return number distanceFromTownHall
local function getCachedDistance(coordinates, offsetY, offsetX, cityCenter)
-- local key = buildCoordinatesKey(coordinates)
-- if cachedDistances[key] ~= nil then
-- return cachedDistances[key]
-- else
local distance = Util.calculateDistance({
y = (coordinates.y + offsetY) * Constants.CELL_SIZE,
x = (coordinates.x + offsetX) * Constants.CELL_SIZE,
}, cityCenter)
-- cachedDistances[key] = distance
return distance
-- end
end
--- @param origin Coordinates
--- @param size number
--- @param allowDiagonal boolean
--- @param allowCenter boolean
--- @return Coordinates[] coordinates
local function getSurroundingCoordinates(origin, size, allowDiagonal, allowCenter)
local c = {}
if allowCenter then
table.insert(c, origin)
end
for i = -1 * size, size, 1 do
for j = -1 * size, size, 1 do
if (allowDiagonal or (math.abs(i) ~= math.abs(j))) then
if not(i == 0 and j == 0) then
table.insert(c, {
x = j + origin.x,
y = i + origin.y
})
end
end
end
end
return c
end
--- @param origin Coordinates
--- @param size number
--- @param city City
--- @return any
local function getCircularSurroundingCoordinates(origin, size, city)
local c = {}
for i = -1 * size, size, 1 do
for j = -1 * size, size, 1 do
-- The first condition excludes the center piece
-- The second condition excludes the four corners. Open for better solutions to make a circle.
if not(i == 0 and j == 0) and not(math.abs(i) == size and math.abs(j) == size) then
local coordinates = {
y = i + origin.y,
x = j + origin.x
}
-- The idea here is to sort the cells in a way that they are built first where it's closer
-- to the origin and the town center, since this function is currently only used for floor upgrades.
-- That should give the reconstruction work a more organic look and feel.
local distance_to_origin = Util.calculateDistance(origin, coordinates)
local distance_to_center = Util.calculateDistance(city.center, coordinates)
local key = math.ceil(distance_to_origin * distance_to_center)
-- We're incrementing the key on conflict, as that's relatively cheap given that "size" won't grow far.
while c[key] ~= nil do
key = key + 1
end
-- table.insert won't shift elements as we'd expect it for an array, if the table is not a perfect array-like struture
-- That may happen because of the distance based insert.
c[key] = coordinates
end
end
end
return c
end
--- @param area any
--- @param surface_index number
--- @param ignorables string[] | nil
local function removeCollidingEntities(area, surface_index, ignorables)
local printEntities = game.surfaces[surface_index].find_entities_filtered({
area=area,
type = {"tree", "simple-entity"}
})
for _, entity in pairs(printEntities) do
if ignorables ~= nil and #ignorables > 0 and Util.indexOf(ignorables, entity.name) ~= nil then
-- noop, skip ignorables
else
entity.destroy()
end
end
end
local function hasCliffsOrWater(area, surface_index)
local water = game.surfaces[surface_index].find_tiles_filtered{
area = area,
name = {
"deepwater",
"deepwater-green",
"out-of-map",
"water",
"water-green",
"water-shallow",
"water-mud",
"water-wube",
},
limit = 1
}
local cliffs = game.surfaces[surface_index].find_entities_filtered{
area = area,
name = { "cliff" },
limit = 1
}
return #water > 0 or #cliffs > 0
end
--- @param area any
--- @param surface_index number
local function isAreaFree(area, surface_index)
-- Water / Cliffs
if hasCliffsOrWater(area, surface_index) then
return false
end
local ignorables = {"huge-rock", "big-rock", "big-sand-rock", "dead-grey-trunk"}
local entities = game.surfaces[surface_index].find_entities_filtered({
area=area,
type={"tree"},
name=ignorables,
invert=true,
limit = 100,
})
return #entities == 0
end
--- @param city City
--- @param coordinates Coordinates
--- @param additionalIgnorables string[] | nil
--- @return CollidableStatus
local function checkForCollidables(city, coordinates, additionalIgnorables)
local startCoordinates = GridUtil.translateCityGridToTileCoordinates(city, coordinates)
local area = {
{startCoordinates.x, startCoordinates.y},
{startCoordinates.x + Constants.CELL_SIZE, startCoordinates.y + Constants.CELL_SIZE}
}
-- Water / Cliffs
if hasCliffsOrWater(area, city.surface_index) then
return "blocked"
end
local ignorables = {"huge-rock", "big-rock", "big-sand-rock", "dead-grey-trunk"}
if additionalIgnorables ~= nil and #additionalIgnorables >0 then
for _, value in ipairs(additionalIgnorables) do
table.insert(ignorables, value)
end
end
-- Too many trees / Other entities
local entities = game.surfaces[city.surface_index].find_entities_filtered({
area=area,
type={"tree"},
name=ignorables,
invert=true,
limit = 100,
})
if #entities == 0 then
return "free"
end
local straightRailCount = 0
for _, entity in ipairs(entities) do
if entity.name == "straight-rail" then
straightRailCount = straightRailCount + 1
end
end
if #entities == straightRailCount then
return "only-straight-rail"
else
return "blocked"
end
end
--- @param city City
local function expand_grid(city)
local old_size = GridUtil.getGridSize(city.grid)
local new_size = old_size + 2 -- Expand by 1 on each side
-- Shift rows downward to keep center
for y = new_size, 1, -1 do
city.grid[y] = city.grid[y - 1] or {}
end
-- Add new columns at the left and right
for y = 1, new_size do
table.insert(city.grid[y], 1, {type = "unused"})
city.grid[y][new_size] = {type = "unused"}
end
-- Fill up any nil fields with type=unused
for y = 1, #city.grid, 1 do
for x = 1, #city.grid, 1 do
if city.grid[y][x] == nil then
city.grid[y][x] = {type = "unused"}
end
end
end
end
--- @param city City
--- @param coordinates Coordinates
local function hasSurroundingRoad(city, coordinates)
local surroundsOfUnused = getSurroundingCoordinates(coordinates, 1, false)
for _, s in ipairs(surroundsOfUnused) do
local surroundingCell = GridUtil.safeGridAccess(city, s)
if surroundingCell ~= nil and surroundingCell.type == "road" then
return true
end
end
return false
end
--- @param coordinates Coordinates
--- @param direction Direction
--- @param distance number
--- @return Coordinates coordinates
local function continueInDirection(coordinates, direction, distance)
local newCoordinates
if direction == "south" then
newCoordinates = {x = coordinates.x, y = coordinates.y + distance}
elseif direction == "east" then
newCoordinates = {x = coordinates.x + distance, y = coordinates.y}
elseif direction == "north" then
newCoordinates = {x = coordinates.x, y = coordinates.y - distance}
elseif direction == "west" then
newCoordinates = {x = coordinates.x - distance, y = coordinates.y}
end
assert(newCoordinates ~= nil, "Coordinates must not be nil. Did you add a new direction?")
return newCoordinates
end
--- @param direction Direction The direction that the road previously extended into.
--- @return Direction direction The inverted direction
local function invertDirection(direction)
local invertedDirection
if direction == "north" then
invertedDirection = "south"
elseif direction == "south" then
invertedDirection = "north"
elseif direction == "east" then
invertedDirection = "west"
elseif direction == "west" then
invertedDirection = "east"
else
assert(false, "Invalid direction")
end
return invertedDirection
end
--- @param originalDirection Direction
--- @return Direction rightDirection
local function getRightDirection(originalDirection)
local rightDirection
if originalDirection == "north" then
rightDirection = "east"
elseif originalDirection == "south" then
rightDirection = "west"
elseif originalDirection == "east" then
rightDirection = "south"
elseif originalDirection == "west" then
rightDirection = "north"
else
assert(false, "Invalid direction")
end
return rightDirection
end
--- @param originalDirection Direction
--- @return Direction leftDirection
local function getLeftDirection(originalDirection)
local leftDirection
if originalDirection == "north" then
leftDirection = "west"
elseif originalDirection == "south" then
leftDirection = "east"
elseif originalDirection == "east" then
leftDirection = "north"
elseif originalDirection == "west" then
leftDirection = "south"
else
assert(false, "Invalid direction")
end
return leftDirection
end
--- @param city City
--- @param coordinates Coordinates
--- @param direction Direction
--- @return boolean
local function areStraightRailsOrthogonal(city, coordinates, direction)
local startCoordinates = GridUtil.translateCityGridToTileCoordinates(city, coordinates)
local area = {
{startCoordinates.x, startCoordinates.y},
{startCoordinates.x + Constants.CELL_SIZE, startCoordinates.y + Constants.CELL_SIZE}
}
-- Too many trees / Other entities
local entities = game.surfaces[city.surface_index].find_entities_filtered({
area=area,
name={"straight-rail"},
-- Only test 10 rail pieces, that should give us enough info
-- todo: how many straight rail pieces fit into 6x6 tiles?
limit = 10,
})
local left = getLeftDirection(direction)
local right = getRightDirection(direction)
for _, entity in ipairs(entities) do
if entity.name == "straight-rail" then
if entity.direction ~= defines.direction[left] and entity.direction ~= defines.direction[right] then
return false
end
end
end
return true
end
local streetIgnorables = {"big-electric-pole", "medium-electric-pole", "small-electric-pole", "small-lamp", "pipe-to-ground"}
--- @param city City
--- @param roadEnd RoadEnd
--- @param lookoutDirections Direction[]
--- @return boolean canBuild
local function testRoadDirection(city, roadEnd, lookoutDirections)
-- Test the compatibility of the directions
for _, direction in ipairs(lookoutDirections) do
local neighbourPosition = continueInDirection(roadEnd.coordinates, direction, 1)
local collidables = checkForCollidables(city, neighbourPosition, streetIgnorables)
if collidables == "blocked" then
return false
elseif collidables == "only-straight-rail" then
local isCrossing = areStraightRailsOrthogonal(city, neighbourPosition, direction)
if not isCrossing then
return false
end
end
-- This should never be fail, because the upstream function is supposed to expand the grid if the position is on the outsides
local neighbourCell = GridUtil.safeGridAccess(city, neighbourPosition, "testRoadDirection")
if neighbourCell == nil then
return false
end
-- Streets must not expand into buildings or collidables, but may expand into empty fields or streets
if neighbourCell.type == "unused" then
-- noop, cell is free
elseif neighbourCell.type == "building" then
return false
elseif neighbourCell.type == "road" then
if Util.indexOf(neighbourCell.roadSockets, invertDirection(direction)) ~= nil then
return false
end
elseif #neighbourCell == 1 and (neighbourCell[1] == "linear.vertical" or neighbourCell[1] == "linear.horizontal" or neighbourCell[1] == "town-hall" or neighbourCell[1] == "intersection") then
return false
end
-- Streets must not continue directly next to and parallel to each other
local neighboursSideDirections = {}
if direction == "north" or direction == "south" then
neighboursSideDirections = {"east", "west"}
elseif direction == "west" or direction == "east" then
neighboursSideDirections = {"south", "north"}
end
local neighboursSideNeighbours = {
continueInDirection(neighbourPosition, neighboursSideDirections[1], 1),
continueInDirection(neighbourPosition, neighboursSideDirections[2], 1),
}
for _, position in ipairs(neighboursSideNeighbours) do
local cell = GridUtil.safeGridAccess(city, position)
if cell ~= nil and cell.type == "road" then
local sockets = cell.roadSockets or {}
for _, socket in ipairs(sockets) do
if socket == direction or socket == invertDirection(direction) then
return false
end
end
end
end
end
return true
end
--- @return RoadConnectionCount[] connectionCountOptions
local function getRoadConnectionCountOptions()
if storage.tycoon_weighted_road_connections ~= nil then
return storage.tycoon_weighted_road_connections
end
local weightedValues = {}
-- Each value describes how many road connections should be built.
-- weightedValues["0"] = 1
weightedValues["3"] = 1
weightedValues["2"] = 2
-- One connection will later be randomized again if it should be a corner or a straight.
weightedValues["1"] = 5
local values = {}
for value, weight in pairs(weightedValues) do
for _i = 1, weight, 1 do
table.insert(values, value)
end
end
storage.tycoon_weighted_road_connections = values
return values
end
local function shuffle(tbl)
for i = #tbl, 2, -1 do
local j = storage.tycoon_global_generator(i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
return tbl
end
--- @param city City
--- @param roadEnd RoadEnd
--- @return Direction[] | nil
local function pickRoadExpansion(city, roadEnd)
local left = getLeftDirection(roadEnd.direction)
local right = getRightDirection(roadEnd.direction)
local options = getRoadConnectionCountOptions()
shuffle(options)
for _, option in ipairs(options) do
local picked
if option == "3" then
picked = {roadEnd.direction, left, right}
-- If the test doesn't succeed, then continue trying the other options
elseif option == "2" then
local sides = {roadEnd.direction, left, right}
picked = {
table.remove(sides, city.generator(#sides)),
table.remove(sides, city.generator(#sides)),
}
-- If the test doesn't succeed, then continue trying the other options
elseif option == "1" then
-- Start with the default maximum length. The for loop will not update it if the street is longer than 10.
local straightStreetLength = 10
for i = 1, straightStreetLength, 1 do
local previousCell = continueInDirection(roadEnd.coordinates, invertDirection(roadEnd.direction), i)
local cell = GridUtil.safeGridAccess(city, previousCell)
if cell == nil then
-- We reached the end of the grid. The road doesn't go beyond here.
break
end
if cell.type ~= "road" then
-- We reached the end of the straight street. Record the total distance.
straightStreetLength = i
break
end
end
local shouldBuildStraight = city.generator() > (straightStreetLength / 10)
if shouldBuildStraight then
picked = {roadEnd.direction}
else
local sides = {left, right}
picked = {sides[city.generator(#sides)]}
end
elseif option == "0" then
picked = {}
else
assert(false, "pickRoadExpansion doesn't yet handle the new roadConnection: " .. option)
end
if testRoadDirection(city, roadEnd, picked) then
return picked
end
end
return nil
end
--- @param direction Direction
--- @return string[] map
local function getMap(direction)
local result = nil
if direction == "north" then
result = {
"001100",
"001100",
"001100",
"001100",
"000000",
"000000",
}
elseif direction == "south" then
result = {
"000000",
"000000",
"001100",
"001100",
"001100",
"001100",
}
elseif direction == "west" then
result = {
"000000",
"000000",
"111100",
"111100",
"000000",
"000000",
}
elseif direction == "east" then
result = {
"000000",
"000000",
"001111",
"001111",
"000000",
"000000",
}
end
assert(result ~= nil, "Invalid direction for getMap")
return result
end
-- TODO: build this table from prototypes or data-constants
local totalBuildingSprites = {
["garden"] = 13,
["excavation-pit"] = 20,
["house-simple"] = 14,
["house-residential"] = 9,
["house-highrise"] = 8,
}
--- @param city City
--- @param buildingType BuildingType
local function getRandomBuildingName(city, buildingType)
assert(city ~= nil, "City instance is nil")
assert(totalBuildingSprites[buildingType] ~= nil, "Unknown building type: " .. tostring(buildingType))
local n = totalBuildingSprites[buildingType] or 1
return "tycoon-" .. buildingType .."-".. city.generator(n)
end
--- @param city City
--- @param recentCoordinates Coordinates | nil
--- @param allowCenter boolean | nil
local function addBuildingLocations(city, recentCoordinates, allowCenter)
if city.buildingLocationQueue == nil then
city.buildingLocationQueue = Queue.new()
end
if city.gardenLocationQueue == nil then
city.gardenLocationQueue = Queue.new()
end
if recentCoordinates ~= nil then
local surrounds = getSurroundingCoordinates(recentCoordinates, 1, false, allowCenter)
for _, value in ipairs(surrounds) do
-- TODO: this will probably skip corners when called from on_entity_destroyed event
-- are edges supposed to be roads or what?
if value.x <= 1 or value.y <= 1 or value.x >= #city.grid or value.y >= #city.grid then
-- Skip locations that are at the edge of the grid or beyond
else
-- Only check cells that are unused and may have a building built there
local cell = GridUtil.safeGridAccess(city, value)
local isUnused = cell ~= nil and cell.type == "unused"
if isUnused then
-- Then check if there are any open roadEnds surrounding this unused field
local surroundsOfUnused = getSurroundingCoordinates(value, 1, false)
local hasSurroundingRoadEnd = false
for _, s in ipairs(surroundsOfUnused) do
if Util.indexOf(recentCoordinates, s) ~= nil then
hasSurroundingRoadEnd = true
break
end
end
if not hasSurroundingRoadEnd then
if hasSurroundingRoad(city, value) then
local offsetY = GridUtil.getOffsetY(city)
local offsetX = GridUtil.getOffsetX(city)
local cityCenter = {
x = city.center.x + Constants.CELL_SIZE,
y = city.center.y + Constants.CELL_SIZE,
}
local distanceA = getCachedDistance(value, offsetY, offsetX, cityCenter)
Queue.insert(city.buildingLocationQueue, value, math.ceil(distanceA))
else
-- Test if this cell is surrounded by houses, if yes then place a garden
-- Because we use getSurroundingCoordinates with allowDiagonal=false above, we only need to count 4 houses or roads
local surroundCount = 0
for _, s in ipairs(surroundsOfUnused) do
local surroundingCell = GridUtil.safeGridAccess(city, s)
if surroundingCell ~= nil and surroundingCell.type == "building" then
surroundCount = surroundCount + 1
end
end
-- Sometimes there are also 2 unused cells within a housing group. We probably need a better check, but for now we'll just build gardens when there are 3 houses.
if surroundCount >= 3 then
Queue.pushright(city.gardenLocationQueue, value)
end
-- noop, wait until there's a house and let it reattempt later
end
else
-- if there's a surrounding roadEnd, then we'll wait so that the houses don't block road expansion
end
end
end
end
end
end
--- @param cellCoordinates Coordinates
local function isCellFree(city, cellCoordinates)
local startCoordinates = GridUtil.translateCityGridToTileCoordinates(city, cellCoordinates)
local area = {
{x = startCoordinates.x, y = startCoordinates.y},
{x = startCoordinates.x + Constants.CELL_SIZE, y = startCoordinates.y + Constants.CELL_SIZE}
}
return isAreaFree(area, city.surface_index)
end
--- @param city City
--- @param coordinates Coordinates
--- @return boolean
local function isConnectedToRoad(city, coordinates)
local surrounds = getSurroundingCoordinates(coordinates, 1, false)
for _, s in ipairs(surrounds) do
local c = GridUtil.safeGridAccess(city, s)
if c ~= nil and c.type == "road" then
return true
end
end
return false
end
--- @param city City
--- @param buildingConstruction BuildingConstruction
--- @param queueIndex string
--- @param allowedCoordinates Coordinates[] | nil
--- @return boolean started
local function startConstruction(city, buildingConstruction, queueIndex, allowedCoordinates)
if city[queueIndex] == nil then
city[queueIndex] = Queue.new()
end
city[queueIndex] = Queue.removeDuplicates(city[queueIndex], function(v)
return v.x .. "-" .. v.y
end)
local function log_failure(reason)
log("startConstruction(): unable to construct: ".. tostring(buildingConstruction.buildingType) ..", reason: ".. reason)
end
-- Make up to 10 attempts to find a location where we can start a construction site
local attempts = 10
local log_reason = "attempts"
if allowedCoordinates ~= nil then
attempts = #allowedCoordinates
end
for i = 1, attempts, 1 do
local coordinates
if allowedCoordinates ~= nil then
coordinates = table.remove(allowedCoordinates)
else
coordinates = Queue.popleft(city[queueIndex])
if coordinates == nil then
-- If there are no more entries left in the queue, then abort
log_failure(log_reason)
Queue.pushright(city[queueIndex], coordinates)
return false
end
end
local startCoordinates = GridUtil.translateCityGridToTileCoordinates(city, coordinates)
local area = {
{x = startCoordinates.x, y = startCoordinates.y},
{x = startCoordinates.x + Constants.CELL_SIZE, y = startCoordinates.y + Constants.CELL_SIZE}
}
local cell = GridUtil.safeGridAccess(city, coordinates)
if coordinates.x <= 1 or coordinates.y <= 1 or coordinates.y >= #city.grid or coordinates.x > #city.grid then
-- If it's at the edge of the grid, then put it back
Queue.pushright(city[queueIndex], coordinates)
elseif cell == nil then
-- noop, if the grid has not been expanded this far, then don't try to build a building here
-- this should insert the coordinates at the end of the list, so that
-- the next iteration will pick a different element from the beginning of the list
Queue.pushright(city[queueIndex], coordinates)
elseif cell.type ~= "unused" then
-- If this location already has a road or building, then don't attempt to build
-- here again.
-- noop
elseif not isAreaFree(area, city.surface_index) then
-- noop, if there are collidables than retry later
-- this should insert the coordinates at the end of the list, so that
-- the next iteration will pick a different element from the beginning of the list
Queue.pushright(city[queueIndex], coordinates)
elseif buildingConstruction.buildingType == "simple" and not isConnectedToRoad(city, coordinates) then
-- Don't build buildings if there is no road connection yet
Queue.pushright(city[queueIndex], coordinates)
elseif buildingConstruction.buildingType == "garden" and isConnectedToRoad(city, coordinates) then
-- Don't build gardens if there's a road right next to it
else
local construction_materials = Constants.CONSTRUCTION_MATERIALS[buildingConstruction.buildingType]
local hardwareStores = Util.list_special_city_buildings(city, "tycoon-hardware-store")
local cost = Consumption.consumeRequired(construction_materials, hardwareStores, city)
if cost == nil then
log_reason = "materials"
log_failure(log_reason)
Queue.pushright(city[queueIndex], coordinates)
return false
end
-- We can start a construction site here
removeCollidingEntities(area, city.surface_index)
-- Place an excavation site entity that will be later replaced with the actual building
local excavationPit = game.surfaces[city.surface_index].create_entity{
name = getRandomBuildingName(city, "excavation-pit"),
position = {x = startCoordinates.x - 0.5 + Constants.CELL_SIZE / 2, y = startCoordinates.y - 0.5 + Constants.CELL_SIZE / 2},
force = "player",
move_stuck_players = true
}
excavationPit.destructible = false
city.grid[coordinates.y][coordinates.x] = {
type = "building",
entity = excavationPit,
createdAtTick = game.tick
}
if city.excavationPits == nil then
city.excavationPits = {}
end
table.insert(city.excavationPits, {
coordinates = coordinates,
createdAtTick = game.tick,
buildingConstruction = buildingConstruction,
})
return true
end
end
log_failure(log_reason)
return false
end
--- @param coordinates Coordinates
local function isCharted(city, coordinates)
local chunkPosition = {
y = math.floor((GridUtil.getOffsetY(city) + coordinates.y * Constants.CELL_SIZE) / Constants.CHUNK_SIZE),
x = math.floor((GridUtil.getOffsetX(city) + coordinates.x * Constants.CELL_SIZE) / Constants.CHUNK_SIZE),
}
return game.forces.player.is_chunk_charted(game.surfaces[city.surface_index], chunkPosition)
end
--- @param coordinates Coordinates
local function increaseCoordinates(coordinates, city)
-- Debugged a case where the new value would be above the current grid size --> coordinates.x > #city.grid
coordinates.x = coordinates.x + 1
coordinates.y = coordinates.y + 1
end
local function clearAreaAndPrintTiles(city, coordinates, map, tileType)
local currentCellStartCoordinates = GridUtil.translateCityGridToTileCoordinates(city, {
x = coordinates.x,
y = coordinates.y,
})
Util.printTiles(currentCellStartCoordinates, map, tileType, city.surface_index, {Constants.GROUND_TILE_TYPES.residential, Constants.GROUND_TILE_TYPES.highrise})
local currentArea = {
{currentCellStartCoordinates.x, currentCellStartCoordinates.y},
{currentCellStartCoordinates.x + Constants.CELL_SIZE, currentCellStartCoordinates.y + Constants.CELL_SIZE}
}
removeCollidingEntities(currentArea, city.surface_index, streetIgnorables)
end
--- @param city City
--- @return Coordinates | nil coordinates
local function growAtRandomRoadEnd(city)
if city.roadEnds == nil then
city.roadEnds = Queue.new()
return
end
local roadEnd = Queue.popleft(city.roadEnds)
if roadEnd == nil then
return
end
if roadEnd.coordinates.x <= 1
or roadEnd.coordinates.x >= GridUtil.getGridSize(city.grid)
or roadEnd.coordinates.y <= 1
or roadEnd.coordinates.y >= GridUtil.getGridSize(city.grid)
then
-- We need to put the item back first, so that the expansion is applied to it properly
Queue.pushleft(city.roadEnds, roadEnd)
-- When expanding the grid I noticed that there sometimes were duplicates, which may have multiplied the coordinate shift (e.g. 3 duplicates meant that x/y for each would be shifted by 3 cells)
-- No idea why there are duplicates or why the multiplication happens, but removing duplicates helped as well
Queue.removeDuplicates(city.roadEnds, function(v)
return v.coordinates.x .. "-" .. v.coordinates.y .. "-" .. v.direction
end)
expand_grid(city)
-- Since we extended the grid (and inserted a top/left row/colum) all roadEnd coordinates need to shift one
if city.roadEnds ~= nil then
for value in Queue.iterate(city.roadEnds) do
increaseCoordinates(value.coordinates, city)
end
end
if city.gardenLocationQueue ~= nil then
for value in Queue.iterate(city.gardenLocationQueue) do
increaseCoordinates(value, city)
end
end
if city.buildingLocationQueue ~= nil then
for value in Queue.iterate(city.buildingLocationQueue) do
increaseCoordinates(value, city)
end
end
if city.excavationPits ~= nil then
for _, r in ipairs(city.excavationPits) do
increaseCoordinates(r.coordinates, city)
end
end
if city.houseLocations ~= nil then
for _, r in ipairs(city.houseLocations) do
increaseCoordinates(r, city)
end
end
return
end
if not isCharted(city, roadEnd.coordinates) then
return
end
local pickedExpansionDirections = pickRoadExpansion(city, roadEnd)
if pickedExpansionDirections ~= nil then
-- For each direction, fill the current cell with the direction and the neighbour with the inverse direction
for _, direction in ipairs(pickedExpansionDirections) do
clearAreaAndPrintTiles(city, roadEnd.coordinates, getMap(direction), Constants.GROUND_TILE_TYPES.road)
local currentCell = GridUtil.safeGridAccess(city, roadEnd.coordinates, "processPickedExpansionDirectionCurrent")
if currentCell == nil then
return nil
end
if currentCell.roadSockets == nil then
currentCell.roadSockets = {}
end
if Util.indexOf(currentCell.roadSockets, direction) == nil then
table.insert(currentCell.roadSockets, direction)
end
local neighbourPosition
if direction == "south" then
neighbourPosition = {x = roadEnd.coordinates.x, y = roadEnd.coordinates.y + 1}
elseif direction == "east" then
neighbourPosition = {x = roadEnd.coordinates.x + 1, y = roadEnd.coordinates.y}
elseif direction == "north" then
neighbourPosition = {x = roadEnd.coordinates.x, y = roadEnd.coordinates.y - 1}
elseif direction == "west" then
neighbourPosition = {x = roadEnd.coordinates.x - 1, y = roadEnd.coordinates.y}
end
local neighbourSocket = invertDirection(direction)
clearAreaAndPrintTiles(city, neighbourPosition, getMap(neighbourSocket), Constants.GROUND_TILE_TYPES.road)
local neighbourCell = GridUtil.safeGridAccess(city, neighbourPosition, "processPickedExpansionDirectionNeighbour")
if neighbourCell == nil then
return nil
end
if neighbourCell.type == "road" then
if Util.indexOf(neighbourCell.roadSockets, neighbourSocket) == nil then
table.insert(neighbourCell.roadSockets, neighbourSocket)
end
elseif neighbourCell.type == "unused" then
city.grid[neighbourPosition.y][neighbourPosition.x] = {
type = "road",
roadSockets = {neighbourSocket}
}
-- When creating a new road cell, then we also mark that as a roadEnd to later continue from
Queue.pushright(city.roadEnds, {
coordinates = neighbourPosition,
-- We need to use the original direction, so that the next expansion continues in the same direction
direction = direction,
})
else
assert(false, "Road should not be expanding into a cell that's not a road or unused.")
end
end
city.surrounding_points_cache = nil
else
-- todo: in what cases can't we build here? entity collision? player collision?
-- buildings should come later to fill empty gaps that have no collisions
-- Add some weight onto this roadEnd, so that it gets processed later (compared to others who are at a similar distance or don't have their weight changed as much)
-- roadEnd.additionalWeight = (roadEnd.additionalWeight or 1) * 1.2
Queue.pushright(city.roadEnds, roadEnd)
end
return roadEnd.coordinates
end