Repository navigation
Expand file tree
/
Copy pathcorescript.cpp
More file actions
executable file
·1307 lines (1089 loc) · 34 KB
/
Copy pathcorescript.cpp
File metadata and controls
executable file
·1307 lines (1089 loc) · 34 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
#include "corescript.h"
#include "../engine/engine.h"
#include "../game/census.h"
#include "../game/lumoschitbag.h"
#include "../game/mapspatialcomponent.h"
#include "../game/worldmap.h"
#include "../game/aicomponent.h"
#include "../game/workqueue.h"
#include "../game/gameitem.h"
#include "../game/sim.h"
#include "../game/worldinfo.h"
#include "../game/reservebank.h"
#include "../game/healthcomponent.h"
#include "../game/physicssims.h"
#include "../game/fluidsim.h"
#include "../xegame/rendercomponent.h"
#include "../xegame/itemcomponent.h"
#include "../script/procedural.h"
#include "../script/itemscript.h"
#include "../script/guardscript.h"
#include "../script/flagscript.h"
/*
See also SectorHerd() for where this gets implemented.
Temples attract / repel monsters
MAX_TECH Less Greater
1: repel some repel
2: repel
3: attract near
4: attract near attract
*/
static const double TECH_ADDED_BY_VISITOR = 0.2;
static const double TECH_DECAY_0 = 0.0001;
static const double TECH_DECAY_1 = 0.0016;
using namespace grinliz;
CoreScript* CoreScript::coreArr[NUM_SECTORS*NUM_SECTORS];
HashTable<int, int>* CoreScript::teamToCoreInfo = 0;
grinliz::CArray<CoreScript*, NUM_SECTORS*NUM_SECTORS> CoreScript::coreList;
void CoreScript::Init()
{
teamToCoreInfo = new HashTable<int, int>();
}
void CoreScript::Free()
{
delete teamToCoreInfo;
teamToCoreInfo = 0;
}
const char* CoreAchievement::CivTechDescription(int score)
{
const char* result = "none";
if (score > 3200) result = "The mighty empire";
else if (score > 1600) result = "The empire";
else if (score > 800) result = "The noted domain";
else if (score > 400) result = "The domain";
else if (score > 100) result = "The outpost";
else if (score > 50) result = "The prototype";
else result = "The proto test";
return result;
}
void CoreAchievement::Serialize(XStream* xs)
{
XarcOpen(xs, "CoreAchievement");
XARC_SER(xs, techLevel);
XARC_SER(xs, gold);
XARC_SER(xs, population);
XARC_SER(xs, civTechScore);
XarcClose(xs);
}
CoreScript::CoreScript() :
workQueue( 0 ),
aiTicker(2000),
scoreTicker(10*1000),
strategicTicker(10*1000),
spawnTick( 20*1000 ),
summonGreater(0),
autoRebuild(false)
{
tech = 0;
achievement.Clear();
workQueue = 0;
pave = 0;
sector.Zero();
}
CoreScript::~CoreScript()
{
delete workQueue;
}
void CoreScript::Flag::Serialize(XStream* xs)
{
XarcOpen(xs, "Flag");
XARC_SER(xs, pos);
XARC_SER(xs, chitID);
XarcClose(xs);
}
void CoreScript::Serialize(XStream* xs)
{
BeginSerialize(xs, Name());
XARC_SER(xs, tech);
XARC_SER(xs, summonGreater);
XARC_SER(xs, autoRebuild);
XARC_SER(xs, pave);
XARC_SER_VAL_CARRAY(xs, citizens);
GLASSERT(MAX_SQUADS == 4);
XARC_SER_VAL_CARRAY(xs, squads[0]);
XARC_SER_VAL_CARRAY(xs, squads[1]);
XARC_SER_VAL_CARRAY(xs, squads[2]);
XARC_SER_VAL_CARRAY(xs, squads[3]);
XARC_SER_VAL_CARRAY(xs, waypoints[0]);
XARC_SER_VAL_CARRAY(xs, waypoints[1]);
XARC_SER_VAL_CARRAY(xs, waypoints[2]);
XARC_SER_VAL_CARRAY(xs, waypoints[3]);
XARC_SER_CARRAY(xs, flags);
spawnTick.Serialize(xs, "spawn");
scoreTicker.Serialize(xs, "score");
achievement.Serialize(xs);
if (!workQueue) {
workQueue = new WorkQueue();
}
workQueue->Serialize(xs);
EndSerialize(xs);
}
void CoreScript::OnAdd(Chit* chit, bool init)
{
super::OnAdd(chit, init);
if (init) {
spawnTick.Randomize(parentChit->ID());
}
if ( !workQueue ) {
workQueue = new WorkQueue();
}
Vector2I mapPos = ToWorld2I(parentChit->Position());
sector = ToSector(mapPos);
workQueue->InitSector( parentChit, sector );
int index = sector.y*NUM_SECTORS + sector.x;
GLASSERT(index);
GLASSERT(coreArr[index] == 0);
coreArr[index] = this;
coreList.Push(this);
aiTicker.Randomize(parentChit->random.Rand());
strategicTicker.Randomize(parentChit->random.Rand());
}
void CoreScript::OnRemove()
{
int index = sector.y*NUM_SECTORS + sector.x;
GLASSERT(coreArr[index] == this);
coreArr[index] = 0;
int idx = coreList.Find(this);
GLASSERT(idx >= 0);
coreList.SwapRemove(idx);
delete workQueue;
workQueue = 0;
super::OnRemove();
}
void CoreScript::OnChitMsg(Chit* chit, const ChitMsg& msg)
{
// Logic split between Sim::OnChitMsg and CoreScript::OnChitMsg
if (msg.ID() == ChitMsg::CHIT_DESTROYED && (chit == parentChit)) {
while (!citizens.Empty()) {
int citizenID = citizens.Pop();
Chit* citizen = Context()->chitBag->GetChit(citizenID);
if (citizen && citizen->GetItem()) {
// Set to rogue team.
citizen->GetItem()->SetRogue();
}
}
Vector2I pos2i = ToWorld2I(chit->Position());
Vector2I sector = ToSector(pos2i);
if (Team::Instance()->IsController(chit->Team())) {
NewsEvent news(NewsEvent::SUPERTEAM_DELETED, ToWorld2F(pos2i), chit->GetItemID(), 0);
Context()->chitBag->GetNewsHistory()->Add(news);
}
int controllerTeam = 0;
if (Team::Instance()->IsControlled(chit->Team(), &controllerTeam)) {
CoreScript* controller = CoreScript::GetCoreFromTeam(controllerTeam);
GLASSERT(controller);
if (controller) {
NewsEvent news(NewsEvent::SUBTEAM_DELETED, ToWorld2F(pos2i), chit->GetItemID(), controller->ParentChit()->GetItemID());
Context()->chitBag->GetNewsHistory()->Add(news);
}
}
int deleterID = chit->GetItemComponent() ? chit->GetItemComponent()->LastDamageID() : 0;
Chit* deleter = Context()->chitBag->GetChit(deleterID);
int superTeam = 0;
if (deleter
&& (deleter->Team() == Team::Instance()->SuperTeam(deleter->Team()))
&& Team::IsDenizen(deleter->Team())
&& Team::IsDenizen(chit->Team()))
{
superTeam = deleter->Team();
}
if (chit->Team() != TEAM_NEUTRAL) {
CoreScript* superCore = CoreScript::GetCoreFromTeam(superTeam);
LumosChitBag::CreateCoreData data = {
sector,
superCore && superCore->WantsToConquer(sector),
chit->Team(),
deleter ? deleter->Team() : 0
};
Context()->chitBag->coreCreateList.Push(data);
}
else {
// Neutral cores are taken over by wandering over them
// with enough friend units to have critical mass.
LumosChitBag::CreateCoreData data = { sector, false, 0, 0 };
Context()->chitBag->coreCreateList.Push(data);
}
Team::Instance()->CoreDestroyed(parentChit->Team());
}
}
void CoreScript::AssignToSquads()
{
// First, how many do we actually have?
// Filter out everyone that has gone away.
for (int i = 0; i < MAX_SQUADS; ++i) {
//GL_ARRAY_FILTER(squads[i], (this->IsCitizen(ele)));
squads[i].Filter(this, [](CoreScript* cs, int id) {
return cs->IsCitizen(id);
});
if (squads[i].Empty()) {
// Flush out dead squads so they don't have
// control flags laying around.
waypoints[i].Clear();
}
}
int nSquaddies = 0;
for (int i = 0; i < MAX_SQUADS; ++i) {
nSquaddies += squads[i].Size();
}
CChitArray recruits;
int nCitizens = Citizens(&recruits);
int nExpected = nCitizens - CITIZEN_BASE;
if (nSquaddies >= nExpected) return;
struct FilterData {
CoreScript* cs;
Chit* avatar;;
};
FilterData fd = { this, Context()->chitBag->GetAvatar() };
// Filter to: not in squad AND not player controlled
recruits.Filter(fd, [](const FilterData& ffd, Chit* chit) {
return (ffd.cs->SquadID(chit->ID()) < 0 && chit != ffd.avatar);
});
// Sort the best recruits to the end.
// FIXME: better if there was a (working) power approximation
recruits.Sort([](Chit* a, Chit* b) {
const GameItem* itemA = a->GetItem();
const GameItem* itemB = b->GetItem();
int scoreA = itemA->Traits().Level() * (itemA->GetPersonality().Fighting() == Personality::LIKES ? 2 : 1);
int scoreB = itemB->Traits().Level() * (itemB->GetPersonality().Fighting() == Personality::LIKES ? 2 : 1);
// Reverse order. Best at end.
return scoreA > scoreB;
});
for (int n = nExpected - nSquaddies; n > 0; --n) {
for (int i = 0; i < MAX_SQUADS; ++i) {
if ( (squads[i].Size() < SQUAD_SIZE)
&& SquadAtRest(i))
{
Chit* chit = recruits.Pop();
squads[i].Push(chit->ID());
++nSquaddies;
break;
}
}
}
}
int CoreScript::Squaddies(int id, CChitArray* arr)
{
GLASSERT(id >= 0 && id < MAX_SQUADS);
if (arr) arr->Clear();
squads[id].Filter(this, [](CoreScript* cs, int fid){
return cs->IsCitizen(fid);
});
if (arr) {
for (int i = 0; i < squads[id].Size(); ++i) {
Chit* c = Context()->chitBag->GetChit(squads[id][i]);
if (c) {
arr->Push(c);
}
}
}
return squads[id].Size();
}
bool CoreScript::WantsToConquer(const grinliz::Vector2I& sector)
{
CoreScript* playerCore = Context()->chitBag->GetHomeCore();
if (playerCore != this) {
return true; // AI always conquers. Player needs a flag on target.
}
CoreScript* targetCore = CoreScript::GetCore(sector);
GLASSERT(targetCore);
if (!targetCore) return false;
for (int i = 0; i < MAX_SQUADS; ++i) {
if (!waypoints[i].Empty()) {
Vector2I pos = waypoints[i].Back();
if (ToWorld2I(targetCore->ParentChit()->Position()) == pos) {
return true;
}
}
}
return false;
}
bool CoreScript::IsSquaddieOnMission(int chitID, int* squadID)
{
if (!CitizenFilter(chitID)) {
return false;
}
for (int i = 0; i < MAX_SQUADS; ++i) {
if (squads[i].Find(chitID) >= 0) {
if (squadID) {
*squadID = i;
}
Chit* chit = Context()->chitBag->GetChit(chitID);
return !waypoints[i].Empty() || (ToSector(chit->Position()) != ToSector(ParentChit()->Position()));
}
}
return false;
}
bool CoreScript::ChangeSquad(Chit* chit, int targetSquad)
{
if (!this->IsCitizen(chit)) return false;
int currentSquad = this->SquadID(chit->ID());
if (currentSquad == targetSquad) return true;
// Can always move local:
if (targetSquad == -1) {
int idx = squads[currentSquad].Find(chit->ID());
GLASSERT(idx >= 0);
squads[currentSquad].SwapRemove(idx);
return true;
}
int n = this->Squaddies(targetSquad, nullptr);
if (n < SQUAD_SIZE) {
if (currentSquad >= 0) {
int idx = squads[currentSquad].Find(chit->ID());
GLASSERT(idx >= 0);
squads[currentSquad].SwapRemove(idx);
}
squads[targetSquad].PushIfCap(chit->ID());
return true;
}
return false;
}
void CoreScript::AddCitizen( Chit* chit )
{
Citizens(0); // Filters the current array.
GLASSERT(citizens.Size() < MAX_CITIZENS);
GLASSERT(ParentChit()->Team());
GLASSERT(!Team::IsRogue(ParentChit()->Team()));
GLASSERT( citizens.Find( chit->ID()) < 0 );
GLASSERT(Team::IsRogue(chit->Team()) || (chit->Team() == ParentChit()->Team()));
chit->GetItem()->SetTeam(ParentChit()->Team());
citizens.Push( chit->ID() );
AssignToSquads();
}
bool CoreScript::IsCitizen( Chit* chit )
{
return IsCitizen(chit->ID());
}
bool CoreScript::IsCitizen(int id)
{
int idx = citizens.Find(id);
return (idx >= 0) && (CitizenFilter(id) != 0);
}
bool CoreScript::IsCitizenItemID(int id)
{
for (int i = 0; i < citizens.Size(); ++i) {
int citizenID = citizens[i];
Chit* chit = CitizenFilter(citizenID);
if (chit && chit->GetItemID() == id) {
return true;
}
}
return false;
}
int CoreScript::SquadID(int chitID)
{
for (int i = 0; i < MAX_SQUADS; ++i) {
if (squads[i].Find(chitID) >= 0) {
if (IsCitizen(chitID))
return i;
}
}
return -1;
}
bool CoreScript::SquadAtRest(int squadID)
{
GLASSERT(squadID >= 0 && squadID < MAX_SQUADS);
if (!waypoints[squadID].Empty()) {
return false;
}
Vector2I sector = ToSector(ParentChit()->Position());
for (int i = 0; i < squads[squadID].Size(); ++i) {
int chitID = squads[squadID][i];
Chit* chit = Context()->chitBag->GetChit(chitID);
if (chit && ToSector(chit->Position()) != sector) {
return false;
}
}
return true;
}
Chit* CoreScript::CitizenFilter(int chitID)
{
Chit* chit = Context()->chitBag->GetChit(chitID);
if (chit && (chit->Team() == parentChit->Team())) {
return chit;
}
return 0;
}
int CoreScript::Citizens(CChitArray* arr)
{
int i=0;
while (i < citizens.Size()) {
int id = citizens[i];
Chit* chit = CitizenFilter(id);
if (chit) { // check for team change, throw out of citizens.
if (arr) arr->Push(chit);
++i;
}
else {
// Dead and gone.
citizens.SwapRemove(i);
// Reset the timer so that there is a little time
// between a dead citizen and re-spawn
spawnTick.Reset();
}
}
#if 0
// This is annoying: seeing if cranking down the spawn rate and not
// destroying the sleep tube achieves success.
// Also, destroy a sleeptube, so it costs something to replace, and towns can fall.
if ( sc ) {
Vector2F pos2 = sc->GetPosition2D();
Vector2I sector = ToSector( ToWorld2I( pos2 ));
Chit* bed = scriptContext->chitBag->FindBuilding( ISC::bed, sector, &pos2, LumosChitBag::RANDOM_NEAR, 0, 0 );
if ( bed && bed->GetItem() ) {
bed->GetItem()->hp = 0;
bed->SetTickNeeded();
}
}
#endif
return citizens.Size();
}
void CoreScript::AddFlag(const Vector2I& _pos)
{
Vector2I pos = _pos;
// A little UI fixup: set the flag to a porch
// if we click on the switch.
Chit* building = Context()->chitBag->QueryBuilding(IString(), pos, 0);
if (building && (building->GetItem()->IName() == ISC::switchOn || building->GetItem()->IName() == ISC::switchOff)) {
MapSpatialComponent* msc = GET_SUB_COMPONENT(building, SpatialComponent, MapSpatialComponent);
if (msc) {
pos = msc->PorchPos().min;
}
}
const WorldGrid& wg = Context()->worldMap->GetWorldGrid(pos);
if (wg.IsWater()) return;
Flag f = { pos, 0 };
if (flags.Find(f) < 0) {
Chit* chit = Context()->chitBag->NewChit();
RenderComponent* rc = new RenderComponent("flag");
chit->Add(rc);
ProcRenderInfo info;
AssignProcedural(ISC::team,
false,
ParentChit()->GetItem()->ID(),
ParentChit()->Team(),
false,
0,
0,
&info);
rc->SetProcedural(0, info);
chit->SetPosition(ToWorld3F(pos));
f.chitID = chit->ID();
flags.Push(f);
}
}
void CoreScript::ToggleFlag(const Vector2I& pos)
{
Flag f = { pos, 0 };
int i = flags.Find(f);
if (i >= 0)
RemoveFlag(pos);
else
AddFlag(pos);
}
void CoreScript::RemoveFlag(const Vector2I& pos)
{
Flag f = { pos, 0 };
int i = flags.Find(f);
if (i >= 0) {
if (flags[i].chitID) {
Chit* chit = Context()->chitBag->GetChit(flags[i].chitID);
if (chit) {
chit->QueueDelete();
}
flags[i].chitID = 0;
}
flags.Remove(i);
}
}
Vector2I CoreScript::GetAvailableFlag()
{
for (int i = 0; i < flags.Size(); ++i) {
if (tasks.Find(flags[i].pos) < 0) {
return flags[i].pos;
}
}
Vector2I v = { 0, 0 };
return v;
}
bool CoreScript::InUse() const
{
return parentChit->Team() != 0;
}
void CoreScript::UpdateAI()
{
if (sector.IsZero()) {
return;
}
int index = sector.y*NUM_SECTORS + sector.x;
GLASSERT(coreArr[index] == this);
}
bool CoreScript::RecruitNeutral()
{
Vector2I sector = ToSector(parentChit->Position());
Rectangle2I inner = InnerSectorBounds(sector);
MOBKeyFilter filter;
filter.value = ISC::denizen;
CChitArray arr;
Context()->chitBag->QuerySpatialHash(&arr, ToWorld2F(inner), 0, &filter);
for (int i = 0; i < arr.Size(); ++i) {
Chit* chit = arr[i];
if (Team::Instance()->GetRelationship(chit, parentChit) != ERelate::ENEMY) {
if (this->IsCitizen(chit)) continue;
if (!chit->GetItem()) continue;
if (Team::IsRogue(chit->Team())) {
// ronin! denizen without a core.
this->AddCitizen( chit );
GLASSERT(chit->GetItem()->Significant());
NewsEvent news(NewsEvent::ROGUE_DENIZEN_JOINS_TEAM, ToWorld2F(chit->Position()), chit->GetItemID(), 0);
Context()->chitBag->GetNewsHistory()->Add(news);
return true;
}
}
}
return false;
}
int CoreScript::DoTick(U32 delta)
{
int nScoreTicks = scoreTicker.Delta(delta);
int nAITicks = aiTicker.Delta(delta);
Citizens(0); // if someone was deleted, the spawn tick will reset.
int nSpawnTicks = spawnTick.Delta(delta);
// Clean rock off the core.
Vector2I pos2i = ToWorld2I(parentChit->Position());
const WorldGrid& wg = Context()->worldMap->GetWorldGrid(pos2i);
if (wg.RockHeight()) {
Context()->worldMap->SetRock(pos2i.x, pos2i.y, 0, false, 0);
}
if (InUse()) {
DoTickInUse(delta, nSpawnTicks);
UpdateScore(nScoreTicks);
}
else {
DoTickNeutral(delta, nSpawnTicks);
}
workQueue->DoTick();
if (nAITicks) {
UpdateAI();
}
for (int i = 0; i < MAX_SQUADS; ++i) {
if (squads[i].Empty()) {
waypoints[i].Clear();
}
}
if (strategicTicker.Delta(delta)) {
if (this->InUse() && Context()->chitBag->GetHomeCore() != this) {
DoStrategicTick();
}
}
RenderComponent* rc = parentChit->GetRenderComponent();
if (rc) {
int team = parentChit->Team();
CStr<40> str = "";
if (this->InUse() && Team::IsDenizen(team)) {
IString teamName = Team::Instance()->TeamName(team);
str.Format("%s", teamName.safe_str());
}
rc->SetDecoText(str.safe_str());
}
return Min(spawnTick.Next(), aiTicker.Next(), scoreTicker.Next());
}
int CoreScript::MaxCitizens(int nTemples)
{
return CITIZEN_BASE + Min(nTemples, MAX_SQUADS)*SQUAD_SIZE;
}
int CoreScript::NumTemples()
{
CChitArray chitArr;
Context()->chitBag->FindBuildingCC( ISC::temple, sector, 0, LumosChitBag::EFindMode::NEAREST, &chitArr, 0 );
int nTemples = chitArr.Size();
return nTemples;
}
int CoreScript::MaxCitizens()
{
CChitArray chitArr;
Context()->chitBag->FindBuildingCC( ISC::bed, sector, 0, LumosChitBag::EFindMode::NEAREST, &chitArr, 0 );
int nBeds = chitArr.Size();
int nTemples = NumTemples();
GLASSERT(nTemples >= 0);
int n = CoreScript::MaxCitizens(nTemples);
return Min(n, nBeds);
}
void CoreScript::DoTickInUse(int /*delta*/, int nSpawnTicks)
{
tech -= Lerp(TECH_DECAY_0, TECH_DECAY_1, tech / double(TECH_MAX));
int maxTech = MaxTech();
tech = Clamp(tech, 0.0, double(maxTech) - 0.01);
MapSpatialComponent* ms = GET_SUB_COMPONENT(parentChit, SpatialComponent, MapSpatialComponent);
GLASSERT(ms);
Vector2I pos2i = ms->MapPosition();
if (nSpawnTicks && Team::IsDenizen(parentChit->Team())) {
// Warning: essentially caps the #citizens to the capacity of CChitArray (32)
// Which just happend to work out with the game design. Citizen limits: 4, 8, 16, 32
int nCitizens = this->Citizens(0);
int maxCitizens = this->MaxCitizens();
if (nCitizens < maxCitizens) {
if (!RecruitNeutral()) {
Chit* chit = Context()->chitBag->NewDenizen(pos2i, parentChit->Team());
this->AddCitizen(chit);
}
}
}
}
void CoreScript::DoTickNeutral( int delta, int nSpawnTicks )
{
int lesser, greater, denizen;
const Census& census = Context()->chitBag->census;
census.NumByType(&lesser, &greater, &denizen);
IString defaultSpawn = Context()->worldMap->GetSectorData(sector).defaultSpawn;
int typical = 0;
int numOf = census.NumOf(defaultSpawn, &typical);
bool lesserPossible = (lesser < TYPICAL_LESSER) && (!typical || numOf < typical * 2);
Vector2I pos2i = ToWorld2I(parentChit->Position());
Vector2I sector = ToSector(pos2i);
if (nSpawnTicks && lesserPossible) {
#if SPAWN_MOBS > 0
int spawnEnabled = Context()->chitBag->GetSim()->SpawnEnabled() & Sim::SPAWN_LESSER;
if (Context()->chitBag->GetSim() && spawnEnabled && !defaultSpawn.empty()) {
Vector3F pf = { (float)pos2i.x + 0.5f, 0, (float)pos2i.y + 0.5f };
int nSpawn = (defaultSpawn == ISC::trilobyte) ? 4 : 1;
int team = Team::GetTeam(defaultSpawn);
GLASSERT(team != TEAM_NEUTRAL);
for (int i = 0; i < nSpawn; ++i) {
Context()->chitBag->NewMonsterChit(pf, defaultSpawn.safe_str(), team);
pf.x += 0.05f;
}
}
#endif
}
// Clear the work queue - chit is gone that controls this.
if (!workQueue || workQueue->HasJob()) {
delete workQueue;
workQueue = new WorkQueue();
workQueue->InitSector(parentChit, ToSector(parentChit->Position()));
}
}
float CoreScript::CivTech()
{
int nCitizens = Citizens(0);
int nTemples = NumTemples();
float citizenScore = float(nCitizens) / float(MAX_CITIZENS);
float templeScore = float(nTemples) / float(MAX_SQUADS);
return (citizenScore + templeScore) * 0.5f;
}
void CoreScript::UpdateScore(int n)
{
static const double FACTOR = 0.002;
if (n) {
// Tuned - somewhat sleazily - that basic 4 unit, 0 temple is one point.
double score = CivTech() * double(n) * double(scoreTicker.Period()) * FACTOR;
achievement.civTechScore += Min(1, int(score));
int team = ParentChit()->Team();
CDynArray<int> subTeams;
if (Team::Instance()->IsController(team, &subTeams)) {
for (int i = 0; i < subTeams.Size(); ++i) {
CoreScript* subCore = CoreScript::GetCoreFromTeam(subTeams[i]);
if (subCore) {
score += 0.5 * subCore->CivTech() * double(n) * double(scoreTicker.Period()) * FACTOR;
}
}
}
// Push this to the GameItem, so it can be recorded in the history + census.
GameItem* gi = ParentChit()->GetItem();
if (gi) {
// Score is a 16 bit quantity...
int s = achievement.civTechScore;
if (s > 65535) s = 65535;
gi->keyValues.Set(ISC::score, s);
gi->UpdateHistory();
}
}
if (ParentChit()->GetItem()) {
achievement.gold = Max(achievement.gold, ParentChit()->GetItem()->wallet.Gold());
achievement.population = Max(achievement.population, citizens.Size());
}
}
int CoreScript::MaxTech()
{
Vector2I sector = ToSector(parentChit->Position());
CChitArray chitArr;
Context()->chitBag->FindBuildingCC(ISC::temple, sector, 0, LumosChitBag::EFindMode::NEAREST, &chitArr, 0);
return Min(chitArr.Size() + 1, TECH_MAX); // get one power for core
}
void CoreScript::AddTech()
{
tech += TECH_ADDED_BY_VISITOR;
tech = Clamp( tech, 0.0, Min( double(TECH_MAX), double( MaxTech() ) - 0.01 ));
achievement.techLevel = Max(achievement.techLevel, (int)tech);
int team = ParentChit()->Team();
int superTeam = Team::Instance()->SuperTeam(team);
if (team != superTeam) {
CoreScript* super = CoreScript::GetCoreFromTeam(superTeam);
if (super) {
super->AddTech();
// EXPERIMENTAL: also transfer Au
Wallet* wallet = parentChit->GetWallet();
GLASSERT(wallet);
if (wallet
&& super->ParentChit()->GetWallet()
&& (wallet->Gold() > (GOLD_XFER_TAKEOVER *3/2)))
{
int gold = GOLD_XFER_TAKEOVER / 10;
super->ParentChit()->GetWallet()->Deposit(wallet, gold);
}
}
}
}
void CoreScript::AddTask(const grinliz::Vector2I& pos2i)
{
tasks.Push(pos2i);
}
void CoreScript::RemoveTask(const grinliz::Vector2I& pos2i)
{
int i = tasks.Find(pos2i);
// GLASSERT(i >= 0); with core deletion, this can be tricky...
// FIXME: should be a safe check. Check with core deletion.
if (i >= 0){
tasks.Remove(i);
}
}
bool CoreScript::HasTask(const grinliz::Vector2I& pos2i)
{
return tasks.Find(pos2i) >= 0;
}
CoreScript** CoreScript::GetCoreList(int *n)
{
*n = coreList.Size();
return coreList.Mem();
}
CoreScript* CoreScript::GetCoreFromTeam(int team)
{
if (!teamToCoreInfo)
return 0; // happens on tear down
if (team == 0)
return 0;
int index = 0;
if (teamToCoreInfo->Query(team, &index)) {
// Make sure it is current:
GLASSERT(index >= 0 && index < NUM_SECTORS*NUM_SECTORS);
CoreScript* cs = coreArr[index];
// GLASSERT(cs); // cores get destroyed at odd times.
if (cs && cs->ParentChit()->Team() == team) {
return cs;
}
}
for (int i = 0; i < NUM_SECTORS*NUM_SECTORS; ++i) {
if (coreArr[i] && coreArr[i]->ParentChit()->Team() == team) {
teamToCoreInfo->Add(team, i);
return coreArr[i];
}
}
return 0;
}
CoreScript* CoreScript::CreateCore( const Vector2I& sector, int team, const ChitContext* context)
{
// Destroy the existing core.
// Create a new core, attached to the player.
CoreScript* cs = CoreScript::GetCore(sector);
if (cs) {
Chit* core = cs->ParentChit();
GLASSERT(core);
CDynArray< Chit* > queryArr;
// Tell all the AIs the core is going away.
ChitHasAIComponent filter;
Rectangle2F b = ToWorld2F(InnerSectorBounds(sector));
context->chitBag->QuerySpatialHash(&queryArr, b, 0, &filter);
for (int i = 0; i < queryArr.Size(); ++i) {
queryArr[i]->GetAIComponent()->ClearTaskList();
}
//context.chitBag->QueueDelete(core);
// QueueDelete is safer, but all kinds of asserts fire (correctly)
// if 2 cores are in the same place. This may cause an issue
// if CreateCore is called during the DoTick()
// Setting the hp to 0 and then calling DoTick()
// is a sleazy trick to clean up.
core->GetItem()->hp = 0;
if (core->GetHealthComponent()) {
core->GetHealthComponent()->DoTick(1);
}
context->chitBag->DeleteChit(core);
}
const SectorData& sd = context->worldMap->GetSectorData(sector);
if (sd.HasCore()) {
int group = 0, id = 0;
Team::SplitID(team, &group, &id);
// Lots of trouble with this code. Used to assert,
// but always seemed to be another case. White list
// groups that *can* take over a core.
if (team == TEAM_NEUTRAL || team == TEAM_TROLL || Team::IsDeity(team) || Team::IsDenizen(team)) {
// Okay! take over.
GLASSERT(!Team::IsDenizen(team) || id); // make sure rogues got filtered out.
}
else {
team = group = id = 0;
}
Chit* chit = context->chitBag->NewBuilding(sd.core, "core", team);
// 'in use' instead of blocking.
MapSpatialComponent* ms = GET_SUB_COMPONENT(chit, SpatialComponent, MapSpatialComponent);
GLASSERT(ms);
ms->SetBlocks(false);
CoreScript* cs = new CoreScript();
chit->Add(cs);
GLASSERT(CoreScript::GetCore(ToSector(sd.core)) == cs);