1 /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
2 
3 #include "NanoPieceCache.h"
4 #include "Sim/Misc/GlobalSynced.h"
5 #include "Sim/Units/Scripts/UnitScript.h"
6 
7 CR_BIND(NanoPieceCache, )
8 
9 CR_REG_METADATA(NanoPieceCache, (
10 	CR_MEMBER(nanoPieces),
11 	CR_MEMBER(lastNanoPieceCnt),
12 	CR_MEMBER(curBuildPowerMask)
13 ))
14 
GetNanoPiece(CUnitScript * ownerScript)15 int NanoPieceCache::GetNanoPiece(CUnitScript* ownerScript) {
16 	assert(UNIT_SLOWUPDATE_RATE == 16);
17 	curBuildPowerMask |= (1 << (UNIT_SLOWUPDATE_RATE - 1));
18 
19 	int nanoPiece = -1;
20 
21 	if (!nanoPieces.empty()) {
22 		const unsigned cnt = nanoPieces.size();
23 		const unsigned rnd = gs->randInt();
24 		nanoPiece = nanoPieces[rnd % cnt];
25 	}
26 
27 	if (lastNanoPieceCnt <= MAX_QUERYNANOPIECE_CALLS) {
28 		// only do so 30 times and then use the cache
29 		const int scriptPiece = ownerScript->QueryNanoPiece();
30 		const int modelPiece  = ownerScript->ScriptToModel(scriptPiece);
31 
32 		if (ownerScript->PieceExists(scriptPiece)) {
33 			nanoPiece = modelPiece;
34 
35 			if (std::find(nanoPieces.begin(), nanoPieces.end(), nanoPiece) != nanoPieces.end()) {
36 				// already in cache
37 				lastNanoPieceCnt++;
38 			} else {
39 				nanoPieces.push_back(nanoPiece);
40 				lastNanoPieceCnt = 0;
41 			}
42 		} else {
43 			lastNanoPieceCnt++;
44 		}
45 	}
46 
47 	return nanoPiece;
48 }
49 
50