-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcivSimTribes_resources.go
616 lines (543 loc) · 18.3 KB
/
civSimTribes_resources.go
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
package genworldvoronoi
import (
"log"
"github.com/Flokey82/genbiome"
"github.com/Flokey82/genworldvoronoi/geo"
)
func (s *simState) handleResources(t *Tribe) {
// Here is what we could do:
// - Feed our people.
// - Produce weapons for hunting.
// - Produce tools for crafting.
// TODO:
// - Calculate suitability for hunting, gathering, herding, farming, etc.
biome := HackyBiome(s.biomeFunc(t.RegionID))
precipitation := s.m.Geo.Rainfall
_, maxElev := minMax(s.m.Elevation)
getGatheringScore := func(r int) float64 {
regSteepness := s.steepness[r]
regPrecipitation := precipitation[r] * geo.MaxPrecipitation * 100
regTemperature := s.m.GetRegTemperature(r, maxElev)
// Gathering is scored from 0 to 1.0.
// Less steepness is better for gathering.
// - at 1.0 steepness, the gathering score will be the minimum.
// - at 0.0 steepness, the gathering score will be (up to) the maximum.
gatheringSteepnessVal := 1.0 - regSteepness
// Gathering gets worse with lower precipitation.
// - at 0mm precipitation, the gathering score will be the minimum.
// - at 1000mm (and above), the gathering score will be (possibly) the maximum.
gatheringPrecipitationVal := min(regPrecipitation, 1000) / 1000
// Gathering gets worse with lower temperature.
// - at 0°C, the gathering score will be the minimum.
// - at 30°C, the gathering score will be (possibly) the maximum.
// - above 30°C, the gathering score will reduce again.
gatheringTemperatureVal := max(regTemperature, 0) / 30
if regTemperature > 30 {
gatheringTemperatureVal = 1.0 - min((regTemperature-30)/30, 1.0)
}
// The base value is 0.2.
regGathering := 0.2 + 0.8*gatheringSteepnessVal*gatheringPrecipitationVal*gatheringTemperatureVal
// There is a disadvantage in snow, desert, cold desert.
if biome == genbiome.WhittakerModBiomeSnow || biome == genbiome.WhittakerModBiomeSubtropicalDesert || biome == genbiome.WhittakerModBiomeColdDesert {
regGathering *= 0.5
}
return regGathering
}
getHuntingScore := func(r int) float64 {
regSteepness := s.steepness[r]
regPrecipitation := precipitation[r] * geo.MaxPrecipitation * 100
regTemperature := s.m.GetRegTemperature(r, maxElev)
// Hunting is scored from 0 to 1.0.
// Less steepness is better for hunting, but the minimum is higher than for gathering.
// - at 1.0 steepness, the hunting score will be the minimum.
// - at 0.0 steepness, the hunting score will be (up to) the maximum.
huntingSteepnessVal := 1.0 - regSteepness
// Hunting gets a little worse with lower precipitation.
// - at 0mm precipitation, the hunting score will be a little lower (40%).
// - at 1000mm, the hunting score will be (possibly) the maximum.
// - above 1000mm, the hunting score will reduce again.
huntingPrecepVal := 1.0
if regPrecipitation <= 1000 {
huntingPrecepVal = (regPrecipitation / 1000)
} else {
huntingPrecepVal = 1.0 - min(((regPrecipitation-1000)/1000), 1.0)
}
// Hunting gets a little worse with lower temperature.
// - at 0°C, the hunting score will be a little lower (40%).
// - at 30°C, the hunting score will be (possibly) the maximum.
// - above 30°C, the hunting score will reduce again.
huntingTempVal := 1.0
if regTemperature <= 30 {
huntingTempVal = (max(regTemperature, 0) / 30)
} else {
huntingTempVal = 1.0 - min(((regTemperature-30)/30), 1.0)
}
// The base value is 0.4.
regHunting := 0.4 + 0.6*huntingSteepnessVal*huntingPrecepVal*huntingTempVal
// There is a disadvantage in (dense) forests.
if biome == genbiome.WhittakerModBiomeTemperateRainforest || biome == genbiome.WhittakerModBiomeTropicalRainforest {
regHunting *= 0.5
}
return regHunting
}
regHunting := getHuntingScore(t.RegionID)
possibleFoodHuntingPerPersonMax := 5.0
possibleFoodHuntingPerPersonMin := 1.0
regGathering := getGatheringScore(t.RegionID)
possibleFoodGatheringPerPersonMax := 3.0
possibleFoodGatheringPerPersonMin := 1.0
// Calculate the food production for hunting and gathering.
foodHuntingPerPerson := possibleFoodHuntingPerPersonMin + (possibleFoodHuntingPerPersonMax-possibleFoodHuntingPerPersonMin)*regHunting
foodGatheringPerPerson := possibleFoodGatheringPerPersonMin + (possibleFoodGatheringPerPersonMax-possibleFoodGatheringPerPersonMin)*regGathering
log.Printf("!!!%s is hunting: %.2f, gathering: %.2f.", t.String(), regHunting, regGathering)
// Calculate how much food the tribe can produce.
// Half of the population is available for hunting.
// The rest might be too young, too old.
//availablePopulationHunter := float64(t.Population) * 0.5
// 90% of the population is available for gathering since
// gathering is less dangerous or physically demanding.
availablePopulationGatherer := float64(t.Population) * 0.9
// The ratio of the scores will determine how many are spent on hunting and how many on gathering.
// The rest will be spent on farming.
// huntingToGatheringRatio := regHunting / regGathering
// TODO: Also weigh the composition by the preference of the tribe.
popHunting := float64(t.Population) / (foodHuntingPerPerson + availablePopulationGatherer - foodGatheringPerPerson)
popGathering := availablePopulationGatherer - popHunting
foodHunting := popHunting * foodHuntingPerPerson
foodGathering := popGathering * foodGatheringPerPerson
// Calculate the food production for gathering.
log.Printf("!!!%s is producing food: %d total; %d from hunting (%d people), %d from gathering (%d people).", t.String(), int(foodHunting+foodGathering), int(foodHunting), int(popHunting), int(foodGathering), int(popGathering))
// Produce food, mainly to feed our population, but also keep some in storage.
// m.Suitability[t.RegionID]
// Check if we have enough resources to build what we want to build.
// How do we know what we need?
// - Ongoing consumption of goods and resources?
// - What do we need to produce?
// - What do we need to trade?
// TODO: We also need a resource sink. What do we spend resources on?
// - Food
// - Tools
// - Weapons
// - Buildings
// - Trade
// - Diplomacy
// Produce goods?
// - Tools
// - Weapons
// - Buildings
const requiredFodPerPerson = 1.0
const requiredFirewoodPerPerson = 0.5 // This should depend on the climate
foodRequired := float64(t.Population) * requiredFodPerPerson
firewoodRequired := float64(t.Population) * requiredFirewoodPerPerson
if foodHunting+foodGathering < foodRequired {
log.Printf("!!!%s is starving. Food production: %d, required: %.2f.", t.String(), int(foodHunting+foodGathering), foodRequired)
}
if foodHunting+foodGathering < firewoodRequired {
log.Printf("!!!%s is freezing. Firewood production: %d, required: %.2f.", t.String(), int(foodHunting+foodGathering), firewoodRequired)
}
// Nomadic tribes will just hunt and gather.
// They can produce some simple tools and simple weapons that will increase their efficiency
// but they cannot build buildings or produce goods that require a settlement.
// Settled tribes will produce food, tools, weapons, and buildings.
// Buildings:
// - Require goods and resources to be constructed.
// - Provide certain benefits to the tribe.
// - They might consume resources or goods each turn and potentially provide resources or goods.
// - They might need maintenance.
// Goods:
// - Are produced from resources or other goods.
// - They might be consumed by the tribe, or traded.
// TODO:
// - Calculate how much food and firewood we need.
// - Calculate need for buildings (housing, etc.)
// - Calculate need for maintenance resources (wood, stone, metal, etc.)
// Determine what we have and what we need.
// - Calculate the resources we have.
// - Calculate the resources we need.
// Generate resources based on the local resources.
// If we aren't settled, we only can gather resources from the region we are in.
if t.Type == TribeTypeNomadic {
res := s.m.getResources(t.RegionID, false)
t.ResourceStorage.Add(res)
t.dumbStorage.resources[StorageWood] = sumResource(t.ResourceStorage.Wood[:])
} else {
// TODO: Introduce storage for settlements, city states, and empires.
res := s.m.getResources(t.RegionID, true)
t.ResourceStorage.Add(res)
t.dumbStorage.resources[StorageWood] = sumResource(t.ResourceStorage.Wood[:])
}
// build stuff
t.dumbStorage.resources[StorageFood] += int(foodHunting + foodGathering)
t.dumbStorage.resources[StorageLeather] += int(foodHunting)
t.dumbStorage.resources[StorageWood] += int(foodGathering)
s.buildThings(t)
}
const (
ResCategoryWood = iota
ResCategoryStone
ResCategoryMetal
ResCategoryGem
ResCategoryVarious
)
const ResourceTypeAny = -1
func (s *simState) handleTrade(t *Tribe) {
// TODO: Figure out what we actually need and what we have in excess.
const tradeRadius = 900.0 // km
tradeCities := s.getNearbyCities(t.RegionID, tradeRadius)
// NOTE: This is only about resources.
type cityTradeProposal struct {
city *City
dist float64 // distance to the city
exp LocalResouces // resources that we can export
imp LocalResouces // resources that we can import
}
// compareResources compares the resources of two regions and returns
// potential exports and imports.
compareResources := func(src, dst int) (exp, imp LocalResouces) {
// Determine what resources we have and what resources we need.
aRes := s.m.getResources(src, true)
bRes := s.m.getResources(dst, true)
imp = bRes.Remove(aRes)
exp = aRes.Remove(bRes)
return
}
var tradeProposals []*cityTradeProposal
// Loop through all the trade cities and propose trades.
// If we have resources that the other city needs, we propose a trade for export.
// If the other city has resources that we need, we propose a trade for import.
for _, tc := range tradeCities {
// Determine what resources we have and what resources we need.
exp, imp := compareResources(t.RegionID, tc.city.ID)
tradeProposals = append(tradeProposals, &cityTradeProposal{
city: tc.city,
exp: exp,
imp: imp,
dist: tc.dist,
})
}
// Log the trade proposals.
for _, tp := range tradeProposals {
log.Printf("!!!%s has proposed a trade with %s, dist %.2f", t.String(), tp.city.String(), tp.dist)
if tp.exp.HasAny() {
log.Printf(" Export: %s", tp.exp.String())
}
if tp.imp.HasAny() {
log.Printf(" Import: %s", tp.imp.String())
}
score := t.Settlement.compare(tp.city)
log.Printf(" Score: %.2f", score)
}
}
func sumResource(res []int) int {
var sum int
for _, r := range res {
sum += r
}
return sum
}
type ResourceStorage struct {
maxStorage int
Wood [geo.ResMaxWoods]int
Stone [geo.ResMaxStones]int
Metal [geo.ResMaxMetals]int
Gem [geo.ResMaxGems]int
Various [geo.ResMaxVarious]int
}
func newResourceStorage(maxStorage int) *ResourceStorage {
return &ResourceStorage{
maxStorage: maxStorage,
}
}
func hasAmount(resource []int, rType, amount int) bool {
if rType == ResourceTypeAny {
// Sum up the available resources.
var available int
for _, a := range resource {
available += a
}
return available >= amount
}
return resource[rType] >= amount
}
func (rs *ResourceStorage) Has(category, rType, amount int) bool {
switch category {
case ResCategoryWood:
return hasAmount(rs.Wood[:], rType, amount)
case ResCategoryStone:
return hasAmount(rs.Stone[:], rType, amount)
case ResCategoryMetal:
return hasAmount(rs.Metal[:], rType, amount)
case ResCategoryGem:
return hasAmount(rs.Gem[:], rType, amount)
case ResCategoryVarious:
return hasAmount(rs.Various[:], rType, amount)
}
return false
}
func (rs *ResourceStorage) HasHowMuchMissing(category, rType, amount int) int {
howManyMissing := func(resource []int, amount int) int {
missing := amount
for _, r := range resource {
if r > 0 {
missing -= r
}
if missing <= 0 {
return 0
}
}
return missing
}
var resource []int
switch category {
case ResCategoryWood:
resource = rs.Wood[:]
case ResCategoryStone:
resource = rs.Stone[:]
case ResCategoryMetal:
resource = rs.Metal[:]
case ResCategoryGem:
resource = rs.Gem[:]
case ResCategoryVarious:
resource = rs.Various[:]
default:
return amount
}
if rType == ResourceTypeAny {
return howManyMissing(resource, amount)
}
return amount - resource[rType]
}
func takeAmount(resource []int, rType, amount int) {
if rType == ResourceTypeAny {
// Take the resources from the first available resource.
remaining := amount
for i := range resource {
if resource[i] > 0 {
toTake := min(remaining, resource[i])
resource[i] -= toTake
remaining -= toTake
if remaining == 0 {
break
}
}
}
} else {
resource[rType] -= amount
}
// TODO: add a check if we have enough resources.
}
func (rs *ResourceStorage) Take(category, rType, amount int) {
switch category {
case ResCategoryWood:
takeAmount(rs.Wood[:], rType, amount)
case ResCategoryStone:
takeAmount(rs.Stone[:], rType, amount)
case ResCategoryMetal:
takeAmount(rs.Metal[:], rType, amount)
case ResCategoryGem:
takeAmount(rs.Gem[:], rType, amount)
case ResCategoryVarious:
takeAmount(rs.Various[:], rType, amount)
}
}
func (rs *ResourceStorage) AddResource(category, rType, amount int) {
switch category {
case ResCategoryWood:
rs.Wood[rType] += amount
case ResCategoryStone:
rs.Stone[rType] += amount
case ResCategoryMetal:
rs.Metal[rType] += amount
case ResCategoryGem:
rs.Gem[rType] += amount
case ResCategoryVarious:
rs.Various[rType] += amount
}
}
func (rs *ResourceStorage) Add(r LocalResouces) {
for _, w := range r.GetWood() {
rs.Wood[w]++
if rs.Wood[w] > rs.maxStorage {
rs.Wood[w] = rs.maxStorage
}
}
for _, s := range r.GetStones() {
rs.Stone[s]++
if rs.Stone[s] > rs.maxStorage {
rs.Stone[s] = rs.maxStorage
}
}
for _, m := range r.GetMetals() {
rs.Metal[m]++
if rs.Metal[m] > rs.maxStorage {
rs.Metal[m] = rs.maxStorage
}
}
for _, g := range r.GetGems() {
rs.Gem[g]++
if rs.Gem[g] > rs.maxStorage {
rs.Gem[g] = rs.maxStorage
}
}
for _, v := range r.GetVarious() {
rs.Various[v]++
if rs.Various[v] > rs.maxStorage {
rs.Various[v] = rs.maxStorage
}
}
}
func (rs *ResourceStorage) Log() {
log.Printf(" Resources:")
log.Printf(" Wood:")
for i, w := range rs.Wood {
if w > 0 {
log.Printf(" %s: %d", geo.WoodToString(i), w)
}
}
log.Printf(" Stone:")
for i, s := range rs.Stone {
if s > 0 {
log.Printf(" %s: %d", geo.StoneToString(i), s)
}
}
log.Printf(" Metal:")
for i, m := range rs.Metal {
if m > 0 {
log.Printf(" %s: %d", geo.MetalToString(i), m)
}
}
log.Printf(" Gem:")
for i, g := range rs.Gem {
if g > 0 {
log.Printf(" %s: %d", geo.GemToString(i), g)
}
}
log.Printf(" Various:")
for i, v := range rs.Various {
if v > 0 {
log.Printf(" %s: %d", geo.VariousToString(i), v)
}
}
}
// LocalResouces represents the resources available in a region.
type LocalResouces struct {
Wood byte // Available wood types.
Stones byte // Available stone types.
Metals byte // Available metal types.
Gems byte // Available gem types.
Various byte // Various resources.
}
// HasAny returns true if there are any resources available.
func (r LocalResouces) HasAny() bool {
return r.Wood != 0 || r.Stones != 0 || r.Metals != 0 || r.Gems != 0 || r.Various != 0
}
func getResources(res byte, max int) []int {
var resSlice []int
for i := 0; i < max; i++ {
if res&(1<<uint(i)) != 0 {
resSlice = append(resSlice, i)
}
}
return resSlice
}
func (r LocalResouces) GetGems() []int {
return getResources(r.Gems, geo.ResMaxGems)
}
func (r LocalResouces) GetMetals() []int {
return getResources(r.Metals, geo.ResMaxMetals)
}
func (r LocalResouces) GetStones() []int {
return getResources(r.Stones, geo.ResMaxStones)
}
func (r LocalResouces) GetWood() []int {
return getResources(r.Wood, geo.ResMaxWoods)
}
func (r LocalResouces) GetVarious() []int {
return getResources(r.Various, geo.ResMaxVarious)
}
func (r LocalResouces) String() string {
var s string
resToString := func(label string, res byte, max int, strFunc func(int) string) string {
if res == 0 {
return ""
}
var resStr string
resStr += label + ": "
for i := 0; i < max; i++ {
if res&(1<<uint(i)) != 0 {
resStr += strFunc(i) + " "
}
}
return resStr
}
s += resToString("Wood", r.Wood, geo.ResMaxWoods, geo.WoodToString)
s += resToString("Stone", r.Stones, geo.ResMaxStones, geo.StoneToString)
s += resToString("Metal", r.Metals, geo.ResMaxMetals, geo.MetalToString)
s += resToString("Gem", r.Gems, geo.ResMaxGems, geo.GemToString)
s += resToString("Various", r.Various, geo.ResMaxVarious, geo.VariousToString)
return s
}
func (r LocalResouces) Add(other LocalResouces) LocalResouces {
r.Wood |= other.Wood
r.Stones |= other.Stones
r.Metals |= other.Metals
r.Gems |= other.Gems
r.Various |= other.Various
return r
}
func (r LocalResouces) Remove(other LocalResouces) LocalResouces {
r.Wood &^= other.Wood
r.Stones &^= other.Stones
r.Metals &^= other.Metals
r.Gems &^= other.Gems
r.Various &^= other.Various
return r
}
func (r LocalResouces) Log() {
logEntry := func(name string, res byte, max int, strFunc func(int) string) {
for i := 0; i < max; i++ {
if res&(1<<uint(i)) != 0 {
log.Printf(" %s: %s", name, strFunc(i))
}
}
}
logEntry("Wood", r.Wood, geo.ResMaxWoods, geo.WoodToString)
logEntry("Stone", r.Stones, geo.ResMaxStones, geo.StoneToString)
logEntry("Metal", r.Metals, geo.ResMaxMetals, geo.MetalToString)
logEntry("Gem", r.Gems, geo.ResMaxGems, geo.GemToString)
logEntry("Various", r.Various, geo.ResMaxVarious, geo.VariousToString)
}
func (m *Civ) getResources(r int, incNeighbors bool) LocalResouces {
var rsc LocalResouces
rsc.Wood = m.Geo.Resources.Wood[r]
rsc.Stones = m.Geo.Resources.Stones[r]
rsc.Metals = m.Geo.Resources.Metals[r]
rsc.Gems = m.Geo.Resources.Gems[r]
rsc.Various = m.Geo.Resources.Various[r]
if incNeighbors {
for _, nb := range m.R_circulate_r(rNbs, r) {
rsc.Wood |= m.Geo.Resources.Wood[nb]
rsc.Stones |= m.Geo.Resources.Stones[nb]
rsc.Metals |= m.Geo.Resources.Metals[nb]
rsc.Gems |= m.Geo.Resources.Gems[nb]
rsc.Various |= m.Geo.Resources.Various[nb]
}
}
return rsc
}
type ResourcePresence struct {
Wood bool
Stones bool
Metals bool
Gems bool
various bool
}
func (m *Civ) getResourcePresence(r int) *ResourcePresence {
return &ResourcePresence{
Wood: m.Geo.Resources.Wood[r] > 0,
Stones: m.Geo.Resources.Stones[r] > 0,
Metals: m.Geo.Resources.Metals[r] > 0,
Gems: m.Geo.Resources.Gems[r] > 0,
various: m.Geo.Resources.Various[r] > 0,
}
}