Open source Star Ruler 2 source code!

This commit is contained in:
Lucas de Vries
2018-07-17 14:15:37 +02:00
commit cc307720ff
4342 changed files with 2365070 additions and 0 deletions
+548
View File
@@ -0,0 +1,548 @@
import saving;
import hooks;
import icons;
import util.formatting;
export AbilityType, Ability;
export getAbilityTypeCount, getAbilityType;
export Targets, TargetType;
tidy final class AbilityType {
uint id = 0;
string ident;
string name;
string description;
double energyCost = 0.0;
double cooldown = 0.0;
double range = INFINITY;
Sprite icon = icons::Ability;
Targets targets;
int objectCast = -1;
int hotkey = 0;
bool empireDefault = false;
bool hideGlobal = false;
const SoundSource@ activateSound;
array<IAbilityHook@> hooks;
};
interface IAbilityHook {
void create(Ability@ abl, any@ data) const;
void destroy(Ability@ abl, any@ data) const;
void enable(Ability@ abl, any@ data) const;
void disable(Ability@ abl, any@ data) const;
void tick(Ability@ abl, any@ data, double time) const;
void save(Ability@ abl, any@ data, SaveFile& file) const;
void load(Ability@ abl, any@ data, SaveFile& file) const;
void changeTarget(Ability@ abl, any@ data, uint index, Target@ oldTarget, Target@ newTarget) const;
void modEnergyCost(const Ability@ abl, const Targets@ targs, double& cost) const;
string getFailReason(const Ability@ abl, uint index, const Target@ targ) const;
bool isValidTarget(const Ability@ abl, uint index, const Target@ targ) const;
bool canActivate(const Ability@ abl, const Targets@ targs, bool ignoreCost) const;
void activate(Ability@ abl, any@ data, const Targets@ targs) const;
bool consume(Ability@ abl, any@ data, const Targets@ targs) const;
void reverse(Ability@ abl, any@ data, const Targets@ targs) const;
bool getVariable(const Ability@ abl, Sprite& sprt, string& name, string& value, Color& color) const;
bool formatCost(const Ability@ abl, const Targets@ targs, string& value) const;
bool isChanneling(const Ability@ abl, const any@ data) const;
}
class AbilityHook : Hook, IAbilityHook {
void create(Ability@ abl, any@ data) const {}
void destroy(Ability@ abl, any@ data) const {}
void enable(Ability@ abl, any@ data) const {}
void disable(Ability@ abl, any@ data) const {}
void tick(Ability@ abl, any@ data, double time) const {}
void save(Ability@ abl, any@ data, SaveFile& file) const {}
void load(Ability@ abl, any@ data, SaveFile& file) const {}
void changeTarget(Ability@ abl, any@ data, uint index, Target@ oldTarget, Target@ newTarget) const {}
string getFailReason(const Ability@ abl, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(const Ability@ abl, uint index, const Target@ targ) const { return true; }
void modEnergyCost(const Ability@ abl, const Targets@ targs, double& cost) const {}
bool canActivate(const Ability@ abl, const Targets@ targs, bool ignoreCost) const { return true; }
void activate(Ability@ abl, any@ data, const Targets@ targs) const {}
bool consume(Ability@ abl, any@ data, const Targets@ targs) const { return true; }
void reverse(Ability@ abl, any@ data, const Targets@ targs) const {}
bool getVariable(const Ability@ abl, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
bool formatCost(const Ability@ abl, const Targets@ targs, string& value) const { return false; }
bool isChanneling(const Ability@ abl, const any@ data) const { return false; }
};
tidy class Ability : Serializable, Savable {
int id = -1;
const AbilityType@ type;
const Subsystem@ subsystem;
Empire@ emp;
Object@ obj;
Object@ toggle;
bool disabled = false;
double cooldown = 0.0;
array<any> data;
Targets targets;
Ability() {
}
Ability(const AbilityType@ type) {
@this.type = type;
data.length = type.hooks.length;
targets = Targets(type.targets);
}
double getRange(const Targets@ targs = null) const {
return type.range;
}
bool isChanneling() const {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(type.hooks[i].isChanneling(this, data[i]))
return true;
}
return false;
}
string formatTooltip(Empire@ forEmp = null) const {
string tt;
tt += format("[b]$1[/b]", type.name);
if(type.hotkey != 0)
tt += format(" "+locale::ABL_HOTKEY_SPEC, getKeyDisplayName(type.hotkey));
tt += "\n"+type.description+"\n";
string vname, vvalue;
Sprite vicon;
Color color;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(type.hooks[i].getVariable(this, vicon, vname, vvalue, color)) {
tt += format("[nl/][vspace=6/][img=$1;22][b][color=$4]$2[/color][/b] [offset=120]$3[/offset][/img]",
getSpriteDesc(vicon), vname, vvalue, toString(color));
color = colors::White;
}
}
double cost = getEnergyCost();
if(cost != 0)
tt += format("[nl/][vspace=6/][img=ResourceIcon::2;22][b][color=#20b6e3]$1:[/color][/b][offset=120]$2[/offset][/img]",
locale::ENERGY_COST, standardize(cost, true));
if(type.cooldown != 0) {
if(cooldown > 0) {
tt += format("[nl/][vspace=6/][img=ContextIcons::1;22][b][color=#9622bb]$1:[/color][/b][offset=120]$2 / $3[/offset][/img]",
locale::COOLDOWN, formatTime(cooldown), formatTime(type.cooldown));
}
else {
tt += format("[nl/][vspace=6/][img=ContextIcons::1;22][b][color=#9622bb]$1:[/color][/b][offset=120]$2[/offset][/img]",
locale::COOLDOWN, formatTime(type.cooldown));
}
}
else if(cooldown > 0) {
tt += format("[nl/][vspace=6/][img=ContextIcons::1;22][b][color=#9622bb]$1:[/color][/b][offset=120]$2[/offset][/img]",
locale::COOLDOWN, formatTime(cooldown));
}
return tt;
}
string formatCosts(const Targets@ targs = null) const {
string costs;
double cost = getEnergyCost(targs);
if(cost > 0)
costs += format(locale::ABILITY_ENERGY, standardize(cost));
string value;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(type.hooks[i].formatCost(this, targs, value)) {
if(costs.length != 0)
costs += ", ";
costs += value;
value = "";
}
}
return costs;
}
void changeTarget(const Argument@ arg, Target@ newTarg) {
Target@ storeTarg = arg.fromTarget(targets);
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].changeTarget(this, data[i], arg.integer, storeTarg, newTarg);
storeTarg = newTarg;
}
void write(Message& msg) {
msg << type.id;
msg << id;
msg << disabled;
msg << cooldown;
msg << emp;
msg << obj;
msg << targets;
if(subsystem !is null) {
msg.write1();
msg << subsystem.inDesign;
msg << subsystem.index;
}
else {
msg.write0();
}
}
void read(Message& msg) {
uint tid = 0;
msg >> tid;
@type = getAbilityType(tid);
msg >> id;
msg >> disabled;
msg >> cooldown;
msg >> emp;
msg >> obj;
msg >> targets;
if(msg.readBit()) {
const Design@ dsg;
msg >> dsg;
@subsystem = dsg.subsystems[msg.read_uint()];
}
}
void save(SaveFile& file) {
file << id;
file.writeIdentifier(SI_AbilityType, type.id);
file << disabled;
file << cooldown;
file << emp;
file << obj;
file << targets;
if(subsystem !is null) {
file.write1();
file << subsystem.inDesign;
file << subsystem.index;
}
else {
file.write0();
}
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].save(this, data[i], file);
}
void load(SaveFile& file) {
file >> id;
uint tid = file.readIdentifier(SI_AbilityType);
@type = getAbilityType(tid);
data.length = type.hooks.length;
file >> disabled;
file >> cooldown;
file >> emp;
file >> obj;
if(file >= SV_0081)
file >> targets;
else
targets = Targets(type.targets);
if(file.readBit()) {
const Design@ dsg;
file >> dsg;
uint index = 0;
file >> index;
@subsystem = dsg.subsystems[index];
}
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].load(this, data[i], file);
}
double getEnergyCost(const Targets@ targs = null) const {
double cost = type.energyCost;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].modEnergyCost(this, targs, cost);
return cost;
}
bool checkTargets(const Targets@ check) const {
if(check is null) {
if(type.targets.length == 0)
return true;
else
return false;
}
if(check.targets.length != type.targets.length)
return false;
for(uint i = 0, cnt = check.targets.length; i < cnt; ++i) {
if(!isValidTarget(i, check.targets[i]))
return false;
}
return true;
}
bool isValidTarget(uint index, const Target@ targ) const {
if(index >= type.targets.length)
return false;
if(targ.type != type.targets[index].type)
return false;
if(!targ.filled)
return false;
if(type.targets[index].filled && type.targets[index] != targ)
return false;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].isValidTarget(this, index, targ))
return false;
}
return true;
}
bool canActivate(const Targets@ targs = null, bool ignoreCost = false) const {
if(targs !is null && !checkTargets(targs))
return false;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].canActivate(this, targs, ignoreCost))
return false;
}
if(!ignoreCost) {
double energy = getEnergyCost(targs);
if(energy != 0.0 && emp.EnergyStored < energy)
return false;
}
return true;
}
bool getTargetError(uint index, const Target@ targ, string& str) const {
if(index >= type.targets.length)
return false;
if(targ.type != type.targets[index].type)
return false;
if(!targ.filled)
return false;
if(type.targets[index].filled && type.targets[index] != targ)
return false;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].isValidTarget(this, index, targ)) {
str = type.hooks[i].getFailReason(this, index, targ);
return true;
}
}
return false;
}
string getTargetError(const Targets@ check) {
string str;
for(uint i = 0, cnt = check.targets.length; i < cnt; ++i) {
if(getTargetError(i, check.targets[i], str))
return str;
}
return str;
}
#section server
bool activate(const Targets@ targs) {
if(!canActivate(targs))
return false;
double energy = getEnergyCost(targs);
if(energy != 0.0 && emp.consumeEnergy(energy, false) == 0.0)
return false;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].consume(this, data[i], targs)) {
for(uint j = 0; j < i; ++j)
type.hooks[j].reverse(this, data[j], targs);
if(energy != 0.0)
emp.modEnergyStored(energy);
return false;
}
}
cooldown = -1.0;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].activate(this, data[i], targs);
if(cooldown < 0) {
if(type.cooldown != 0.0)
cooldown = type.cooldown;
else
cooldown = 0;
}
return true;
}
void create() {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].create(this, data[i]);
}
void destroy() {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].destroy(this, data[i]);
}
void enable() {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].enable(this, data[i]);
}
void disable() {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].disable(this, data[i]);
}
void tick(double time) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].tick(this, data[i], time);
}
#section all
};
array<AbilityType@> abilities;
dictionary abilityIdents;
int getAbilityID(const string& ident) {
AbilityType@ type;
abilityIdents.get(ident, @type);
if(type !is null)
return int(type.id);
return -1;
}
string getAbilityIdent(int id) {
if(id < 0 || id >= int(abilities.length))
return "-";
return abilities[id].ident;
}
uint getAbilityTypeCount() {
return abilities.length;
}
const AbilityType@ getAbilityType(uint id) {
if(id < abilities.length)
return abilities[id];
else
return null;
}
const AbilityType@ getAbilityType(const string& name) {
AbilityType@ abl;
abilityIdents.get(name, @abl);
return abl;
}
void addAbilityType(AbilityType@ abl) {
abl.id = abilities.length;
abilities.insertLast(abl);
abilityIdents.set(abl.ident, @abl);
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = abilities.length; i < cnt; ++i) {
AbilityType@ type = abilities[i];
file.addIdentifier(SI_AbilityType, type.id, type.ident);
}
}
void parseLine(string& line, AbilityType@ type, ReadFile@ file) {
//Hook line
auto@ hook = cast<IAbilityHook>(parseHook(line, "ability_effects::", instantiate=false, file=file));
if(hook !is null)
type.hooks.insertLast(hook);
}
void loadAbilities(const string& filename) {
ReadFile file(filename, true);
string key, value;
AbilityType@ type;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
string line = file.line;
parseLine(line, type, file);
}
else if(key.equals_nocase("Ability")) {
if(type !is null)
addAbilityType(type);
@type = AbilityType();
type.ident = value;
}
else if(type is null) {
file.error("Missing Ability ID line");
}
else if(key.equals_nocase("Name")) {
type.name = localize(value);
}
else if(key.equals_nocase("Description")) {
type.description = localize(value);
}
else if(key.equals_nocase("Icon")) {
type.icon = getSprite(value);
}
else if(key.equals_nocase("Energy Cost")) {
type.energyCost = toDouble(value);
}
else if(key.equals_nocase("Cooldown")) {
type.cooldown = toDouble(value);
}
else if(key.equals_nocase("Range")) {
type.range = toDouble(value);
}
else if(key.equals_nocase("Hide Global")) {
type.hideGlobal = toBool(value);
}
else if(key.equals_nocase("Empire Default")) {
type.empireDefault = toBool(value);
}
else if(key.equals_nocase("Target")) {
parseTarget(type.targets, value);
}
else if(key.equals_nocase("Activate Sound")) {
@type.activateSound = getSound(value);
if(type.activateSound is null)
file.error("Could not find activation sound '"+value+"'.");
}
else if(key.equals_nocase("Hotkey")) {
type.hotkey = getKey(value);
}
else if(key.equals_nocase("Object Cast")) {
auto@ targ = type.targets.get(value);
if(targ is null) {
file.error("Could not find target "+value);
continue;
}
if(targ.type != TT_Object) {
file.error("Target "+value+" is not an object target.");
continue;
}
type.objectCast = type.targets.getIndex(value);
}
else {
string line = file.line;
parseLine(line, type, file);
}
}
if(type !is null)
addAbilityType(type);
}
void preInit() {
FileList list("data/abilities", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadAbilities(list.path[i]);
}
void init() {
for(uint i = 0, cnt = abilities.length; i < cnt; ++i) {
auto@ type = abilities[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n) {
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook "+addrstr(type.hooks[n])+" on ability "+type.ident);
else
cast<Hook>(type.hooks[n]).initTargets(type.targets);
}
}
}
File diff suppressed because it is too large Load Diff
+338
View File
@@ -0,0 +1,338 @@
import hooks;
import artifacts;
import resources;
import ai.consider;
#section server
from empire import Creeps;
#section all
interface Artifacts {
Empire@ get_empire();
Considerer@ get_consider();
}
class ArtifactAI : Hook, ConsiderHook {
double consider(Considerer& cons, Object@ obj) const {
return 0.0;
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const {
return false;
}
};
class Value : ArtifactAI {
Document doc("Sets the value for the artifact to a basic amount.");
Argument value(AT_Decimal, doc="Value to set for the artifact.");
#section server
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
value *= this.value.decimal;
return true;
}
#section all
};
class ActivateOnBestFleet : ArtifactAI {
Document doc("This artifact should be activated on our strongest fleet that it can be.");
Argument value(AT_Decimal, "1.0", doc="Value for activating on the best fleet.");
Argument min_strength(AT_Decimal, "1000", doc="Minimum strength for a fleet to be considered for this.");
#section server
double consider(Considerer& cons, Object@ fleet) const override {
double str = fleet.getFleetStrength() * 0.001;
if(str < min_strength.decimal)
return 0.0;
if(!cons.artifact.canTarget(fleet))
return 0.0;
return str;
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
@ai.consider.artifact = c;
Object@ best = ai.consider.Fleets(this);
if(best !is null) {
c.setTarget(best);
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
class ActivateOnBestPlanet : ArtifactAI {
Document doc("This artifact should be activated on our best planet that it can be.");
Argument value(AT_Decimal, "1.0", doc="Value for activating on the best planet.");
Argument min_population(AT_Decimal, "10", doc="Minimum population for a planet to be considered for this.");
#section server
double consider(Considerer& cons, Object@ planet) const override {
double pop = planet.population;
if(pop < min_population.decimal)
return 0.0;
if(!cons.artifact.canTarget(planet))
return 0.0;
return pop;
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
@ai.consider.artifact = c;
Object@ best = ai.consider.ImportantPlanets(this);
if(best !is null) {
c.setTarget(best);
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
class AsCreatedResource : ArtifactAI {
Document doc("This artifact is used to spawn a new resource type on a planet that needs it.");
Argument resource(AT_PlanetResource, doc="Resource to match import requests to.");
Argument value(AT_Decimal, "1.0", doc="Value for activating this.");
Argument replaces_existing(AT_Boolean, "True", doc="Whether this can be used to replace an existing import of that type or not.");
#section server
double consider(Considerer& cons, Object@ requestedAt) const override {
if(!cons.artifact.canTarget(requestedAt))
return 0.0;
if(cons.currentSupplier !is null)
return 0.5;
return 1.0;
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
@ai.consider.artifact = c;
Object@ best = ai.consider.MatchingImportRequests(this, getResource(resource.integer), replaces_existing.boolean);
if(best !is null) {
c.setTarget(best);
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
class ActivateInOwnedSystem : ArtifactAI {
Document doc("Activate this artifact on a position in an arbitrary owned system.");
Argument value(AT_Decimal, "1.0", doc="Value for activating this.");
#section server
double consider(Considerer& cons, Object@ obj) const override {
Region@ sys = cast<Region>(obj);
if(sys.PlanetsMask & ~cons.empire.mask != 0)
return randomd(0.4, 0.6);
return randomd(0.9, 1.1);
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
Region@ best = cast<Region>(ai.consider.OwnedSystems(this));
if(best !is null) {
vec3d position = best.position;
vec2d offset = random2d(best.radius * 0.4, best.radius * 0.85);
position.x += offset.x;
position.z += offset.y;
if(!c.canTargetPosition(position))
return false;
c.setTargetPosition(position);
if(best.PlanetsMask & ~ai.empire.mask != 0)
value *= 0.5;
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
class ActivateNearOwnedSystem : ArtifactAI {
Document doc("Activate this artifact on a position placed outside an arbitrary owned system.");
Argument value(AT_Decimal, "1.0", doc="Value for activating this.");
Argument min_distance(AT_Decimal, "2000", doc="Minimum distance from the system boundary to place it.");
#section server
double consider(Considerer& cons, Object@ obj) const override {
Region@ sys = cast<Region>(obj);
if(sys.PlanetsMask & ~cons.empire.mask != 0)
return randomd(0.4, 0.6);
return randomd(0.9, 1.1);
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
Region@ best = cast<Region>(ai.consider.OwnedSystems(this));
if(best !is null) {
vec3d position = best.position;
vec2d offset = random2d(best.radius + min_distance.decimal, best.radius + min_distance.decimal * 2.0);
position.x += offset.x;
position.z += offset.y;
position.y += min_distance.decimal * randomd(0.0, 0.25);
if(!c.canTargetPosition(position))
return false;
c.setTargetPosition(position);
if(best.PlanetsMask & ~ai.empire.mask != 0)
value *= 0.5;
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
class AsVisionGain : ArtifactAI {
Document doc("Activate this to gain vision over systems with other people in them we want to see.");
Argument value(AT_Decimal, "1.0", doc="Value for activating this.");
#section server
double consider(Considerer& cons, Object@ obj) const override {
Region@ sys = cast<Region>(obj);
if(sys.VisionMask & cons.empire.visionMask != 0)
return 0.0;
if(!cons.artifact.canTarget(sys))
return 0.0;
double w = 1.0;
if(sys.PlanetsMask & cons.empire.hostileMask != 0)
w *= 2.0;
return w * randomd(0.9, 1.1);
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
@ai.consider.artifact = c;
Region@ best = cast<Region>(ai.consider.OtherSystems(this));
if(best !is null) {
c.setTarget(best);
value *= this.value.decimal;
if(best.PlanetsMask & ai.empire.hostileMask != 0)
value *= 2.0;
return true;
}
else {
return false;
}
}
#section all
};
class RevenantPart : ArtifactAI {
Document doc("Special AI to deal with using parts of the revenant.");
#section server
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
//If we are subjugated don't use these
if(ai.empire.SubjugatedBy !is null)
return false;
value *= 10.0;
//If we have parts ourselves, weight more
value *= pow(2.0, ai.empire.RevenantParts);
//If an enemy has multilple parts, weight more
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ other = getEmpire(i);
if(!other.major || other !is ai.empire)
value *= pow(3.0, other.RevenantParts);
}
return true;
}
#section all
};
class ActivateAsPressureBoost : ArtifactAI {
Document doc("Activate this artifact on a planet to boost its pressure.");
Argument value(AT_Decimal, "1.0", doc="Value for activating on the best planet.");
Argument pressure_amount(AT_Decimal, "1.0", doc="Amount of pressure that is added.");
#section server
double consider(Considerer& cons, Object@ planet) const override {
auto@ res = getResource(planet.primaryResourceType);
if(res is null)
return 0.0;
if(res.totalPressure < 1)
return 0.0;
double pres = planet.totalPressure;
double cap = planet.pressureCap;
if(pres + pressure_amount.decimal > cap * 1.5)
return 0.0;
if(!cons.artifact.canTarget(planet))
return 0.0;
return 1.0;
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
@ai.consider.artifact = c;
Object@ best = ai.consider.SomePlanets(this);
Object@ existing = c.getTarget();
if(existing !is null && consider(ai.consider, existing) > ai.consider.selectedWeight)
@best = existing;
if(best !is null) {
c.setTarget(best);
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
class ActivateOnRemnantStation : ArtifactAI {
Document doc("Find remnant stations to trigger this on.");
Argument value(AT_Decimal, "1.0", doc="Value for activating on the best station.");
#section server
double consider(Considerer& cons, Object@ obj) const override {
Region@ reg = cast<Region>(obj);
if(reg.getStrength(Creeps) > 0)
return 1.0;
return 0.0;
}
bool consider(Artifacts& ai, ArtifactConsider& c, double& value) const override {
@ai.consider.artifact = c;
Object@ best;
Object@ reg = cast<Region>(ai.consider.OwnedSystems(this));
if(reg !is null) {
Object@ en = reg.findEnemy(ai.empire, Creeps.mask, fleets=false, stations=true);
if(en !is null) {
if(c.canTarget(en))
@best = en;
}
}
Object@ existing = c.getTarget();
if(best is null && existing !is null && existing.valid && c.canTarget(existing))
@best = existing;
if(best !is null) {
c.setTarget(best);
value *= this.value.decimal;
return true;
}
else {
return false;
}
}
#section all
};
+141
View File
@@ -0,0 +1,141 @@
import hooks;
import buildings;
import resources;
import ai.consider;
interface Buildings : ConsiderComponent {
Empire@ get_empire();
Considerer@ get_consider();
bool requestsFTLStorage();
bool isBuilding(const BuildingType& type);
bool isFocus(Object@ obj);
void registerUse(BuildingUse use, const BuildingType& type);
};
enum BuildingUse {
BU_Factory,
BU_LaborStorage,
};
const array<string> BuildingUseName = {
"Factory",
"LaborStorage",
};
class BuildingAI : Hook, ConsiderHook {
double consider(Considerer& cons, Object@ obj) const {
return 0.0;
}
void register(Buildings& buildings, const BuildingType& type) const {
}
//Return the planet to build this building on
Object@ considerBuild(Buildings& buildings, const BuildingType& type) const {
return null;
}
};
class RegisterForUse : BuildingAI {
Document doc("Register this building for a particular use. Only one building can be used for a specific specialized use.");
Argument use(AT_Custom, doc="Specialized usage for this building.");
void register(Buildings& buildings, const BuildingType& type) const override {
for(uint i = 0, cnt = BuildingUseName.length; i < cnt; ++i) {
if(BuildingUseName[i] == use.str) {
buildings.registerUse(BuildingUse(i), type);
return;
}
}
}
};
class AsCreatedResource : BuildingAI {
Document doc("This building is used to spawn a new resource type on a planet that needs it.");
Argument resource(AT_PlanetResource, doc="Resource to match import requests to.");
Argument minimum_idle(AT_Decimal, "180", doc="Minimum amount of time the resource request has to have been idle to consider this.");
Argument minimum_colonize_idle(AT_Decimal, "180", doc="Minimum amount of time since we've colonized something matching the request before we consider building this.");
Argument minimum_gametime(AT_Decimal, "1500", doc="Minimum gametime that needs to have passed before we consider building this.");
#section server
double consider(Considerer& cons, Object@ requestedAt) const override {
double w = 1.0;
if(cons.currentSupplier !is null)
return 0.0;
if(cons.idleTime < minimum_idle.decimal)
return 0.0;
if(cons.timeSinceMatchingColonize() < minimum_colonize_idle.decimal)
return 0.0;
if(!cons.building.canBuildOn(requestedAt, ignoreState=true))
return 0.0;
return w;
}
Object@ considerBuild(Buildings& buildings, const BuildingType& type) const override {
if(gameTime < minimum_gametime.decimal)
return null;
@buildings.consider.building = type;
return buildings.consider.MatchingImportRequests(this, getResource(resource.integer), false);
}
#section all
};
class BuildForPressureCap : BuildingAI {
Document doc("Build this to increase the pressure capacity on a planet.");
Argument increase(AT_Integer, doc="Pressure this should increase the cap by.");
#section server
double consider(Considerer& cons, Object@ obj) const override {
double w = 1.0;
int pres = obj.totalPressure;
int cap = obj.pressureCap;
if(pres <= cap)
return 0.0;
if(obj.level <= 0)
return 0.0;
if(double(obj.population) < double(obj.maxPopulation) * 0.9)
return 0.0;
double eff = double(pres) / double(cap);
if(eff < 1.5 && cap + increase.integer > 2 * pres)
return 0.0;
if(!cons.building.canBuildOn(obj, ignoreState=true))
return 0.0;
return eff;
}
Object@ considerBuild(Buildings& buildings, const BuildingType& type) const override {
@buildings.consider.building = type;
return buildings.consider.SomePlanets(this);
}
#section all
};
class AsFTLStorage : BuildingAI {
Document doc("This building is built whenever more ftl storage is requested.");
#section server
double consider(Considerer& cons, Object@ obj) const override {
if(cast<Buildings>(cons.component).isFocus(obj))
return 0.0;
if(obj.emptyDevelopedTiles < 10)
return 0.0;
if(!cons.building.canBuildOn(obj, ignoreState=true))
return 0.0;
return 1.0;
}
Object@ considerBuild(Buildings& buildings, const BuildingType& type) const override {
if(!buildings.requestsFTLStorage())
return null;
if(buildings.isBuilding(type))
return null;
@buildings.consider.component = buildings;
@buildings.consider.building = type;
return buildings.consider.SomePlanets(this);
}
#section all
};
+75
View File
@@ -0,0 +1,75 @@
import resources;
import buildings;
export Considerer;
export ConsiderHook;
export ArtifactConsider;
export ConsiderComponent;
export ConsiderFilter;
interface ArtifactConsider {
void setTarget(Object@ obj);
Object@ getTarget();
bool canTarget(Object@ obj);
void setTargetPosition(const vec3d& pos);
vec3d getTargetPosition();
bool canTargetPosition(const vec3d& pos);
};
interface ConsiderComponent {
};
interface ConsiderFilter {
bool filter(Object@ obj);
};
interface Considerer {
Empire@ get_empire();
Object@ get_currentSupplier();
ArtifactConsider@ get_artifact();
void set_artifact(ArtifactConsider@ cons);
double get_selectedWeight();
double get_idleTime();
const BuildingType@ get_building();
void set_building(const BuildingType@ type);
ConsiderComponent@ get_component();
void set_component(ConsiderComponent@ comp);
void set_filter(ConsiderFilter@ filter);
//Consider all systems we currently have planets in
Object@ OwnedSystems(const ConsiderHook& hook, uint limit = uint(-1));
//Consider all systems on our empire borders
Object@ BorderSystems(const ConsiderHook& hook);
//Consider all systems we know other empires have planets in
Object@ OtherSystems(const ConsiderHook& hook);
//Consider all our fleets
Object@ Fleets(const ConsiderHook& hook);
//Consider planets we own that are important in some way
Object@ ImportantPlanets(const ConsiderHook& hook);
//Consider all our planets
Object@ AllPlanets(const ConsiderHook& hook);
//Consider a random selection of our planets
Object@ SomePlanets(const ConsiderHook& hook, uint count = 5, bool alwaysImportant = true);
//Consider any planets we're using as factories to build things
Object@ FactoryPlanets(const ConsiderHook& hook);
//Consider import requests that could be satisfied by the specified resource type
Object@ MatchingImportRequests(const ConsiderHook& hook, const ResourceType@ type, bool considerExisting);
//Time since the last colonization of theh import request we're currently considering
double timeSinceMatchingColonize();
};
interface ConsiderHook {
double consider(Considerer& cons, Object@ object) const;
};
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
import hooks;
import orbitals;
import ai.consider;
interface AIOrbitals : ConsiderComponent {
Empire@ get_empire();
Considerer@ get_consider();
void registerUse(OrbitalUse use, const OrbitalModule& type);
};
enum OrbitalUse {
OU_Shipyard,
};
const array<string> OrbitalUseName = {
"Shipyard",
};
class OrbitalAIHook : Hook, ConsiderHook {
double consider(Considerer& cons, Object@ obj) const {
return 0.0;
}
void register(AIOrbitals& orbitals, const OrbitalModule& type) const {
}
//Return a system or a planet to build this orbital in/around
Object@ considerBuild(AIOrbitals& orbitals, const OrbitalModule& type) const {
return null;
}
};
class RegisterForUse : OrbitalAIHook {
Document doc("Register this orbital for a particular use. Only one orbital can be used for a specific specialized use.");
Argument use(AT_Custom, doc="Specialized usage for this orbital.");
void register(AIOrbitals& orbitals, const OrbitalModule& type) const override {
for(uint i = 0, cnt = OrbitalUseName.length; i < cnt; ++i) {
if(OrbitalUseName[i] == use.str) {
orbitals.registerUse(OrbitalUse(i), type);
return;
}
}
}
};
+100
View File
@@ -0,0 +1,100 @@
import hooks;
import resources;
import ai.consider;
interface AIResources : ConsiderComponent {
Empire@ get_empire();
Considerer@ get_consider();
};
class ResourceAI : Hook, ConsiderHook {
double consider(Considerer& cons, Object@ obj) const {
return 1.0;
}
//If the AI is not currently using this resource for anything
//that explicitly requested it, this hook determines where it will
//be distributed to in the meantime. Returning null means it will not be
//placed anywhere.
Object@ distribute(AIResources& ai, const ResourceType& type, Object@ current) const {
return null;
}
};
class DistributeToImportantPlanet : ResourceAI {
Document doc("This resource goes to important planets to make them better.");
#section server
double consider(Considerer& cons, Object@ obj) const {
return 1.0 + obj.level;
}
Object@ distribute(AIResources& ai, const ResourceType& type, Object@ current) const {
if(current !is null)
return current;
return ai.consider.ImportantPlanets(this);
}
#section all
};
class DistributeToLaborUsing : ResourceAI {
Document doc("This resource gets distributed to planets building things with labor.");
Argument remove_idle(AT_Boolean, "True", doc="Remove the resource again when the target goes idle.");
#section server
double consider(Considerer& cons, Object@ obj) const {
if(obj.constructionCount == 0)
return 0.0;
return 1.0;
}
Object@ distribute(AIResources& ai, const ResourceType& type, Object@ current) const {
if(current !is null) {
if(!remove_idle.boolean || current.constructionCount != 0)
return current;
}
return ai.consider.FactoryPlanets(this);
}
#section all
};
class DistributeAsLocalPressureBoost : ResourceAI {
Document doc("This resource gets distributed to boost the native pressure of a resource.");
Argument amount(AT_Integer, doc="Amount of pressure this boosts by.");
#section server
double consider(Considerer& cons, Object@ obj) const {
auto@ resource = getResource(obj.primaryResourceType);
if(resource is null)
return 0.0;
if(resource.totalPressure <= 0)
return 0.0;
bool havePressure = obj.owner.HasPressure != 0.0;
if(havePressure) {
int presCap = obj.pressureCap;
int presUse = obj.totalPressure;
if(presUse + amount.integer <= presCap)
return 1.0;
return 0.0;
}
else {
return 1.0;
}
}
Object@ distribute(AIResources& ai, const ResourceType& type, Object@ current) const {
if(current !is null) {
int presCap = current.pressureCap;
int presUse = current.totalPressure;
if(presUse <= presCap)
return current;
}
Object@ check = ai.consider.SomePlanets(this);
if(check !is null)
return check;
else
return current;
}
#section all
};
+462
View File
@@ -0,0 +1,462 @@
#priority init 2000
import hooks;
import saving;
export AnomalyType, AnomalyOption, AnomalyState;
export getAnomalyType, getAnomalyTypeCount;
export getDistributedAnomalyType;
export Targets;
tidy final class AnomalyOption {
uint id = 0;
Sprite icon;
string ident, desc;
string blurb;
bool isSafe = true;
double chance = 1.0;
array<IAnomalyHook@> hooks;
array<AnomalyResult@> results;
double resultTotal = 0.0;
Targets targets;
bool checkTargets(Empire@ emp, const Targets@ check) const {
if(check is null) {
if(targets.targets.length == 0)
return true;
else
return false;
}
if(check.targets.length != targets.targets.length)
return false;
for(uint i = 0, cnt = check.targets.length; i < cnt; ++i) {
if(!isValidTarget(emp, i, check.targets[i]))
return false;
}
return true;
}
bool isValidTarget(Empire@ emp, uint index, const Target@ targ) const {
if(index >= targets.targets.length)
return false;
if(targ.type != targets.targets[index].type)
return false;
if(!targ.filled)
return false;
if(targets.targets[index].filled && targets.targets[index] != targ)
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].isValidTarget(emp, index, targ))
return false;
}
return true;
}
#section server
void choose(Anomaly@ anomaly, Empire@ emp, Targets@ targets) const {
if(!checkTargets(emp, targets))
return;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].choose(anomaly, emp, targets);
double roll = randomd(0.0, resultTotal);
for(uint i = 0, cnt = results.length; i < cnt; ++i) {
if(roll <= results[i].chance) {
results[i].choose(anomaly, emp, targets);
break;
}
roll -= results[i].chance;
}
}
bool giveOption(Anomaly@ anomaly, Empire@ emp) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].giveOption(anomaly, emp))
return false;
}
return true;
}
#section all
};
tidy class AnomalyResult {
double chance = 1.0;
array<IAnomalyHook@> hooks;
void choose(Anomaly@ anomaly, Empire@ emp, Targets@ targets) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].choose(anomaly, emp, targets);
}
};
interface IAnomalyHook {
void init(AnomalyType@ type);
void choose(Anomaly@ obj, Empire@ emp, Targets@ targets) const;
bool giveOption(Anomaly@ obj, Empire@ emp) const;
bool isValidTarget(Empire@ emp, uint index, const Target@ targ) const;
};
tidy class AnomalyHook : Hook, IAnomalyHook {
void init(AnomalyType@ type) {}
void choose(Anomaly@ obj, Empire@ emp, Targets@ targets) const {}
bool giveOption(Anomaly@ obj, Empire@ emp) const { return true; }
bool isValidTarget(Empire@ emp, uint index, const Target@ targ) const { return true; }
};
tidy class AnomalyType {
uint id = 0;
string ident, name = locale::ANOMALY, desc, narrative;
string modelName = "Debris", matName = "Asteroid";
double frequency = 1.0;
double scanTime = 60.0;
bool unique = false;
double stateTotal = 0.0;
array<AnomalyState@> states;
array<AnomalyOption@> options;
const AnomalyState@ getState() const {
if(states.length == 0)
return null;
double value = randomd(0.0, stateTotal);
for(uint i = 0, cnt = states.length; i < cnt; ++i) {
if(value <= states[i].frequency)
return states[i];
value -= states[i].frequency;
}
return states[states.length-1];
}
const AnomalyOption@ getOption(const string& ident) const {
for(uint i = 0, cnt = options.length; i < cnt; ++i) {
if(options[i].ident == ident)
return options[i];
}
return null;
}
const AnomalyState@ getState(const string& ident) const {
for(uint i = 0, cnt = states.length; i < cnt; ++i) {
if(states[i].ident == ident)
return states[i];
}
return null;
}
};
tidy class AnomalyState {
uint id = 0;
string ident;
string narrative;
string modelName = "Debris", matName = "Asteroid";
array<const AnomalyOption@> options;
array<double> option_chances;
array<string> def_options;
double frequency = 1.0;
};
void parseLine(string& line, AnomalyType@ anomaly, AnomalyResult@ result, ReadFile@ file) {
//Try to find the design
if(line.findFirst("(") == -1) {
error("Invalid line during " + anomaly.ident+": "+escape(line));
}
else {
if(anomaly.options.length == 0) {
error("Missing 'Pickup:' line for: "+escape(line));
return;
}
//Hook line
auto@ hook = cast<IAnomalyHook>(parseHook(line, "anomaly_effects::", instantiate=false, file=file));
if(hook !is null) {
if(result !is null)
result.hooks.insertLast(hook);
else
anomaly.options[anomaly.options.length-1].hooks.insertLast(hook);
}
}
}
void loadAnomaly(const string& filename) {
ReadFile file(filename, true);
string key, value;
AnomalyType@ anomaly;
AnomalyOption@ opt;
AnomalyState@ state;
AnomalyResult@ result;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
if(anomaly is null) {
error("Missing 'Anomaly: ID' line in " + filename);
continue;
}
if(opt is null) {
error("Missing 'Option: ID' line in " + filename);
continue;
}
string line = file.line;
parseLine(line, anomaly, result, file);
}
else if(key == "Anomaly") {
if(anomaly !is null)
addAnomalyType(anomaly);
@state = null;
@opt = null;
@result = null;
@anomaly = AnomalyType();
anomaly.ident = value;
if(anomaly.ident.length == 0)
anomaly.ident = filename+"__"+index;
@opt = null;
++index;
}
else if(anomaly is null) {
error("Missing 'Anomaly: ID' line in " + filename);
}
else if(key == "Name") {
anomaly.name = localize(value);
}
else if(key == "Scan Time") {
anomaly.scanTime = toDouble(value);
}
else if(key == "Unique") {
anomaly.unique = toBool(value);
}
else if(key == "Model") {
if(state !is null)
state.modelName = value;
else
anomaly.modelName = value;
}
else if(key == "Material") {
if(state !is null)
state.matName = value;
else
anomaly.matName = value;
}
else if(key == "Description") {
if(anomaly.desc.length == 0)
anomaly.desc = localize(value);
else if(opt !is null)
opt.desc = localize(value);
else
error("Duplicate Description for " + anomaly.ident + ". Missing Option line?");
}
else if(key == "Blurb") {
if(opt !is null)
opt.blurb = localize(value);
}
else if(key == "Narrative") {
if(state !is null)
state.narrative = localize(value);
else
anomaly.narrative = localize(value);
}
else if(key == "Frequency") {
if(state !is null)
state.frequency = toDouble(value);
else
anomaly.frequency = toDouble(value);
}
else if(key == "Icon") {
if(opt !is null)
opt.icon = getSprite(value);
else
file.error("Icon outside option block.");
}
else if(key == "Option") {
@state = null;
@result = null;
@opt = AnomalyOption();
opt.id = anomaly.options.length;
opt.ident = value;
if(opt.ident.length == 0)
opt.ident = anomaly.ident+"__opt__"+anomaly.options.length;
anomaly.options.insertLast(opt);
}
else if(key == "Safe") {
if(opt !is null)
opt.isSafe = toBool(value);
}
else if(key == "State") {
@opt = null;
@result = null;
@state = AnomalyState();
state.id = anomaly.states.length;
state.ident = value;
state.modelName = anomaly.modelName;
state.matName = anomaly.matName;
if(state.ident.length == 0)
state.ident = anomaly.ident+"__state__"+anomaly.states.length;
anomaly.states.insertLast(state);
}
else if(key == "Result") {
if(opt is null) {
file.error("Result outside option block.");
continue;
}
@state = null;
@result = AnomalyResult();
if(value.length == 0)
result.chance = 1.0;
else
result.chance = toDouble(value);
opt.resultTotal += result.chance;
opt.results.insertLast(result);
}
else if(key == "Chance") {
if(opt is null) {
file.error("Chance outside option block.");
continue;
}
double chance = 0.0;
if(value.findFirst("%") == -1)
chance = toDouble(value);
else
chance = toDouble(value) / 100.0;
opt.chance = chance;
}
else if(key == "Choice") {
if(state is null) {
file.error("Choice outside state block.");
continue;
}
int pos = value.findFirst("=");
if(pos == -1) {
state.def_options.insertLast(value);
state.option_chances.insertLast(1.0);
}
else {
state.def_options.insertLast(value.substr(0, pos).trimmed());
state.option_chances.insertLast(toDouble(value.substr(pos+1)) / 100.0);
}
}
else if(file.key == "Target") {
if(opt is null) {
file.error("Target outside option block.");
continue;
}
parseTarget(opt.targets, file.value);
}
else {
string line = file.line;
parseLine(line, anomaly, result, file);
}
}
if(anomaly !is null)
addAnomalyType(anomaly);
}
void preInit() {
//Load anomaly types
FileList list("data/anomalies", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadAnomaly(list.path[i]);
}
void init() {
auto@ list = anomalyTypes;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ type = list[i];
type.stateTotal = 0;
for(uint o = 0, ocnt = type.options.length; o < ocnt; ++o) {
auto@ opt = type.options[o];
for(uint n = 0, ncnt = opt.hooks.length; n < ncnt; ++n) {
if(!cast<Hook>(opt.hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(opt.hooks[n])+" in "+type.ident);
cast<Hook>(opt.hooks[n]).initTargets(opt.targets);
opt.hooks[n].init(type);
}
for(uint n = 0, ncnt = opt.results.length; n < ncnt; ++n) {
auto@ res = opt.results[n];
for(uint j = 0, jcnt = res.hooks.length; j < jcnt; ++j) {
if(!cast<Hook>(res.hooks[j]).instantiate())
error("Could not instantiate hook: "+addrstr(res.hooks[j])+" in "+type.ident);
cast<Hook>(res.hooks[j]).initTargets(opt.targets);
res.hooks[j].init(type);
}
}
}
for(uint o = 0, ocnt = type.states.length; o < ocnt; ++o) {
auto@ state = type.states[o];
type.stateTotal += state.frequency;
for(uint n = 0, ncnt = state.def_options.length; n < ncnt; ++n) {
auto@ opt = type.getOption(state.def_options[n]);
if(opt !is null)
state.options.insertLast(opt);
else
error("Could not find option: "+state.def_options[n]);
}
}
}
}
AnomalyType@[] anomalyTypes;
dictionary idents;
double totalFrequency = 0;
const AnomalyType@ getAnomalyType(uint id) {
if(id >= anomalyTypes.length)
return null;
return anomalyTypes[id];
}
const AnomalyType@ getAnomalyType(const string& ident) {
AnomalyType@ anomaly;
if(idents.get(ident, @anomaly))
return anomaly;
return null;
}
uint getAnomalyTypeCount() {
return anomalyTypes.length;
}
const AnomalyType@ getDistributedAnomalyType() {
uint count = anomalyTypes.length;
double num = randomd(0, totalFrequency);
for(uint i = 0, cnt = anomalyTypes.length; i < cnt; ++i) {
AnomalyType@ type = anomalyTypes[i];
double freq = type.frequency;
if(num <= freq) {
if(type.unique) {
totalFrequency -= type.frequency;
type.frequency = 0;
}
return type;
}
num -= freq;
}
return anomalyTypes[anomalyTypes.length-1];
}
void addAnomalyType(AnomalyType@ type) {
type.id = anomalyTypes.length;
anomalyTypes.insertLast(type);
idents.set(type.ident, @type);
totalFrequency += type.frequency;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = anomalyTypes.length; i < cnt; ++i) {
auto type = anomalyTypes[i];
file.addIdentifier(SI_AnomalyType, type.id, type.ident);
}
}
+52
View File
@@ -0,0 +1,52 @@
import hooks;
import anomalies;
import research;
from anomalies import IAnomalyHook, AnomalyHook;
import bonus_effects;
import target_filters;
class ProgressToState : AnomalyHook {
Document doc("Progresses the anomaly to a specified state.");
Argument goal("State", AT_Custom, doc="ID of the target state.");
const AnomalyState@ state;
#section server
void init(AnomalyType@ type) override {
@state = type.getState(goal.str);
if(state is null)
error("ProgressState(): Could not find state "+goal.str);
}
void choose(Anomaly@ obj, Empire@ emp, Targets@ targets) const override {
if(state !is null)
obj.progressToState(state.id);
}
#section all
};
//Trigger(<Object>, <Hook>(...))
// Run <Hook> as a single-time effect hook on <Planet>.
class Trigger : AnomalyHook {
Document doc("Runs another type of hook on the target when the activated.");
Argument planet(TT_Object);
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::"));
if(hook is null) {
error("BonusEffect(): could not find inner hook: "+escape(hookID.str));
return false;
}
return AnomalyHook::instantiate();
}
#section server
void choose(Anomaly@ obj, Empire@ emp, Targets@ targets) const override {
auto@ objTarg = arguments[0].fromTarget(targets);
if(objTarg is null || objTarg.obj is null)
return;
hook.activate(objTarg.obj, emp);
}
#section all
};
+304
View File
@@ -0,0 +1,304 @@
#priority init 2000
import abilities;
import saving;
import hooks;
export ArtifactType;
export getArtifactType, getArtifactTypeCount;
export getDistributedArtifactType;
export getSeedArtifactType;
tidy final class ArtifactType {
uint id = 0;
string ident;
string name;
string description;
Sprite icon = Sprite(spritesheet::ArtifactIcon, 0);
Sprite strategicIcon = Sprite(spritesheet::ArtifactIcon, 0);
double iconSize = 0.02;
double frequency = 1.0;
double timeFrequency = 0.0;
double mass = 300.0;
bool singleUse = true;
bool orbit = false;
bool unique = false;
bool natural = false;
bool collapses = true;
bool canDonate = true;
bool canOwn = true;
string spreadVariable;
double requireContestation = -INFINITY;
const Model@ model = model::Artifact;
const Material@ material = material::VolkurGenericPBR;
double physicalSize = 5.0;
array<string> ability_defs;
array<const AbilityType@> abilities;
array<Hook@> ai;
array<Hook@> secondaryAI;
double secondaryChance = 0.0;
array<string> tags;
bool hasTag(const string& tag) const {
for(uint i = 0, cnt = tags.length; i < cnt; ++i) {
if(tags[i] == tag)
return true;
}
return false;
}
};
array<ArtifactType@> artifacts;
dictionary artifactIdents;
double totalFrequency = 1.0;
int getArtifactID(const string& ident) {
ArtifactType@ type;
artifactIdents.get(ident, @type);
if(type !is null)
return int(type.id);
return -1;
}
string getArtifactIdent(int id) {
if(id < 0 || id >= int(artifacts.length))
return "-";
return artifacts[id].ident;
}
uint getArtifactTypeCount() {
return artifacts.length;
}
const ArtifactType@ getArtifactType(uint id) {
if(id < artifacts.length)
return artifacts[id];
else
return null;
}
const ArtifactType@ getArtifactType(const string& name) {
ArtifactType@ abl;
artifactIdents.get(name, @abl);
return abl;
}
void addArtifactType(ArtifactType@ abl) {
abl.id = artifacts.length;
artifacts.insertLast(abl);
artifactIdents.set(abl.ident, @abl);
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = artifacts.length; i < cnt; ++i) {
ArtifactType@ type = artifacts[i];
file.addIdentifier(SI_Artifact, type.id, type.ident);
}
}
void loadArtifacts(const string& filename) {
ReadFile file(filename, false);
string key, value;
ArtifactType@ type;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(key.equals_nocase("Artifact")) {
if(type !is null)
addArtifactType(type);
@type = ArtifactType();
type.ident = value;
}
else if(type is null) {
file.error("Missing Artifact ID line");
}
else if(key.equals_nocase("Name")) {
type.name = localize(value);
}
else if(key.equals_nocase("Description")) {
type.description = localize(value);
}
else if(key.equals_nocase("Icon")) {
type.icon = getSprite(value);
}
else if(key.equals_nocase("Tag")) {
type.tags.insertLast(value);
}
else if(key.equals_nocase("Ability")) {
type.ability_defs.insertLast(value);
}
else if(key.equals_nocase("Frequency")) {
type.frequency = toDouble(value);
}
else if(key.equals_nocase("Time Frequency")) {
type.timeFrequency = toDouble(value);
}
else if(key.equals_nocase("Single Use")) {
type.singleUse = toBool(value);
}
else if(key.equals_nocase("Size")) {
type.physicalSize = toDouble(value);
}
else if(key.equals_nocase("Icon Size")) {
type.iconSize = toDouble(value);
}
else if(key.equals_nocase("Strategic Icon")) {
type.strategicIcon = getSprite(value);
}
else if(key.equals_nocase("Model")) {
@type.model = getModel(value);
}
else if(key.equals_nocase("Material")) {
@type.material = getMaterial(value);
}
else if(key.equals_nocase("Orbit")) {
type.orbit = toBool(value);
}
else if(key.equals_nocase("Unique")) {
type.unique = toBool(value);
}
else if(key.equals_nocase("Natural")) {
type.natural = toBool(value);
}
else if(key.equals_nocase("Collapses")) {
type.collapses = toBool(value);
}
else if(key.equals_nocase("Mass")) {
type.mass = toDouble(value);
}
else if(key.equals_nocase("Can Donate")) {
type.canDonate = toBool(value);
}
else if(key.equals_nocase("Can Own")) {
type.canOwn = toBool(value);
}
else if(key.equals_nocase("AI")) {
auto@ hook = parseHook(value, "ai.artifacts::", instantiate=false, file=file);
if(hook !is null)
type.ai.insertLast(hook);
}
else if(key.equals_nocase("Secondary AI")) {
auto@ hook = parseHook(value, "ai.artifacts::", instantiate=false, file=file);
if(hook !is null)
type.secondaryAI.insertLast(hook);
}
else if(key.equals_nocase("Secondary Chance")) {
type.secondaryChance = toDouble(value);
}
else if(key.equals_nocase("Require Contestation")) {
type.requireContestation = toDouble(value);
}
else if(key.equals_nocase("Spread Variable")) {
type.spreadVariable = value;
type.frequency = 0;
type.canDonate = false;
type.canOwn = false;
}
else {
file.error("Invalid line");
}
}
if(type !is null)
addArtifactType(type);
}
ArtifactType@ getRandomArtifactType() {
uint count = artifacts.length;
double num = randomd(0, totalFrequency);
ArtifactType@ type;
for(uint i = 0, cnt = artifacts.length; i < cnt; ++i) {
@type = artifacts[i];
double freq = type.frequency;
if(num <= freq)
break;
num -= freq;
}
if(type is null)
@type = artifacts[artifacts.length-1];
return type;
}
const ArtifactType@ getDistributedArtifactType(bool isUse = true) {
auto@ type = getRandomArtifactType();
if(type.unique && isUse) {
totalFrequency -= type.frequency;
type.frequency = 0;
}
return type;
}
const ArtifactType@ getDistributedArtifactType(double contestation, bool isUse = true) {
uint tries = 0;
ArtifactType@ type;
while(tries < 10) {
@type = getRandomArtifactType();
if(type.requireContestation <= contestation)
break;
tries += 1;
}
if(type.unique && isUse) {
totalFrequency -= type.frequency;
type.frequency = 0;
}
return type;
}
const ArtifactType@ getSeedArtifactType(bool isUse = true) {
double total = 0.0;
for(uint i = 0, cnt = artifacts.length; i < cnt; ++i) {
auto@ type = artifacts[i];
if(type.frequency <= 0 || !type.singleUse || type.natural)
continue;
double freq = type.frequency + type.timeFrequency * (gameTime / 1200.0);
total += freq;
}
double num = randomd(0, total);
ArtifactType@ type;
for(uint i = 0, cnt = artifacts.length; i < cnt; ++i) {
@type = artifacts[i];
if(type.frequency <= 0 || !type.singleUse || type.natural)
continue;
double freq = type.frequency + type.timeFrequency * (gameTime / 1200.0);
if(num <= freq)
break;
num -= freq;
}
if(type is null)
@type = artifacts[artifacts.length-1];
if(type !is null && type.unique && isUse) {
totalFrequency -= type.frequency;
type.frequency = 0;
}
return type;
}
void preInit() {
FileList list("data/artifacts", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadArtifacts(list.path[i]);
}
void init() {
totalFrequency = 0.0;
for(uint i = 0, cnt = artifacts.length; i < cnt; ++i) {
auto@ type = artifacts[i];
totalFrequency += type.frequency;
for(uint j = 0, jcnt = type.ability_defs.length; j < jcnt; ++j) {
auto@ abl = getAbilityType(type.ability_defs[j]);
if(abl !is null)
type.abilities.insertLast(abl);
else
error("Error: could not find ability "+type.ability_defs[j]+" in artifact "+type.ident);
}
for(uint n = 0, ncnt = type.ai.length; n < ncnt; ++n) {
if(!type.ai[n].instantiate())
error("Could not instantiate AI hook: "+addrstr(type.ai[n])+" in artifact "+type.ident);
}
}
}
+207
View File
@@ -0,0 +1,207 @@
import attitudes;
from attitudes import AttitudeHook;
import hooks;
import abilities;
import empire_effects;
import bonus_effects;
import systems;
class ProgressFromAttribute : AttitudeHook {
Document doc("Take the progress value for this attitude from an empire attribute.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument multiply(AT_Decimal, "1.0", doc="Multiplication factor to attitude progress from attribute.");
Argument retroactive(AT_Boolean, "False", doc="If set, count increases in the attribute from the start of the game, instead of from when this attitude was taken.");
Argument monotonic(AT_Boolean, "True", doc="If not set, the attribute progress can be decreased by the attribute going down.");
#section server
void enable(Attitude& att, Empire& emp, any@ data) const {
double offset = 0;
if(!retroactive.boolean)
offset = emp.getAttribute(attribute.integer);
data.store(offset);
}
void tick(Attitude& att, Empire& emp, any@ data, double time) const {
double offset = 0;
data.retrieve(offset);
double next = emp.getAttribute(attribute.integer);
if(next != offset) {
if(!monotonic.boolean || next > offset) {
data.store(next);
att.progress += (next - offset) * multiply.decimal * emp.AttitudeProgressFactor;
}
}
}
void save(any@ data, SaveFile& file) const {
double offset = 0;
data.retrieve(offset);
file << offset;
}
void load(any@ data, SaveFile& file) const {
double offset = 0;
file >> offset;
data.store(offset);
}
#section all
};
class Conflict : AttitudeHook {
Document doc("This attitude can not be taken if a particular other attitude has already been taken.");
Argument attitude(AT_Attitude, doc="Attitude to conflict with.");
bool canTake(Empire& emp) const {
return !emp.hasAttitude(attitude.integer);
}
};
class TiedAbility : AttitudeHook {
Document doc("An ability is tied to this attitude.");
Argument ability(AT_Ability, doc="Ability to create tied to this attitude.");
Ability@ showAbility(Attitude& att, Empire& emp, Ability@ abl) const {
if(abl is null)
@abl = Ability();
if(receive(emp.getAbilityOfType(ability.integer), abl))
return abl;
return null;
}
#section server
void enable(Attitude& att, Empire& emp, any@ data) const {
int id = emp.addAbility(ability.integer);
data.store(id);
}
void disable(Attitude& att, Empire& emp, any@ data) const {
int id = -1;
data.retrieve(id);
emp.removeAbility(id);
}
void save(any@ data, SaveFile& file) const {
int id = -1;
data.retrieve(id);
file << id;
}
void load(any@ data, SaveFile& file) const {
int id = -1;
file >> id;
data.store(id);
}
#section all
};
class ProgressFromEmpirePopulation : AttitudeHook {
Document doc("Take the progress value for this attitude from the empire's total population.");
Argument multiply(AT_Decimal, "1.0", doc="Multiplication factor to attitude progress from attribute.");
Argument monotonic(AT_Boolean, "True", doc="If not set, the attribute progress can be decreased by the attribute going down.");
#section server
void enable(Attitude& att, Empire& emp, any@ data) const {
double offset = 0;
data.store(offset);
}
void tick(Attitude& att, Empire& emp, any@ data, double time) const {
double offset = 0;
data.retrieve(offset);
double next = emp.TotalPopulation;
if(next != offset) {
if(!monotonic.boolean || next > offset) {
data.store(next);
att.progress += (next - offset) * multiply.decimal;
}
}
}
void save(any@ data, SaveFile& file) const {
double offset = 0;
data.retrieve(offset);
file << offset;
}
void load(any@ data, SaveFile& file) const {
double offset = 0;
file >> offset;
data.store(offset);
}
#section all
};
tidy final class ScoutData {
set_int flagged;
array<uint> systems;
};
class ProgressFromScoutedSystems : AttitudeHook {
Document doc("Progress based on the time that you are scouting systems owned by other players.");
#section server
void enable(Attitude& att, Empire& emp, any@ data) const {
ScoutData info;
data.store(@info);
}
void tick(Attitude& att, Empire& emp, any@ data, double time) const {
ScoutData@ info;
data.retrieve(@info);
uint offset = randomi(0, systemCount-1);
for(uint n = 0; n < 10; ++n) {
uint index = (n+offset) % systemCount;
const SystemDesc@ sys = getSystem(index);
bool haveScouted = true;
if(sys.object.PlanetsMask & emp.mask != 0)
haveScouted = false;
else if(sys.object.PlanetsMask & ~(emp.mask | emp.ForcedPeaceMask.value | emp.visionMask) == 0)
haveScouted = false;
else if(sys.object.BasicVisionMask & emp.mask == 0)
haveScouted = false;
bool haveRecorded = info.flagged.contains(sys.index);
if(haveRecorded && !haveScouted) {
info.flagged.erase(sys.index);
info.systems.remove(sys.index);
}
else if(!haveRecorded && haveScouted) {
info.flagged.insert(sys.index);
info.systems.insertLast(sys.index);
}
}
if(info.systems.length != 0)
att.progress += time * double(info.systems.length) / 60.0 * emp.AttitudeProgressFactor;
}
void save(any@ data, SaveFile& file) const {
ScoutData@ info;
data.retrieve(@info);
uint cnt = info.systems.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file << info.systems[i];
}
void load(any@ data, SaveFile& file) const {
ScoutData info;
data.store(@info);
uint cnt = 0;
file >> cnt;
info.systems.length = cnt;
for(uint i = 0; i < cnt; ++i) {
file >> info.systems[i];
info.flagged.insert(info.systems[i]);
}
}
#section all
};
+491
View File
@@ -0,0 +1,491 @@
#priority init 2000
import hooks;
import saving;
import abilities;
export AttitudeLevel, AttitudeType, Attitude;
export getAttitudeID, getAttitudeIdent, getAttitudeType;
export getAttitudeTypeCount;
#section server
from achievements import giveAchievement;
#section all
interface IAttitudeHook {
Ability@ showAbility(Attitude& att, Empire& emp, Ability@ abl) const;
bool canTake(Empire& emp) const;
void enable(Attitude& att, Empire& emp, any@ data) const;
void disable(Attitude& att, Empire& emp, any@ data) const;
void tick(Attitude& att, Empire& emp, any@ data, double time) const;
void save(any@ data, SaveFile& file) const;
void load(any@ data, SaveFile& file) const;
};
class AttitudeHook : Hook, IAttitudeHook {
Ability@ showAbility(Attitude& att, Empire& emp, Ability@ abl) const { return null; }
bool canTake(Empire& emp) const { return true; }
void enable(Attitude& att, Empire& emp, any@ data) const {}
void disable(Attitude& att, Empire& emp, any@ data) const {}
void tick(Attitude& att, Empire& emp, any@ data, double time) const {}
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
};
tidy class AttitudeLevel {
uint level = 0;
Sprite icon;
string description;
double threshold = 0;
array<IAttitudeHook@> hooks;
};
tidy class AttitudeAction {
string name;
string description;
Color color;
Sprite icon;
array<IAttitudeHook@> hooks;
};
tidy class AttitudeType {
uint id;
string ident;
string name;
string description;
string progress;
Color color;
int sort = 0;
array<IAttitudeHook@> hooks;
array<AttitudeLevel@> levels;
bool canTake(Empire& emp) const {
if(emp.hasAttitude(id))
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canTake(emp))
return false;
}
return true;
}
int opCmp(const AttitudeType@ other) const {
if(other is null)
return -1;
if(other.sort < sort)
return 1;
if(other.sort > sort)
return -1;
return 0;
}
};
tidy class Attitude : Serializable, Savable {
const AttitudeType@ type;
double progress = 0.0;
uint level = 0;
array<any> data;
bool delta = true;
int getDiscardCost(Empire& emp) {
return config::ATTITUDE_DISCARD_COST + config::ATTITUDE_DISCARD_LEVEL_COST * level;
}
int get_nextLevel() {
return clamp(level+1, 0, type.levels.length);
}
int get_prevLevel() {
return clamp(int(level)-1, 0, int(type.levels.length));
}
int get_maxLevel() {
return type.levels.length;
}
uint get_allHookCount() {
uint hookCnt = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n < type.levels.length)
hookCnt += type.levels[n].hooks.length;
}
return hookCnt;
}
const IAttitudeHook@ get_allHooks(uint index) {
if(index < type.hooks.length)
return type.hooks[index];
index -= type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n < type.levels.length) {
if(index < type.levels[n].hooks.length)
return type.levels[n].hooks[index];
index -= type.levels[n].hooks.length;
}
}
return null;
}
const AttitudeLevel@ get_levels(uint level) {
if(level == 0)
return null;
return type.levels[clamp(int(level)-1, 0, int(type.levels.length)-1)];
}
void write(Message& msg) {
msg.writeLimited(type.id, getAttitudeTypeCount());
msg << float(progress);
msg.writeSmall(level);
}
void read(Message& msg) {
@type = getAttitudeType(msg.readLimited(getAttitudeTypeCount()));
progress = msg.read_float();
level = msg.readSmall();
}
void save(SaveFile& file) {
file.writeIdentifier(SI_AttitudeType, type.id);
file << progress;
file << level;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].save(data[i], file);
uint h = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n >= type.levels.length)
continue;
for(uint i = 0, cnt = type.levels[n].hooks.length; i < cnt; ++i)
type.levels[n].hooks[i].save(data[h+i], file);
h += type.levels[n].hooks.length;
}
}
void load(SaveFile& file) {
@type = getAttitudeType(file.readIdentifier(SI_AttitudeType));
file >> progress;
file >> level;
uint hookCnt = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n < type.levels.length)
hookCnt += type.levels[n].hooks.length;
}
data.length = hookCnt;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].load(data[i], file);
uint h = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n >= type.levels.length)
continue;
for(uint i = 0, cnt = type.levels[n].hooks.length; i < cnt; ++i)
type.levels[n].hooks[i].load(data[h+i], file);
h += type.levels[n].hooks.length;
}
}
#section server
void start(Empire& emp) {
//Start the attitude in the empire
data.length = type.hooks.length;
level = 0;
progress = 0.0;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].enable(this, emp, data[i]);
}
void tick(Empire& emp, double time) {
double prevProgress = progress;
//Tick all the base hooks
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].tick(this, emp, data[i], time);
//Tick all the levels we currently have
uint h = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n >= type.levels.length)
continue;
for(uint i = 0, cnt = type.levels[n].hooks.length; i < cnt; ++i)
type.levels[n].hooks[i].tick(this, emp, data[h+i], time);
h += type.levels[n].hooks.length;
}
//Make sure we have the appropriate levels according to progress
if(prevProgress != progress) {
checkProgress(emp);
delta = true;
}
}
void checkProgress(Empire& emp) {
uint getLevel = 0;
for(uint i = 0, cnt = type.levels.length; i < cnt; ++i) {
if(type.levels[i].threshold <= progress)
getLevel += 1;
else
break;
}
changeLevel(emp, getLevel);
}
void changeLevel(Empire& emp, uint newLevel) {
if(level == newLevel)
return;
//Disable old levels
uint h = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n >= type.levels.length)
continue;
if(n < newLevel) {
h += type.levels[n].hooks.length;
continue;
}
for(uint i = 0, cnt = type.levels[n].hooks.length; i < cnt; ++i)
type.levels[n].hooks[i].disable(this, emp, data[h+i]);
h += type.levels[n].hooks.length;
}
//Change amount of data we have stored
uint hookCnt = type.hooks.length;
for(uint n = 0; n < newLevel; ++n) {
if(n < type.levels.length)
hookCnt += type.levels[n].hooks.length;
}
data.length = hookCnt;
//Set level
uint prevLevel = level;
level = newLevel;
delta = true;
//Enable new levels
h = type.hooks.length;
for(uint n = 0; n < newLevel; ++n) {
if(n >= type.levels.length)
continue;
if(n < prevLevel) {
h += type.levels[n].hooks.length;
continue;
}
for(uint i = 0, cnt = type.levels[n].hooks.length; i < cnt; ++i)
type.levels[n].hooks[i].enable(this, emp, data[h+i]);
h += type.levels[n].hooks.length;
}
if(level == 5) {
if(emp.getLevelAttitudeCount(5) >= 3)
giveAchievement(emp, "ACH_ATTIDS");
}
}
void end(Empire& emp) {
//Disable base hooks
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].disable(this, emp, data[i]);
//Disable any levels we have
uint h = type.hooks.length;
for(uint n = 0; n < level; ++n) {
if(n >= type.levels.length)
continue;
for(uint i = 0, cnt = type.levels[n].hooks.length; i < cnt; ++i)
type.levels[n].hooks[i].disable(this, emp, data[h+i]);
h += type.levels[n].hooks.length;
}
}
#section all
};
array<AttitudeType@> attitudeTypes;
dictionary attitudeIdents;
int getAttitudeID(const string& ident) {
auto@ type = getAttitudeType(ident);
if(type is null)
return -1;
return int(type.id);
}
string getAttitudeIdent(int id) {
auto@ type = getAttitudeType(id);
if(type is null)
return "";
return type.ident;
}
const AttitudeType@ getAttitudeType(uint id) {
if(id >= attitudeTypes.length)
return null;
return attitudeTypes[id];
}
const AttitudeType@ getAttitudeType(const string& ident) {
AttitudeType@ def;
if(attitudeIdents.get(ident, @def))
return def;
return null;
}
uint getAttitudeTypeCount() {
return attitudeTypes.length;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = attitudeTypes.length; i < cnt; ++i) {
auto type = attitudeTypes[i];
file.addIdentifier(SI_AttitudeType, type.id, type.ident);
}
}
void addAttitude(AttitudeType@ type) {
type.id = attitudeTypes.length;
attitudeTypes.insertLast(type);
attitudeIdents.set(type.ident, @type);
}
void parseLine(string& line, AttitudeType@ type, ReadFile@ file) {
auto@ hook = cast<IAttitudeHook>(parseHook(line, "attitude_effects::", instantiate=false, file=file));
if(hook !is null)
type.hooks.insertLast(hook);
}
void loadAttitudes(const string& filename) {
ReadFile file(filename, true);
while(true) {
if(file.key.equals_nocase("Attitude")) {
if(!loadAttitude(file))
break;
}
else {
if(!file++)
break;
}
}
}
bool loadAttitude(ReadFile@ file) {
AttitudeType att;
att.ident = file.value;
addAttitude(att);
int blockIndent = file.indent;
if(!file++)
return false;
while(true) {
if(file.indent <= blockIndent)
return true;
if(file.fullLine) {
auto@ hook = cast<IAttitudeHook>(parseHook(file.line, "attitude_effects::", instantiate=false));
if(hook !is null)
att.hooks.insertLast(hook);
if(!file++)
return false;
if(file.indent <= blockIndent)
return true;
}
else if(file.key.equals_nocase("Level")) {
if(!loadLevel(att, file))
return false;
}
else {
if(file.key.equals_nocase("Name")) {
att.name = localize(file.value);
}
else if(file.key.equals_nocase("Description")) {
att.description = localize(file.value);
}
else if(file.key.equals_nocase("Progress")) {
att.progress = localize(file.value);
}
else if(file.key.equals_nocase("Color")) {
att.color = toColor(file.value);
}
else if(file.key.equals_nocase("Sort")) {
att.sort = toInt(file.value);
}
else {
auto@ hook = cast<IAttitudeHook>(parseHook(file.line, "attitude_effects::", instantiate=false));
if(hook !is null)
att.hooks.insertLast(hook);
}
if(!file++)
return false;
}
}
return true;
}
bool loadLevel(AttitudeType@ att, ReadFile@ file) {
AttitudeLevel lv;
lv.level = att.levels.length;
att.levels.insertLast(lv);
int blockIndent = file.indent;
if(!file++)
return false;
while(true) {
if(file.indent <= blockIndent)
return true;
if(file.fullLine) {
auto@ hook = cast<IAttitudeHook>(parseHook(file.line, "attitude_effects::", instantiate=false));
if(hook !is null)
lv.hooks.insertLast(hook);
if(!file++)
return false;
}
else {
if(file.key.equals_nocase("Description")) {
lv.description = localize(file.value);
}
else if(file.key.equals_nocase("Threshold")) {
lv.threshold = toDouble(file.value);
}
else if(file.key.equals_nocase("Icon")) {
lv.icon = getSprite(file.value);
}
else {
auto@ hook = cast<IAttitudeHook>(parseHook(file.line, "attitude_effects::", instantiate=false));
if(hook !is null)
lv.hooks.insertLast(hook);
}
if(!file++)
return false;
}
}
return true;
}
void preInit() {
FileList list("data/attitudes", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadAttitudes(list.path[i]);
}
void init() {
auto@ list = attitudeTypes;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ type = list[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n)
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(type.hooks[n])+" in "+type.ident);
for(uint j = 0, jcnt = type.levels.length; j < jcnt; ++j) {
for(uint n = 0, ncnt = type.levels[j].hooks.length; n < ncnt; ++n)
if(!cast<Hook>(type.levels[j].hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(type.levels[j].hooks[n])+" in "+type.ident+" level "+j);
}
}
}
+70
View File
@@ -0,0 +1,70 @@
import saving;
enum AttributeComp {
AC_Add,
AC_AddBase,
AC_AddFactor,
AC_Multiply,
AC_INVALID
};
AttributeComp getAttributeMode(const string& str) {
if(str.equals_nocase("add"))
return AC_Add;
if(str.equals_nocase("addbase"))
return AC_AddBase;
if(str.equals_nocase("addfactor"))
return AC_AddFactor;
if(str.equals_nocase("multiply"))
return AC_Multiply;
return AC_INVALID;
}
string getAttributeModeIdent(int id) {
switch(id) {
case AC_Add: return "Add";
case AC_AddBase: return "AddBase";
case AC_AddFactor: return "AddFactor";
case AC_Multiply: return "Multiply";
}
return "Invalid";
}
//Attributes are computed as:
// attrib = ((Base + AddBase) * (1 + AddFactor) + Add) * Multiply
// Modifies for anything but Multiply is additive, Multiply is multiplicative.
array<string> dynAttributes;
dictionary attribIdents;
uint getEmpAttributeCount() {
return dynAttributes.length + EA_COUNT;
}
int getEmpAttribute(const string& ident, bool create = true) {
int id = ::getEmpireAttribute(ident);
if(id != -1)
return id;
if(!attribIdents.get(ident, id) && create) {
id = int(dynAttributes.length) + EA_COUNT;
dynAttributes.insertLast(ident);
attribIdents.set(ident, id);
}
return id;
}
string getEmpAttributeIdent(int id) {
if(id < EA_COUNT)
return getEmpireAttributeName(id);
if(uint(id - EA_COUNT) >= dynAttributes.length)
return "";
return dynAttributes[id - EA_COUNT];
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0; i < EA_COUNT; ++i)
file.addIdentifier(SI_EmpAttribute, int(i), getEmpireAttributeName(i));
for(uint i = 0, cnt = dynAttributes.length; i < cnt; ++i)
file.addIdentifier(SI_EmpAttribute, int(EA_COUNT + i), dynAttributes[i]);
}
+128
View File
@@ -0,0 +1,128 @@
#priority init 2010
import resources;
from saving import SaveIdentifier;
final class Biome {
uint8 id = 0;
string ident;
string name;
string description;
Color color;
Sprite tile;
uint frequency = 1;
float useWeight = 1.f;
float buildCost = 1.f, buildTime = 1.f;
//Temp and humidity range from 0 to 1 (lowest to highest)
float temp = 0.5f, humidity = 0.5f;
bool isCrystallic = false;
bool isVoid = false;
bool buildable = true;
bool isWater = false;
bool isMoon = false;
vec4f picks(0.f, 0.f, 0.f, -0.025f);
vec2f lookupRange(0.f, 0.f);
};
final class ColonizationOrder : Serializable, Savable {
Object@ target;
double targetPopulation;
double inTransit;
double totalSent;
ColonizationOrder() {
targetPopulation = 1.0;
inTransit = 0.0;
totalSent = 0.0;
}
void save(SaveFile& msg) {
msg << target;
msg << targetPopulation;
msg << inTransit;
msg << totalSent;
}
void load(SaveFile& msg) {
msg >> target;
msg >> targetPopulation;
msg >> inTransit;
if(msg >= SV_0148)
msg >> totalSent;
}
void write(Message& msg) {
msg << target;
msg << targetPopulation;
msg << inTransit;
}
void read(Message& msg) {
msg >> target;
msg >> targetPopulation;
msg >> inTransit;
}
};
namespace biomes {
::array<::Biome@> biomes;
::dictionary biomeIdents;
::uint totalFrequency = 0;
};
uint getBiomeCount() {
return biomes::biomes.length;
}
const Biome@ getBiome(uint id) {
if(id < biomes::biomes.length)
return biomes::biomes[id];
else
return null;
}
int getBiomeID(const string& ident) {
auto@ type = getBiome(ident);
if(type is null)
return -1;
return int(type.id);
}
string getBiomeIdent(int id) {
auto@ type = getBiome(id);
if(type is null)
return "";
return type.ident;
}
const Biome@ getBiome(const string& name) {
Biome@ b;
biomes::biomeIdents.get(name, @b);
return b;
}
const Biome@ getDistributedBiome() {
uint num = randomi(1, biomes::totalFrequency);
for(uint i = 0, cnt = biomes::biomes.length; i < cnt; ++i) {
if(num <= biomes::biomes[i].frequency)
return biomes::biomes[i];
num -= biomes::biomes[i].frequency;
}
return biomes::biomes[0];
}
void addBiome(Biome@ biome) {
biome.id = biomes::biomes.length;
biomes::biomes.insertLast(biome);
biomes::biomeIdents.set(biome.ident, @biome);
biomes::totalFrequency += biome.frequency;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = biomes::biomes.length; i < cnt; ++i) {
Biome@ type = biomes::biomes[i];
file.addIdentifier(SI_Biome, type.id, type.ident);
}
}
+145
View File
@@ -0,0 +1,145 @@
from map_systems import IMapHook;
import hooks;
import settings.map_lib;
class BlockEffect : BlockHook, IMapHook {
//For use in maps
bool prepare(Argument@& arg, SystemData@ data, SystemDesc@ system, Object@& current) const{
return true;
}
void trigger(SystemData@ data, SystemDesc@ system, Object@& current) const override {
Argument@ arg;
if(!prepare(arg) || !prepare(arg, data, system, current))
return;
Hook@ hook;
uint num = 0;
while(feed(arg, hook, num)) {
auto@ cur = cast<IMapHook@>(hook);
if(cur !is null)
cur.trigger(data, system, current);
}
}
void postTrigger(SystemData@ data, SystemDesc@ system, Object@& current) const override {
Argument@ arg;
if(!prepare(arg) || !prepare(arg, data, system, current))
return;
Hook@ hook;
uint num = 0;
while(feed(arg, hook, num)) {
auto@ cur = cast<IMapHook@>(hook);
if(cur !is null)
cur.postTrigger(data, system, current);
}
}
};
class Repeat : BlockEffect {
Argument count(AT_Range);
bool prepare(Argument@& dat) const override {
@dat = Argument();
if(count.isRange)
dat.integer = randomi(int(count.decimal), int(count.decimal2));
else
dat.integer = int(count.decimal);
return true;
}
bool feed(Argument@& dat, Hook@& hook, uint& num) const override {
if(num >= inner.length * uint(dat.integer))
return false;
@hook = inner[num % inner.length];
num += 1;
return true;
}
};
class RepeatModified : Repeat {
Argument mod(AT_Range);
Argument minimum(AT_Integer, "1");
Argument maximum(AT_Integer, "99999999");
bool prepare(Argument@& dat) const override {
@dat = Argument();
dat.integer = clamp(int(round(count.fromRange() * mod.fromRange())), minimum.integer, maximum.integer);
return true;
}
};
class RepeatChance : BlockEffect {
RepeatChance() {
argument("Chance", AT_Range);
argument("Repeat Modifier", AT_Range, "1.0");
}
bool prepare(Argument@& dat) const override {
@dat = Argument();
dat.decimal = arguments[0].fromRange();
dat.decimal2 = arguments[1].fromRange();
return true;
}
bool feed(Argument@& dat, Hook@& hook, uint& num) const override {
uint index = num % inner.length;
if(index == 0) {
uint repeats = num / inner.length;
double chance = dat.decimal * pow(dat.decimal2, repeats);
if(randomd() > chance)
return false;
}
@hook = inner[index];
num += 1;
return true;
}
};
class RepeatQuality : BlockEffect {
RepeatQuality() {
argument("Chance", AT_Range);
argument("Repeat Modifier", AT_Range, "1.0");
argument("Quality Step", AT_Range);
}
bool prepare(Argument@& dat) const override {
@dat = Argument();
dat.decimal = arguments[0].fromRange();
dat.decimal2 = arguments[1].fromRange();
dat.integer = 0;
return true;
}
bool prepare(Argument@& dat, SystemData@ data, SystemDesc@ system, Object@& current) const{
dat.integer = floor(double(data.quality) / arguments[2].fromRange());
return true;
}
bool feed(Argument@& dat, Hook@& hook, uint& num) const override {
uint index = num % inner.length;
if(index == 0) {
uint repeats = num / inner.length;
double chance = dat.decimal * pow(dat.decimal2, repeats);
bool gotten = false;
do {
if(randomd() <= chance) {
gotten = true;
break;
}
else {
dat.integer -= 1;
}
}
while(dat.integer >= 0);
if(!gotten)
return false;
}
@hook = inner[index];
num += 1;
return true;
}
};
File diff suppressed because it is too large Load Diff
+293
View File
@@ -0,0 +1,293 @@
import buildings;
from buildings import BuildingHook;
from bonus_effects import BonusEffect;
import planet_effects;
import listed_values;
import requirement_effects;
import consume_effects;
tidy final class TriggerStartConstruction : BuildingHook {
Document doc("Triggers another hook when construction of a building starts.");
Argument hook("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ eff;
bool instantiate() override {
@eff = cast<BonusEffect>(parseHook(hook.str, "bonus_effects::", required=false));
if(eff is null) {
error("TriggerStartConstruction(): could not find inner hook: "+escape(hook.str));
return false;
}
return BuildingHook::instantiate();
}
#section server
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {
if(eff !is null)
eff.activate(obj, obj.owner);
}
#section all
};
tidy final class TriggerCancelConstruction : BuildingHook {
Document doc("Triggers another hook when construction of a building is cancelled.");
Argument hook("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ eff;
bool instantiate() override {
@eff = cast<BonusEffect>(parseHook(hook.str, "bonus_effects::", required=false));
if(eff is null) {
error("TriggerCancelConstruction(): could not find inner hook: "+escape(hook.str));
return false;
}
return BuildingHook::instantiate();
}
#section server
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {
if(eff !is null)
eff.activate(obj, obj.owner);
}
#section all
};
tidy final class TriggerConstructed : BuildingHook {
Document doc("Triggers another hook when construction of a building is finished.");
Argument hook("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ eff;
bool instantiate() override {
@eff = cast<BonusEffect>(parseHook(hook.str, "bonus_effects::", required=false));
if(eff is null) {
error("TriggerConstructed(): could not find inner hook: "+escape(hook.str));
return false;
}
return BuildingHook::instantiate();
}
#section server
void complete(Object& obj, SurfaceBuilding@ bld) const {
if(eff !is null)
eff.activate(obj, obj.owner);
}
#section all
};
class ConstructibleIfAttributeGTE : BuildingHook {
Document doc("Only constructible if an empire attribute is greater than or equal to the specified value.");
Argument attribute("Attribute", AT_EmpAttribute, doc="Attribute to test, can be set to any arbitrary name to be created as a new attribute with starting value 0.");
Argument value("Value", AT_Decimal, doc="Value to test against.");
bool canBuildOn(Object& obj, bool ignoreState = false) const override {
Empire@ emp = obj.owner;
if(emp is null)
return false;
if(emp.getAttribute(attribute.integer) < value.decimal)
return false;
return true;
}
};
class ConstructibleIfAttribute : BuildingHook {
Document doc("Only constructible if an empire attribute is equal to the specified value.");
Argument attribute("Attribute", AT_EmpAttribute, doc="Attribute to test, can be set to any arbitrary name to be created as a new attribute with starting value 0.");
Argument value("Value", AT_Decimal, doc="Value to test against.");
bool canBuildOn(Object& obj, bool ignoreState = false) const override {
Empire@ emp = obj.owner;
if(emp is null)
return false;
if(abs(emp.getAttribute(attribute.integer) - value.decimal) >= 0.001)
return false;
return true;
}
};
class CannotBuildManually : BuildingHook {
Document doc("Indicates that the building cannot be manually constructed.");
bool canBuildOn(Object& obj, bool ignoreState = false) const override {
return false;
}
};
class CannotRemove : BuildingHook {
Document doc("Indicates that the building cannot be removed by the player.");
bool canRemove(Object& obj) const override {
return false;
}
};
class ModBuildSpeedAttribute : BuildingHook {
Document doc("Multiply the build speed of this building by an attribute.");
Argument attribute(AT_EmpAttribute, doc="Attribute to modify build speed by.");
void modBuildTime(Object& obj, double& time) const {
time /= obj.owner.getAttribute(attribute.integer);
}
};
tidy final class ActiveWhenCargoConsumed : GenericEffect {
Document doc("This hook applies while a particular amount of cargo can be consumed every interval.");
Argument cargo_type(AT_Cargo, doc="Type of cargo to consume.");
Argument amount(AT_Decimal, doc="Amount of cargo to consume per interval.");
Argument interval(AT_Decimal, doc="Interval to consume cargo at.");
Argument hookID(AT_Hook, "planet_effects::GenericEffect");
Argument labor_use_linked(AT_Boolean, "False", doc="Don't require the cargo consumption when no labor is currently being used.");
Argument inactive_status(AT_Status, EMPTY_DEFAULT, doc="Status to add when this building is inactive.");
Argument inactive_status_count(AT_Integer, "1", doc="How many statuses to add when this building is inactive.");
GenericEffect@ hook;
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
bool withHook(const string& str) {
@hook = cast<GenericEffect>(parseHook(str, "planet_effects::"));
if(hook is null) {
error("If<>(): could not find inner hook: "+escape(str));
return false;
}
return true;
}
bool condition(Object& obj) const {
return false;
}
#section server
void complete(Object& obj, SurfaceBuilding@ bld) const {
auto@ data = bld.data[hookIndex];
ConsumeData info;
info.enabled = false;
data.store(@info);
bld.disabled = !info.enabled;
bld.delta = true;
if(info.enabled) {
hook.enable(obj, info.data);
}
else if(inactive_status.integer != -1) {
for(int n = 0; n < inactive_status_count.integer; ++n)
obj.addStatus(inactive_status.integer);
}
}
void disable(Object& obj, any@ data) const override {
ConsumeData@ info;
data.retrieve(@info);
if(info.enabled)
hook.disable(obj, info.data);
}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {
auto@ data = bld.data[hookIndex];
ConsumeData@ info;
data.retrieve(@info);
bool cond = info.enabled;
info.timer -= time;
if(info.timer <= 0) {
if(!obj.hasCargo) {
cond = false;
info.timer += interval.decimal;
}
else if(labor_use_linked.boolean && !obj.isUsingLabor) {
cond = obj.getCargoStored(cargo_type.integer) >= amount.decimal;
}
else {
double consAmt = obj.consumeCargo(cargo_type.integer, amount.decimal, partial=false);
if(consAmt < amount.decimal - 0.001) {
cond = false;
info.timer += interval.decimal;
}
else {
cond = true;
info.timer += interval.decimal;
}
}
}
if(cond != info.enabled) {
if(info.enabled)
hook.disable(obj, info.data);
else
hook.enable(obj, info.data);
info.enabled = cond;
bld.disabled = !cond;
bld.delta = true;
if(inactive_status.integer != -1) {
for(int n = 0; n < inactive_status_count.integer; ++n) {
if(bld.disabled)
obj.addStatus(inactive_status.integer);
else
obj.removeStatusInstanceOfType(inactive_status.integer);
}
}
}
if(info.enabled)
hook.tick(obj, info.data, time);
}
void ownerChange(Object& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {
ConsumeData@ info;
data.retrieve(@info);
if(info.enabled)
hook.ownerChange(obj, info.data, prevOwner, newOwner);
}
void regionChange(Object& obj, any@ data, Region@ fromRegion, Region@ toRegion) const {
ConsumeData@ info;
data.retrieve(@info);
if(info.enabled)
hook.regionChange(obj, info.data, fromRegion, toRegion);
}
void save(any@ data, SaveFile& file) const {
ConsumeData@ info;
data.retrieve(@info);
if(info is null) {
bool enabled = false;
file << enabled;
double timer = 0.0;
file << timer;
}
else {
file << info.enabled;
file << info.timer;
if(info.enabled)
hook.save(info.data, file);
}
}
void load(any@ data, SaveFile& file) const {
ConsumeData info;
data.store(@info);
file >> info.enabled;
file >> info.timer;
if(info.enabled)
hook.load(info.data, file);
}
#section all
};
class RequireStatusToProgress : Requirement {
Document doc("Require that a particular status is present for this building to progress construction.");
Argument status(AT_Status, doc="Status type to check for.");
bool canProgress(Object& obj) const override {
if(!obj.hasStatuses)
return false;
return obj.getStatusStackCountAny(status.integer) > 0;
}
};
+690
View File
@@ -0,0 +1,690 @@
#priority init 2000
import tile_resources;
from saving import SaveIdentifier, SaveVersion;
import util.formatting;
import biomes;
import hooks;
export BuildingClass;
export BuildingType;
export SurfaceBuilding;
export getBuildingTypeCount, getBuildingType;
namespace buildings {
::array<::BuildingType@> types;
::dictionary typeIdents;
};
enum BuildingClass {
BC_Building,
BC_Civilian,
BC_City,
};
tidy class BiomeAffinity {
const Biome@ biome;
double factor = 0.0;
string def;
BiomeAffinity(const string& spec) {
int pos = spec.findFirst(" ");
if(pos == -1) {
def = spec;
}
else {
def = spec.substr(0, pos);
factor = toDouble(spec.substr(pos+1));
}
}
void init() {
@biome = getBiome(def);
if(biome is null)
error("Invalid affinity biome: "+def);
}
};
tidy final class BuildingType {
uint id = 0;
string ident;
string name;
string description;
string category;
Sprite sprite;
string upgradesFrom;
const BuildingType@ base;
array<const BuildingType@> upgrades;
array<IBuildingHook@> hooks;
array<Hook@> ai;
array<BiomeAffinity@> buildAffinities;
array<BiomeAffinity@> maintainAffinities;
float hubWeight = 1.f;
BuildingClass cls = BC_Building;
double[] resources = double[](TR_COUNT, 0.f);
float[] saturates = float[](TR_COUNT, 0.f);
double totalResource = 0.f;
float totalSaturate = 0.f;
int pressureCapTaken = 0;
vec2u size(1, 1);
int baseBuildCost = 0;
int tileBuildCost = 0;
int baseMaintainCost = 0;
int tileMaintainCost = 0;
double buildTime = 3.0 * 60.0;
double laborCost = 0;
bool buildInQueue = false;
double getBuildTime(Object& obj) const {
double time = buildTime;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].modBuildTime(obj, time);
return time;
}
string getTooltip(bool showName = true, bool showCost = true, bool showSize = true, bool showAffinity = true, Object@ valueObject = null, bool isOption = false) const {
string tt;
if(showName)
tt += format("[font=Medium][b]$1[/b][/font]\n", name);
tt += format("[vspace=4/][center][img=$1;$2x$3/][/center][vspace=4/]",
getSpriteDesc(sprite), toString(40*size.x,0), toString(40*size.y,0));
tt += description;
string vname, vvalue;
Sprite vicon;
Color color;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(hooks[i].getVariable(valueObject, vicon, vname, vvalue, color, isOption)) {
tt += format("[nl/]\n[img=$1;22][b][color=$4]$2[/color][/b] [offset=120]$3[/offset][/img]",
getSpriteDesc(vicon), vname, vvalue, toString(color));
color = colors::White;
}
}
if(showCost && !civilian) {
tt += "[nl/]\n";
if(showSize && (size.x > 1 || size.y > 1))
tt += format(locale::BLD_TT_SIZE, toString(size.x), toString(size.y))+"\n";
int bld = buildCostEst, mnt = maintainCostEst;
if(bld != 0 || mnt != 0)
tt += format(locale::BLD_TT_COST, formatMoney(bld, mnt));
if(showAffinity) {
for(uint n = 0, ncnt = buildAffinities.length; n < ncnt; ++n) {
auto@ aff = buildAffinities[n];
if(aff.biome is null)
continue;
if(aff.factor > 1)
tt += "[nl/]\n"+format(locale::BLD_TT_AFFINITY_BUILD_NEG, toString((aff.factor-1.0)*100,0)+"%", toString(aff.biome.color), aff.biome.name, getSpriteDesc(icons::Minus));
else
tt += "[nl/]\n"+format(locale::BLD_TT_AFFINITY_BUILD, toString((1.0-aff.factor)*100,0)+"%", toString(aff.biome.color), aff.biome.name, getSpriteDesc(icons::Plus));
}
for(uint n = 0, ncnt = maintainAffinities.length; n < ncnt; ++n) {
auto@ aff = maintainAffinities[n];
if(aff.biome is null)
continue;
if(aff.factor > 1)
tt += "[nl/]\n"+format(locale::BLD_TT_AFFINITY_MAINT_NEG, toString((aff.factor-1.0)*100,0)+"%", toString(aff.biome.color), aff.biome.name, getSpriteDesc(icons::Minus));
else
tt += "[nl/]\n"+format(locale::BLD_TT_AFFINITY_MAINT, toString((1.0-aff.factor)*100,0)+"%", toString(aff.biome.color), aff.biome.name, getSpriteDesc(icons::Plus));
}
if(!civilian && (tileBuildCost != 0 || tileMaintainCost != 0))
tt += "[nl/]\n"+locale::BLD_TT_DEV;
}
}
else {
if(showSize && (size.x > 1 || size.y > 1)) {
tt += "[nl/]\n";
tt += format(locale::BLD_TT_SIZE, toString(size.x), toString(size.y));
}
}
return tt;
}
bool canProgress(Object& obj) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canProgress(obj))
return false;
}
return true;
}
bool consume(Object& obj) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].consume(obj)) {
for(uint j = 0; j < i; ++j)
hooks[j].reverse(obj);
return false;
}
}
return true;
}
void reverseConsume(Object& obj) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].reverse(obj);
}
double getMaintenanceFor(const Biome@ biome) const {
double cost = tileMaintainCost;
for(uint i = 0, cnt = maintainAffinities.length; i < cnt; ++i) {
if(maintainAffinities[i].biome is biome)
cost *= maintainAffinities[i].factor;
}
return cost;
}
bool get_civilian() const {
return cls != BC_Building;
}
bool canBuildOn(Object@ obj, bool ignoreState = false) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canBuildOn(obj, ignoreState))
return false;
}
return true;
}
bool canRemove(Object@ obj) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canRemove(obj))
return false;
}
return true;
}
int get_buildCostEst() const {
return baseBuildCost + size.x * size.y * tileBuildCost;
}
int get_maintainCostEst() const {
return baseMaintainCost + size.x * size.y * tileMaintainCost;
}
vec2u getCenter() const {
vec2u center(floor(float(size.x) / 2.f), floor(float(size.y) / 2.f));
center.x = clamp(center.x, 0, size.x-1);
center.y = clamp(center.y, 0, size.y-1);
return center;
}
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].startConstruction(obj, bld);
}
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].cancelConstruction(obj, bld);
}
void complete(Object& obj, SurfaceBuilding@ bld) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].complete(obj, bld);
}
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].ownerChange(obj, bld, prevOwner, newOwner);
}
void remove(Object& obj, SurfaceBuilding@ bld) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].remove(obj, bld);
}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].tick(obj, bld, time);
}
void save(SurfaceBuilding@ bld, SaveFile& file) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].save(bld, file);
}
void load(SurfaceBuilding@ bld, SaveFile& file) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].load(bld, file);
}
};
interface IBuildingHook {
void initialize(BuildingType@ type, uint index);
void startConstruction(Object& obj, SurfaceBuilding@ bld) const;
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const;
void complete(Object& obj, SurfaceBuilding@ bld) const;
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const;
void remove(Object& obj, SurfaceBuilding@ bld) const;
void tick(Object& obj, SurfaceBuilding@ bld, double time) const;
void save(SurfaceBuilding@ bld, SaveFile& file) const;
void load(SurfaceBuilding@ bld, SaveFile& file) const;
bool canBuildOn(Object& obj, bool ignoreState = false) const;
bool canRemove(Object& obj) const;
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color, bool isOption) const;
bool getCost(Object& obj, string& value, Sprite& icon) const;
bool consume(Object& obj) const;
void reverse(Object& obj) const;
void modBuildTime(Object& obj, double& time) const;
bool canProgress(Object& obj) const;
};
class BuildingHook : Hook, IBuildingHook {
uint hookIndex = 0;
void initialize(BuildingType@ type, uint index) { hookIndex = index; }
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void complete(Object& obj, SurfaceBuilding@ bld) const {}
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const {}
void remove(Object& obj, SurfaceBuilding@ bld) const {}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {}
void save(SurfaceBuilding@ bld, SaveFile& file) const {}
void load(SurfaceBuilding@ bld, SaveFile& file) const {}
bool canBuildOn(Object& obj, bool ignoreState = false) const { return true; }
bool canRemove(Object& obj) const { return true; }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color, bool isOption) const {
return false;
}
bool consume(Object& obj) const { return true; }
void reverse(Object& obj) const {}
bool getCost(Object& obj, string& value, Sprite& icon) const {
return false;
}
void modBuildTime(Object& obj, double& time) const {}
bool canProgress(Object& obj) const { return true; }
};
tidy final class SurfaceBuilding : Serializable, Savable {
vec2u position;
const BuildingType@ type;
float completion = 0.f;
bool disabled = false;
bool upgrading = false;
bool delta = false;
int cost = 0;
int cycle = -1;
Object@ tied;
array<any>@ data;
SurfaceBuilding() {}
SurfaceBuilding(const BuildingType@ Type) {
@type = Type;
if(type.hooks.length > 0)
@data = array<any>(type.hooks.length);
}
void write(Message& msg) {
msg.writeSmall(position.x);
msg.writeSmall(position.y);
msg.writeSmall(type.id);
msg << disabled;
msg << upgrading;
if(tied !is null) {
msg.write1();
msg << tied;
}
else {
msg.write0();
}
if(completion < 1.f) {
msg.write1();
msg.writeFixed(completion, 0, 1.f, 7);
}
else {
msg.write0();
}
}
void read(Message& msg) {
position.x = msg.readSmall();
position.y = msg.readSmall();
@type = getBuildingType(msg.readSmall());
msg >> disabled;
msg >> upgrading;
if(msg.readBit())
msg >> tied;
else
@tied = null;
if(msg.readBit()) {
completion = msg.readFixed(0, 1.f, 7);
}
else {
completion = 1.f;
}
}
void save(SaveFile& msg) {
msg << position;
msg.writeIdentifier(SI_Building, type.id);
msg << completion;
msg << disabled;
msg << upgrading;
msg << tied;
msg << cost;
msg << cycle;
if(completion >= 1.f)
type.save(this, msg);
}
void load(SaveFile& msg) {
msg >> position;
uint tid = msg.readIdentifier(SI_Building);
@type = getBuildingType(tid);
if(type.hooks.length > 0)
@data = array<any>(type.hooks.length);
msg >> completion;
msg >> disabled;
msg >> upgrading;
msg >> tied;
if(msg >= SV_0072) {
msg >> cost;
msg >> cycle;
}
if(completion >= 1.f || msg < SV_0136)
type.load(this, msg);
}
string getTooltip(Object@ obj = null) {
return type.getTooltip(showCost=false, showSize=false, valueObject=obj);
}
};
void parseLine(ReadFile& file, string& line, BuildingType@ bld) {
if(line.findFirst("(") == -1) {
//Resource line
array<string>@ decls = line.split(",");
for(uint i = 0, cnt = decls.length; i < cnt; ++i) {
array<string>@ parts = decls[i].split(" ");
if(parts.length != 3) {
file.error("Invalid building effect: "+escape(decls[i].trimmed()));
continue;
}
uint resource = getTileResource(parts[1]);
if(resource == TR_INVALID) {
file.error("Invalid building effect: "+escape(decls[i].trimmed()));
continue;
}
double amt = toDouble(parts[0]);
string type = parts[2].trimmed();
if(type.equals_nocase("saturation")) {
bld.saturates[resource] += amt;
}
else if(type.equals_nocase("production")) {
bld.resources[resource] += amt;
}
else {
file.error("Invalid building effect: "+escape(decls[i].trimmed()));
continue;
}
}
}
else {
//Hook line
auto@ hook = cast<IBuildingHook@>(parseHook(line, "building_effects::", instantiate=false, file=file));
if(hook !is null) {
hook.initialize(bld, bld.hooks.length);
bld.hooks.insertLast(hook);
}
}
}
void loadBuildings(const string& filename) {
ReadFile file(filename, true);
string key, value;
BuildingType@ bld;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
if(bld is null) {
file.error("Missing 'Building: ID' line");
continue;
}
string line = file.line;
parseLine(file, line, bld);
}
else if(key == "Building") {
if(bld !is null)
addBuildingType(bld);
@bld = BuildingType();
bld.ident = value;
}
else if(bld is null) {
error("Missing 'Building: ID' line in " + filename);
}
else if(key == "Name") {
bld.name = localize(value);
}
else if(key == "Description") {
bld.description = localize(value);
}
else if(key == "Sprite") {
bld.sprite = getSprite(value);
}
else if(key == "Upgrades From") {
bld.upgradesFrom = value;
}
else if(key == "Category") {
bld.category = value;
}
else if(key == "Civilian") {
if(toBool(value)) {
bld.cls = BC_Civilian;
bld.pressureCapTaken = 1;
}
}
else if(key == "City") {
if(toBool(value)) {
bld.cls = BC_City;
bld.pressureCapTaken = 0;
}
}
else if(key == "Size") {
array<string>@ split = value.split("x");
if(split.length != 2) {
error("Invalid building size: "+escape(file.line));
}
else {
bld.size.x = toUInt(split[0]);
bld.size.y = toUInt(split[1]);
}
}
else if(key == "Base Cost") {
bld.baseBuildCost = toInt(value);
}
else if(key == "Tile Cost") {
bld.tileBuildCost = toInt(value);
}
else if(key == "Base Maintenance") {
bld.baseMaintainCost = toInt(value);
}
else if(key == "Tile Maintenance") {
bld.tileMaintainCost = toInt(value);
}
else if(key == "Build Time") {
bld.buildTime = toDouble(value);
}
else if(key == "Labor Cost") {
bld.laborCost = toDouble(value);
bld.buildInQueue = true;
}
else if(key == "Pressure Cap") {
bld.pressureCapTaken = toInt(value);
}
else if(key == "Build Affinity") {
bld.buildAffinities.insertLast(BiomeAffinity(value));
}
else if(key == "Maintenance Affinity") {
bld.maintainAffinities.insertLast(BiomeAffinity(value));
}
else if(key == "In Queue") {
bld.buildInQueue = toBool(value);
}
else if(key == "Saturation") {
array<string>@ decls = value.split(",");
for(uint i = 0, cnt = decls.length; i < cnt; ++i) {
array<string>@ parts = decls[i].split(" ");
if(parts.length != 2) {
file.error("Invalid saturation spec: "+escape(decls[i]));
continue;
}
uint resource = getTileResource(parts[1]);
if(resource == TR_INVALID) {
file.error("Invalid pressure spec: "+escape(decls[i]));
continue;
}
double amt = toDouble(parts[0]);
bld.saturates[resource] += amt;
}
}
else if(key == "Production") {
array<string>@ decls = value.split(",");
for(uint i = 0, cnt = decls.length; i < cnt; ++i) {
array<string>@ parts = decls[i].split(" ");
if(parts.length != 2) {
file.error("Invalid saturation spec: "+escape(decls[i]));
continue;
}
uint resource = getTileResource(parts[1]);
if(resource == TR_INVALID) {
file.error("Invalid pressure spec: "+escape(decls[i]));
continue;
}
double amt = toDouble(parts[0]);
bld.resources[resource] += amt;
}
}
else if(key.equals_nocase("AI")) {
auto@ hook = parseHook(value, "ai.buildings::", instantiate=false, file=file);
if(hook !is null)
bld.ai.insertLast(hook);
else
file.error("Could not find AI hook "+value);
}
else {
string line = file.line;
parseLine(file, line, bld);
}
}
if(bld !is null)
addBuildingType(bld);
}
void preInit() {
FileList list("data/buildings", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadBuildings(list.path[i]);
for(uint i = 0, cnt = buildings::types.length; i < cnt; ++i) {
BuildingType@ type = buildings::types[i];
if(type.upgradesFrom.length != 0) {
BuildingType@ par;
buildings::typeIdents.get(type.upgradesFrom, @par);
if(par !is null) {
par.upgrades.insertLast(type);
@type.base = par;
}
else {
error("Error: "+type.ident+": Could not find base building "+type.upgradesFrom);
}
}
}
}
void init() {
auto@ list = buildings::types;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ type = list[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n)
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(type.hooks[n])+" in "+type.ident);
for(uint n = 0, ncnt = type.buildAffinities.length; n < ncnt; ++n)
type.buildAffinities[n].init();
for(uint n = 0, ncnt = type.maintainAffinities.length; n < ncnt; ++n)
type.maintainAffinities[n].init();
for(uint n = 0, ncnt = type.ai.length; n < ncnt; ++n) {
if(!type.ai[n].instantiate())
error("Could not instantiate AI hook: "+addrstr(type.ai[n])+" in building "+type.ident);
}
}
}
uint getBuildingTypeCount() {
return buildings::types.length;
}
string getBuildingIdent(int id) {
if(uint(id) < buildings::types.length)
return buildings::types[id].ident;
return "";
}
int getBuildingID(const string& ident) {
BuildingType@ def;
buildings::typeIdents.get(ident, @def);
if(def is null)
return -1;
return def.id;
}
const BuildingType@ getBuildingType(uint id) {
if(id < buildings::types.length)
return buildings::types[id];
return null;
}
const BuildingType@ getBuildingType(const string& ident) {
BuildingType@ def;
buildings::typeIdents.get(ident, @def);
return def;
}
void addBuildingType(BuildingType@ def) {
def.id = buildings::types.length;
buildings::typeIdents.set(def.ident, @def);
buildings::types.insertLast(def);
for(uint i = 0; i < TR_COUNT; ++i) {
def.totalResource += def.resources[i];
def.totalSaturate += def.saturates[i];
}
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = buildings::types.length; i < cnt; ++i) {
BuildingType@ type = buildings::types[i];
file.addIdentifier(SI_Building, type.id, type.ident);
}
}
+123
View File
@@ -0,0 +1,123 @@
export CampaignScenario;
export getCampaignScenarioCount, getCampaignScenario;
export completeCampaignScenario, reloadCampaignCompletion;
class CampaignScenario {
uint id;
string ident;
string name;
string description;
Sprite picture;
Sprite icon;
Color color;
array<string> dependencies;
string mapName;
bool completed = false;
bool get_isAvailable() const {
for(uint i = 0, cnt = dependencies.length; i < cnt; ++i) {
auto@ other = getCampaignScenario(i);
if(other !is null && !other.completed)
return false;
}
return true;
}
};
array<CampaignScenario@> campaignList;
dictionary campaignIdents;
uint getCampaignScenarioCount() {
return campaignList.length;
}
const CampaignScenario@ getCampaignScenario(uint index) {
if(index >= campaignList.length)
return null;
return campaignList[index];
}
const CampaignScenario@ getCampaignScenario(const string& ident) {
CampaignScenario@ scen;
if(!campaignIdents.get(ident, @scen))
return null;
return scen;
}
void loadScenarios(const string& filename) {
ReadFile file(filename, true);
string key, value;
CampaignScenario@ scen;
while(file++) {
key = file.key;
value = file.value;
if(key == "Scenario") {
@scen = CampaignScenario();
scen.ident = value;
scen.id = campaignList.length;
campaignList.insertLast(scen);
campaignIdents.set(scen.ident, @scen);
}
else if(scen is null) {
file.error("Missing 'Scenario: ID' line.");
}
else if(key == "Name") {
scen.name = localize(value);
}
else if(key == "Description") {
scen.description = localize(value);
}
else if(key == "Icon") {
scen.icon = getSprite(value);
}
else if(key == "Picture") {
scen.picture = getSprite(value);
}
else if(key == "Color") {
scen.color = toColor(value);
}
else if(key == "Map") {
scen.mapName = value;
}
else if(key == "Dependency") {
scen.dependencies.insertLast(value);
}
}
}
void preInit() {
FileList list("data/campaign", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadScenarios(list.path[i]);
reloadCampaignCompletion();
}
void completeCampaignScenario(const string& ident) {
reloadCampaignCompletion();
CampaignScenario@ scen;
if(campaignIdents.get(ident, @scen) && scen !is null)
scen.completed = true;
WriteFile file(path_join(modProfile, "campaign"));
for(uint i = 0, cnt = campaignList.length; i < cnt; ++i) {
if(campaignList[i].completed)
file.writeLine(campaignList[i].ident);
}
}
void reloadCampaignCompletion() {
for(uint i = 0, cnt = campaignList.length; i < cnt; ++i)
campaignList[i].completed = false;
ReadFile completed(path_join(modProfile, "campaign"), true);
CampaignScenario@ scen;
while(completed++) {
if(campaignIdents.get(completed.line, @scen) && scen !is null)
scen.completed = true;
}
}
+359
View File
@@ -0,0 +1,359 @@
#priority init 2001
import pickups;
import statuses;
from pickups import IPickupHook, PickupHook;
import saving;
import hooks;
export CampType;
export getCreepCamp, getCreepCampCount;
export getDistributedCreepCamp;
#section server
from empire import Creeps;
#section all
tidy final class CampType {
uint id = 0;
string ident;
double frequency = 1.0;
double pickupFrequency = 0.0;
int flagshipSize = 0;
double supportOccupation = 1.0;
double targetStrength = 0.0;
array<string> def_region_statuses;
array<const StatusType@> region_statuses;
array<string> def_statuses;
array<const StatusType@> statuses;
array<PickupType@> pickups;
array<string> def_ships;
array<const Design@> ships;
array<string> shipNames;
array<uint> shipMins;
array<uint> shipMaxes;
void init() {
statuses.length = 0;
for(uint i = 0, cnt = def_statuses.length; i < cnt; ++i) {
auto@ type = getStatusType(def_statuses[i]);
if(type is null) {
error("ERROR: Could not find status '"+def_statuses[i]+"' in creep camp '"+ident+"'.");
continue;
}
statuses.insertLast(type);
}
for(uint i = 0, cnt = def_region_statuses.length; i < cnt; ++i) {
auto@ type = getStatusType(def_region_statuses[i]);
if(type is null) {
error("ERROR: Could not find region status '"+def_region_statuses[i]+"' in creep camp '"+ident+"'.");
continue;
}
region_statuses.insertLast(type);
}
#section server
for(uint i = 0, cnt = def_ships.length; i < cnt; ++i) {
string line = def_ships[i];
const Design@ dsg;
uint min = 1, max = 1;
string name;
if(line.findFirst("[") != -1 && line.findFirst("]") != -1) {
int fpos = line.findFirst("[");
int epos = line.findFirst("]");
name = localize(line.substr(fpos+1, epos-fpos-1));
line = line.substr(0, fpos);
}
@dsg = Creeps.getDesign(line.trimmed());
if(dsg is null) {
//Check if we have a number
int pos = line.findFirst(" ");
if(pos == -1) {
error(" Error: invalid design spec "+escape(line.trimmed()));
return;
}
string counts = line.substr(0, pos).trimmed();
string design = line.substr(pos).trimmed();
if(counts[counts.length-1] != 'x') {
error(" Error: could not find design "+escape(line.trimmed()));
return;
}
int dashPos = counts.findFirst("-");
if(dashPos == -1) {
min = max = toUInt(counts.substr(0, counts.length-1));
}
else {
min = toUInt(counts.substr(0, dashPos));
max = toUInt(counts.substr(dashPos+1, counts.length-dashPos-2));
}
@dsg = Creeps.getDesign(design);
if(dsg is null) {
error(" Error: could not find design "+escape(line.trimmed()));
return;
}
}
ships.insertLast(dsg);
shipMins.insertLast(min);
shipMaxes.insertLast(max);
shipNames.insertLast(name);
}
#section all
}
};
void parseLine(string& line, CampType@ c, ReadFile@ file) {
//Try to find the design
if(line.findFirst("(") == -1) {
c.def_ships.insertLast(line);
}
else {
if(c.pickups.length == 0) {
error("Missing 'Pickup:' line for: "+escape(line));
return;
}
//Hook line
auto@ hook = cast<IPickupHook>(parseHook(line, "pickup_effects::", instantiate=false, file=file));
if(hook !is null)
c.pickups[c.pickups.length-1].hooks.insertLast(hook);
}
}
void loadCamps(const string& filename) {
ReadFile file(filename, true);
string key, value;
CampType@ c;
PickupType@ p;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
if(c is null) {
error("Missing 'Camp: ID' line in " + filename);
continue;
}
string line = file.line;
parseLine(line, c, file);
}
else if(key == "Camp") {
if(c !is null)
addCreepCamp(c);
@c = CampType();
c.ident = value;
if(c.ident.length == 0)
c.ident = filename+"__"+index;
@p = null;
++index;
}
else if(c is null) {
error("Missing 'Camp: ID' line in " + filename);
}
else if(key == "Frequency") {
if(p !is null)
p.frequency = toDouble(value);
else
c.frequency = toDouble(value);
}
else if(key == "Pickup") {
@p = PickupType();
p.ident = value;
if(p.ident.length == 0)
p.ident = c.ident+"__"+c.pickups.length;
c.pickups.insertLast(p);
}
else if(key == "DLC") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
p.dlc = value;
}
else if(key == "Name") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
p.name = localize(value);
}
else if(key == "Verb") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
p.verb = localize(value);
}
else if(key == "Description") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
p.description = localize(value);
}
else if(key == "Model") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
@p.model = getModel(value);
}
else if(key == "Material") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
@p.material = getMaterial(value);
}
else if(key == "Physical Size") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
p.physicalSize = toDouble(value);
}
else if(key == "Icon Sheet") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
@p.iconSheet = getSpriteSheet(value);
}
else if(key == "Icon Index") {
if(p is null) {
error("Missing 'Pickup:' line in " + filename);
continue;
}
p.iconIndex = toUInt(value);
}
else if(key == "Region Status") {
c.def_region_statuses.insertLast(value);
}
else if(key == "Remnant Status") {
c.def_statuses.insertLast(value);
}
else if(key == "Flagship Size") {
c.flagshipSize = toInt(value);
}
else if(key == "Target Strength") {
c.targetStrength = toDouble(value);
}
else if(key == "Support Occupation") {
c.supportOccupation = toDouble(value);
}
else if(key == "Ship") {
parseLine(value, c, file);
}
else {
string line = file.line;
parseLine(line, c, file);
}
}
if(c !is null)
addCreepCamp(c);
}
bool initialized = false;
void initCreepCampTypes() {
if(initialized)
return;
initialized = true;
for(uint i = 0, cnt = campTypes.length; i < cnt; ++i)
campTypes[i].init();
}
void preInit() {
//Load camp types
FileList list("data/creeps", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadCamps(list.path[i]);
}
void init() {
if(!isLoadedSave)
initCreepCampTypes();
}
CampType@[] campTypes;
dictionary idents;
double totalFrequency = 0;
const CampType@ getCreepCamp(uint id) {
if(id >= campTypes.length)
return null;
return campTypes[id];
}
const CampType@ getCreepCamp(const string& ident) {
CampType@ camp;
if(idents.get(ident, @camp))
return camp;
return null;
}
uint getCreepCampCount() {
return campTypes.length;
}
const CampType@ getDistributedCreepCamp() {
double num = randomd(0, totalFrequency);
for(uint i = 0, cnt = campTypes.length; i < cnt; ++i) {
const CampType@ type = campTypes[i];
double freq = type.frequency;
if(num <= freq)
return type;
num -= freq;
}
return campTypes[campTypes.length-1];
}
void addCreepCamp(CampType@ type) {
type.id = campTypes.length;
campTypes.insertLast(type);
idents.set(type.ident, @type);
type.pickupFrequency = 0.0;
for(uint i = 0, cnt = type.pickups.length; i < cnt; ++i) {
auto@ pu = type.pickups[i];
if(pu.dlc.length != 0 && !hasDLC(pu.dlc))
pu.frequency = 0.0;
addPickupType(pu);
type.pickupFrequency += pu.frequency;
}
if(type.pickupFrequency == 0.0)
type.frequency = 0.0;
totalFrequency += type.frequency;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = campTypes.length; i < cnt; ++i) {
auto type = campTypes[i];
file.addIdentifier(SI_CreepCamp, type.id, type.ident);
}
}
File diff suppressed because it is too large Load Diff
+395
View File
@@ -0,0 +1,395 @@
#priority init 2000
import saving;
import attributes;
export CargoType;
export CargoStorage;
export hasDesignCosts;
export getCargoID;
export getCargoType, getCargoTypeCount;
tidy final class CargoType {
uint id;
string ident;
string name;
string description;
Sprite icon;
Color color;
double storageSize = 1.0;
HexVariable variable = HexVariable(-1);
};
tidy class CargoStorage : Serializable, Savable {
array<const CargoType@>@ types;
array<double>@ amounts;
double capacity = 0.0;
double filled = 0.0;
bool delta = false;
uint get_length() {
return types.length;
}
int index(const CargoType@ type, bool create = true) {
int ind = -1;
if(types !is null)
ind = types.find(type);
if(ind == -1 && create) {
if(types is null) {
@types = array<const CargoType@>();
@amounts = array<double>();
}
ind = types.length;
types.insertLast(type);
amounts.insertLast(0.0);
}
return ind;
}
void remove(const CargoType@ type) {
int ind = index(type, false);
if(ind == -1)
return;
if(types is null)
return;
types.removeAt(ind);
amounts.removeAt(ind);
/*if(types.length == 0) {*/
/* @types = null;*/
/* @amounts = null;*/
/*}*/
}
void removeAll() {
@types = null;
@amounts = null;
filled = 0;
}
double get(const CargoType@ type) {
int ind = index(type, false);
if(ind == -1)
return 0.0;
return amounts[ind];
}
double add(const CargoType@ type, double amount, bool partial = true) {
if(!partial && (capacity - filled) < type.storageSize * amount)
return 0.0;
double storeAmt = min(amount, (capacity - filled) / type.storageSize);
if(storeAmt <= 0.0001)
return 0.0;
int ind = index(type);
amounts[ind] += storeAmt;
filled = clamp(filled + (storeAmt * type.storageSize), 0, capacity);
delta = true;
return amount - storeAmt;
}
double consume(const CargoType@ type, double amount, bool partial = false) {
int ind = index(type, false);
if(ind == -1)
return 0.0;
if(!partial && amounts[ind] < amount)
return 0.0;
double consAmt = min(amount, amounts[ind]);
amounts[ind] -= consAmt;
filled = clamp(filled - (consAmt * type.storageSize), 0, capacity);
delta = true;
if(amounts[ind] < 0.0001)
remove(type);
return consAmt;
}
void write(Message& msg) {
if(types is null) {
msg.writeSmall(0);
}
else {
msg.writeSmall(types.length);
for(uint i = 0, cnt = types.length; i < cnt; ++i) {
msg.writeSmall(types[i].id);
msg << amounts[i];
}
}
msg << capacity;
msg << filled;
}
void read(Message& msg) {
uint cnt = msg.readSmall();
if(cnt == 0) {
if(types !is null) {
@types = null;
@amounts = null;
}
}
else {
if(types is null) {
@types = array<const CargoType@>();
@amounts = array<double>();
}
types.length = cnt;
amounts.length = cnt;
for(uint i = 0; i < cnt; ++i) {
@types[i] = getCargoType(msg.readSmall());
msg >> amounts[i];
}
}
msg >> capacity;
msg >> filled;
}
void save(SaveFile& file) {
uint cnt = 0;
if(types !is null)
cnt = types.length;
file << cnt;
for(uint i = 0; i < cnt; ++i) {
file.writeIdentifier(SI_CargoType, types[i].id);
file << amounts[i];
}
file << capacity;
file << filled;
}
void load(SaveFile& file) {
uint cnt = 0;
file >> cnt;
if(cnt == 0) {
if(types !is null) {
@types = null;
@amounts = null;
}
}
else {
if(types is null) {
@types = array<const CargoType@>();
@amounts = array<double>();
}
types.length = cnt;
amounts.length = cnt;
for(uint i = 0; i < cnt; ++i) {
auto@ type = getCargoType(file.readIdentifier(SI_CargoType));
if(type is null) {
double tmp = 0;
file >> tmp;
amounts.removeAt(i);
--cnt; --i;
}
else {
@types[i] = type;
file >> amounts[i];
}
}
}
file >> capacity;
file >> filled;
}
};
#section server
export payDesignCosts, reverseDesignCosts;
bool payDesignCosts(Object& obj, const Design@ dsg, double multiply = 1.0) {
double energyCost = dsg.total(SV_EnergyBuildCost);
if(energyCost > 0) {
if(obj.owner.consumeEnergy(energyCost, consumePartial=false) < energyCost-0.001)
return false;
}
int influenceCost = dsg.total(SV_InfluenceBuildCost);
if(influenceCost > 0) {
if(!obj.owner.consumeInfluence(influenceCost)) {
if(energyCost > 0)
obj.owner.modEnergyStored(+energyCost);
return false;
}
}
double ftlCost = dsg.total(SV_FTLBuildCost);
if(ftlCost > 0) {
if(obj.owner.consumeFTL(ftlCost, partial=false, record=false) < ftlCost-0.001) {
if(energyCost > 0)
obj.owner.modEnergyStored(+energyCost);
if(influenceCost > 0)
obj.owner.modInfluence(+influenceCost);
return false;
}
}
for(uint i = 0, cnt = getCargoTypeCount(); i < cnt; ++i) {
auto@ cargo = getCargoType(i);
if(int(cargo.variable) == -1)
continue;
double amt = dsg.total(cargo.variable) * multiply;
if(amt > 0) {
if(!obj.hasCargo || obj.consumeCargo(cargo.id, amt, partial=false) < amt - 0.001) {
for(uint j = 0; j < i; ++j) {
auto@ other = getCargoType(j);
if(int(other.variable) == -1)
continue;
double amt = dsg.total(other.variable) * multiply;
if(amt > 0)
obj.addCargo(other.id, amt);
}
if(energyCost > 0)
obj.owner.modEnergyStored(+energyCost);
if(influenceCost > 0)
obj.owner.modInfluence(+influenceCost);
if(ftlCost > 0)
obj.owner.modFTLStored(+ftlCost);
return false;
}
}
}
if(ftlCost > 0)
obj.owner.modAttribute(EA_FTLEnergySpent, AC_Add, ftlCost);
return true;
}
void reverseDesignCosts(Object& obj, const Design@ dsg, double multiply = 1.0, bool cancel = false) {
if(!cancel) {
double energyCost = dsg.total(SV_EnergyBuildCost);
if(energyCost > 0)
obj.owner.modEnergyStored(+energyCost);
int influenceCost = dsg.total(SV_EnergyBuildCost);
if(influenceCost > 0)
obj.owner.addInfluence(+influenceCost);
double ftlCost = dsg.total(SV_FTLBuildCost);
if(ftlCost > 0)
obj.owner.modFTLStored(+ftlCost, obeyMaximum=true);
}
if(obj.hasCargo) {
for(uint i = 0, cnt = getCargoTypeCount(); i < cnt; ++i) {
auto@ cargo = getCargoType(i);
if(int(cargo.variable) == -1)
continue;
double amt = dsg.total(cargo.variable) * multiply;
if(amt > 0)
obj.addCargo(cargo.id, amt);
}
}
}
#section all
bool hasDesignCosts(const Design@ dsg) {
for(uint i = 0, cnt = getCargoTypeCount(); i < cnt; ++i) {
auto@ cargo = getCargoType(i);
if(int(cargo.variable) == -1)
continue;
double amt = dsg.total(cargo.variable);
if(amt > 0)
return true;
}
if(dsg.total(SV_EnergyBuildCost) > 0)
return true;
if(dsg.total(SV_InfluenceBuildCost) > 0)
return true;
if(dsg.total(SV_FTLBuildCost) > 0)
return true;
return false;
}
array<CargoType@> cargoTypes;
dictionary cargoIdents;
int getCargoID(const string& ident) {
auto@ type = getCargoType(ident);
if(type is null)
return -1;
return int(type.id);
}
string getCargoIdent(int id) {
auto@ type = getCargoType(id);
if(type is null)
return "";
return type.ident;
}
const CargoType@ getCargoType(uint id) {
if(id >= cargoTypes.length)
return null;
return cargoTypes[id];
}
const CargoType@ getCargoType(const string& ident) {
CargoType@ def;
if(cargoIdents.get(ident, @def))
return def;
return null;
}
uint getCargoTypeCount() {
return cargoTypes.length;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = cargoTypes.length; i < cnt; ++i) {
auto type = cargoTypes[i];
file.addIdentifier(SI_CargoType, type.id, type.ident);
}
}
void addCargoType(CargoType@ type) {
type.id = cargoTypes.length;
cargoTypes.insertLast(type);
cargoIdents.set(type.ident, @type);
}
void loadCargo(const string& filename) {
ReadFile file(filename, false);
string key, value;
CargoType@ type;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(key.equals_nocase("Cargo")) {
@type = CargoType();
type.ident = value;
addCargoType(type);
type.variable = getHexVariable(type.ident+"Cost");
}
else if(type is null) {
file.error("Missing Cargo: ID' line");
}
else if(key.equals_nocase("Name")) {
type.name = localize(value);
}
else if(key.equals_nocase("Description")) {
type.description = localize(value);
}
else if(key.equals_nocase("Icon")) {
type.icon = getSprite(value);
}
else if(key.equals_nocase("Color")) {
type.color = toColor(value);
}
else if(key.equals_nocase("Storage Size")) {
type.storageSize = toDouble(value);
}
}
}
void preInit() {
FileList list("data/cargo", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadCargo(list.path[i]);
}
+95
View File
@@ -0,0 +1,95 @@
enum CargoType {
CT_Resource,
CT_Goods,
};
enum CivilianType {
CiT_Freighter,
CiT_Station,
};
array<const Model@> CivilianModels = {
model::Fighter,
model::CommerceStation,
};
array<const Material@> CivilianMaterials = {
material::Ship10,
material::GenericPBR_CommerceStation,
};
array<Sprite> CivilianIcons = {
Sprite(spritesheet::HullIcons, 2),
Sprite(spritesheet::OrbitalIcons, 0),
};
const double CIV_SIZE_MIN = 2.0;
const double CIV_SIZE_MAX = 5.4;
const double CIV_SIZE_FREIGHTER = 2.7;
const double CIV_SIZE_CARAVAN = 5.0;
const double CIV_RADIUS_WORTH = 1.0;
const int CIV_CARAVAN_INCOME = 15;
const int CIV_STATION_INCOME = 20;
const Model@ getCivilianModel(Empire@ owner, uint type, double radius) {
if(owner !is null) {
auto@ ss = owner.shipset;
if(ss !is null) {
const ShipSkin@ skin;
if(type == CiT_Freighter)
@skin = ss.getSkin("Freighter");
if(skin !is null)
return skin.model;
}
}
return CivilianModels[type];
}
const Material@ getCivilianMaterial(Empire@ owner, uint type, double radius) {
if(owner !is null) {
auto@ ss = owner.shipset;
if(ss !is null) {
const ShipSkin@ skin;
if(type == CiT_Freighter)
@skin = ss.getSkin("Freighter");
if(skin !is null)
return skin.material;
}
}
return CivilianMaterials[type];
}
double randomCivilianFreighterSize() {
return sqr(randomd()) * (CIV_SIZE_MAX - CIV_SIZE_MIN) + CIV_SIZE_MIN;
}
string getCivilianName(uint type, double radius) {
if(type == CiT_Freighter) {
if(radius >= CIV_SIZE_CARAVAN)
return locale::CIVILIAN_CARAVAN;
else if(radius >= CIV_SIZE_FREIGHTER)
return locale::CIVILIAN_FREIGHTER;
return locale::CIVILIAN_MERCHANT;
}
else if(type == CiT_Station) {
return locale::CIVILIAN_STATION;
}
return locale::CIVILIAN;
}
Sprite getCivilianIcon(Empire@ owner, uint type, double radius) {
if(type == CiT_Freighter) {
if(radius >= CIV_SIZE_CARAVAN)
return Sprite(spritesheet::HullIcons, 4);
else if(radius >= CIV_SIZE_FREIGHTER)
return Sprite(spritesheet::HullIcons, 3);
}
return CivilianIcons[type];
}
const double STATION_MIN_RAD = 5.0;
const double STATION_MAX_RAD = 10.0;
+870
View File
@@ -0,0 +1,870 @@
import influence;
import hooks;
from influence import InfluenceClauseHook;
import resources;
#section server
import influence_global;
#section all
//ShareVision(To Starter = True, To Other = True)
// Share empire vision between the empires.
/// If <To Starter> is true, the treaty starter gets vision.
/// If <To Other> is true, the treaty signatories get vision.
class ShareVision : InfluenceClauseHook {
Document doc("Shares vision from either of the parties in a treaty to the other (or both).");
Argument starter("To Starter", AT_Boolean, "True", doc="Whether the receiver shares vision with the starter.");
Argument other("To Other", AT_Boolean, "True", doc="Whether the starter shares vision with the receiver.");
#section server
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
uint mask = 0;
if(treaty.leader !is null)
mask = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i)
mask |= treaty.joinedEmpires[i].mask;
if(starter.boolean && treaty.leader !is null)
treaty.leader.visionMask |= mask;
if(other.boolean) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
if(treaty.joinedEmpires[i] !is treaty.leader)
treaty.joinedEmpires[i].visionMask |= mask;
}
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const override {
if(treaty.leader !is null)
treaty.leader.visionMask = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i)
treaty.joinedEmpires[i].visionMask = treaty.joinedEmpires[i].mask;
}
void onLeave(Treaty@ treaty, Clause@ clause, Empire@ left) const override {
left.visionMask = left.mask;
onEnd(treaty, clause);
onTick(treaty, clause, 0.0);
}
#section all
};
//FreeTrade(To Starter = True, To Other = True)
// Share trade borders between empires.
/// If <To Starter> is true, the treaty starter gets free trade.
/// If <To Other> is true, the treaty signatories get free trade.
class FreeTrade : InfluenceClauseHook {
Document doc("Shares trade from either of the parties in a treaty to the other (or both).");
Argument starter("To Starter", AT_Boolean, "True", doc="Whether the receiver shares trade with the starter.");
Argument other("To Other", AT_Boolean, "True", doc="Whether the starter shares trade with the receiver.");
#section server
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
uint mask = 0;
if(treaty.leader !is null)
mask = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i)
mask |= treaty.joinedEmpires[i].mask;
if(starter.boolean && treaty.leader !is null)
treaty.leader.TradeMask |= mask;
if(other.boolean) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
if(treaty.joinedEmpires[i] !is treaty.leader)
treaty.joinedEmpires[i].TradeMask |= mask;
}
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const override {
if(treaty.leader !is null)
treaty.leader.TradeMask.value = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i)
treaty.joinedEmpires[i].TradeMask.value = treaty.joinedEmpires[i].mask;
}
void onLeave(Treaty@ treaty, Clause@ clause, Empire@ left) const override {
left.TradeMask.value = left.mask;
onEnd(treaty, clause);
onTick(treaty, clause, 0.0);
}
#section all
};
//ForcePeace()
// Empires cannot declare war on each other while in this treaty.
class ForcePeace : InfluenceClauseHook {
Document doc("Prevents and ends wars between any members of this treaty.");
Argument break_on_war(AT_Boolean, "False", doc="Break the treaty if war does happen, for example due to mutual defense pacts.");
#section server
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
uint mask = 0;
if(treaty.leader !is null)
mask = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i)
mask |= treaty.joinedEmpires[i].mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp.hostileMask & mask != 0 && break_on_war.boolean) {
leaveTreaty(emp, treaty.id, force=true);
--i; --cnt;
continue;
}
emp.ForcedPeaceMask |= mask;
emp.PeaceMask &= ~mask;
}
}
void onJoin(Treaty@ treaty, Clause@ clause, Empire@ joined) const {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
Empire@ other = treaty.joinedEmpires[i];
if(other !is joined) {
other.setHostile(joined, false);
joined.setHostile(other, false);
}
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const override {
if(treaty.leader !is null)
treaty.leader.ForcedPeaceMask.value = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i)
treaty.joinedEmpires[i].ForcedPeaceMask.value = treaty.joinedEmpires[i].mask;
}
void onLeave(Treaty@ treaty, Clause@ clause, Empire@ left) const override {
left.ForcedPeaceMask.value = left.mask;
onEnd(treaty, clause);
onTick(treaty, clause, 0.0);
}
#section all
};
class MakePeace : InfluenceClauseHook {
Document doc("Ends wars when this treaty is accepted.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const override {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
Empire@ emp = treaty.joinedEmpires[i];
for(uint j = 0; j < cnt; ++j) {
Empire@ other = treaty.joinedEmpires[j];
if(other !is emp) {
other.setHostile(emp, false);
emp.setHostile(other, false);
}
}
}
}
#section all
};
class RemoveOnCreate : InfluenceClauseHook {
Document doc("This clause is temporary and is removed after applying its effects.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const override {
if(treaty.leader !is null) {
leaveTreaty(treaty.leader, treaty.id, force=true);
}
else {
array<Empire@> emps = treaty.joinedEmpires;
for(uint i = 0, cnt = emps.length; i < cnt; ++i)
leaveTreaty(emps[i], treaty.id, force=true);
}
}
#section all
};
//CannotBreak()
// This treaty is permanent and cannot be broken.
class CannotBreak : InfluenceClauseHook {
Document doc("Prevents this treaty from being broken.");
bool canLeave(const Treaty@ treaty, const Clause@ clause, Empire& empire) const {
return false;
}
};
//CannotInvite()
// No further empires can be invited to this treaty.
class CannotInvite : InfluenceClauseHook {
Document doc("Prevents inviting others to enter this treaty.");
bool canInvite(const Treaty@ treaty, const Clause@ clause, Empire& from, Empire& invite) const {
return false;
}
};
//CannotAlter()
// No additional clauses can be played into this treaty.
class CannotAlter : InfluenceClauseHook {
Document doc("Prevents any alterations to this treaty.");
};
class DictateWar : InfluenceClauseHook {
Document doc("The owner of the treaty dictates the war status for everyone.");
#section server
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
if(treaty.leader is null)
return;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ member = treaty.joinedEmpires[i];
if(member !is treaty.leader)
member.hostileMask = treaty.leader.hostileMask;
for(uint j = 0, jcnt = getEmpireCount(); j < jcnt; ++j) {
Empire@ other = getEmpire(j);
if(other is member || other is treaty.leader)
continue;
bool shouldWar = other.isHostile(treaty.leader);
bool hasWar = other.isHostile(member);
if(shouldWar != hasWar)
other.setHostile(member, shouldWar);
}
}
uint allMask = treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
allMask |= emp.mask;
}
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
emp.mutualDefenseMask |= allMask;
}
}
void onLeave(Treaty@ treaty, Clause@ clause, Empire@ left) const override {
uint allMask = 0;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
allMask |= emp.mask;
}
left.mutualDefenseMask &= ~allMask;
}
#section all
};
class DictateTrade : InfluenceClauseHook {
Document doc("The owner of the treaty dictates the trade capabilities for everyone.");
#section server
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
if(treaty.leader is null)
return;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ member = treaty.joinedEmpires[i];
if(member !is treaty.leader)
member.TradeMask.value = treaty.leader.TradeMask.value;
}
}
#section all
};
class DictateVision : InfluenceClauseHook {
Document doc("The owner of the treaty dictates everyone's vision.");
#section server
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
if(treaty.leader is null)
return;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ member = treaty.joinedEmpires[i];
if(member !is treaty.leader)
member.visionMask = treaty.leader.visionMask;
}
}
#section all
};
class NotNormallyVisible : InfluenceClauseHook {
Document doc("This treaty is not normally visible to people not in it.");
bool isVisibleTo(const Treaty@ treaty, const Clause@ clause, Empire& empire) const {
if(empire.mask & treaty.inviteMask != 0)
return true;
if(empire.mask & treaty.presentMask != 0)
return true;
return false;
}
};
class SubjugateMembers : InfluenceClauseHook {
Document doc("Members of this treaty count as subjugated.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const {
//Find out which empire is the leader
Empire@ subjEmp;
if(treaty.leader is null) {
@treaty.leader = treaty.joinedEmpires[1];
@subjEmp = treaty.joinedEmpires[0];
}
else {
@subjEmp = treaty.joinedEmpires[1];
}
treaty.name = format(locale::SURRENDER_NAME, formatEmpireName(subjEmp));
//Subjugate any secondaries
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ other = getEmpire(i);
if(other is subjEmp || other is treaty.leader)
continue;
if(other.SubjugatedBy is subjEmp) {
treaty.presentMask |= other.mask;
treaty.joinedEmpires.insertLast(other);
}
}
//Trigger subjugation
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
if(treaty.joinedEmpires[i] !is treaty.leader)
subjugate(treaty, treaty.joinedEmpires[i], treaty.leader);
}
}
void subjugate(Treaty& treaty, Empire& emp, Empire& leader) {
//Set subjugator
int pts = emp.prevPoints;
if(emp.SubjugatedBy !is null)
emp.SubjugatedBy.points -= pts;
@emp.SubjugatedBy = treaty.leader;
emp.SubjugatedBy.points += pts;
treaty.leader.setHostile(emp, false);
emp.setHostile(treaty.leader, false);
//Leave all existing treaties
Lock lck(influenceLock);
array<Treaty@> treaties = activeTreaties;
for(uint i = 0, cnt = treaties.length; i < cnt; ++i) {
auto@ other = treaties[i];
if(other.id == treaty.id)
continue;
if(other.inviteMask & emp.mask != 0)
declineTreaty(emp, other.id);
if(other.presentMask & emp.mask != 0)
leaveTreaty(emp, other.id, force=true);
}
//Notify everyone
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ other = getEmpire(i);
if(other is emp || other is leader)
continue;
if(emp.ContactMask & other.mask == 0)
continue;
other.notifyTreaty(treaty.id, TET_Subjugate, emp, leader);
}
}
void onJoin(Treaty@ treaty, Clause@ clause, Empire@ joined) const {
subjugate(treaty, joined, treaty.leader);
}
void onLeave(Treaty@ treaty, Clause@ clause, Empire@ left) const {
if(left.SubjugatedBy !is null) {
int pts = left.prevPoints;
left.SubjugatedBy.points -= pts;
}
@left.SubjugatedBy = null;
}
void onEnd(Treaty@ treaty, Clause@ clause) const {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
if(treaty.joinedEmpires[i] !is treaty.leader)
@treaty.joinedEmpires[i].SubjugatedBy = null;
}
}
#section all
};
class ShareWar : InfluenceClauseHook {
Document doc("When one member declares war, all members declare war.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const override {
uint warMask = 0;
clause.data[hookIndex].store(warMask);
}
void onJoin(Treaty@ treaty, Clause@ clause, Empire@ emp) const override {
uint curMask = 0;
clause.data[hookIndex].retrieve(curMask);
for(uint n = 0, ncnt = getEmpireCount(); n < ncnt; ++n) {
Empire@ other = getEmpire(n);
if(emp is other)
continue;
if(emp.isHostile(other)) {
if(curMask & other.mask == 0) {
emp.setHostile(other, false);
other.setHostile(emp, false);
}
}
else {
if(curMask & other.mask != 0) {
emp.setHostile(other, true);
other.setHostile(emp, true);
}
}
}
}
void onLeave(Treaty@ treaty, Clause@ clause, Empire@ left) const override {
uint allMask = 0;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
allMask |= emp.mask;
}
left.mutualDefenseMask &= ~allMask;
}
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
uint prevMask = 0, newMask = 0;
clause.data[hookIndex].retrieve(prevMask);
for(uint n = 0, ncnt = getEmpireCount(); n < ncnt; ++n) {
auto@ check = getEmpire(n);
bool wasWar = prevMask & check.mask != 0;
if(wasWar) {
bool isAllWar = true;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
if(!treaty.joinedEmpires[i].isHostile(check)) {
isAllWar = false;
continue;
}
}
if(!isAllWar) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp.isHostile(check)) {
emp.setHostile(check, false);
check.setHostile(emp, false);
}
}
}
else {
newMask |= check.mask;
}
}
else {
bool hasAnyWar = false;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
if(treaty.joinedEmpires[i].isHostile(check)) {
hasAnyWar = true;
continue;
}
}
if(hasAnyWar) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is check) {
//Boot from treaties that would be at war with yourself
leaveTreaty(emp, treaty.id, force=true);
--i; --cnt;
continue;
}
if(!emp.isHostile(check)) {
emp.setHostile(check, true);
check.setHostile(emp, true);
}
}
newMask |= check.mask;
}
}
}
uint allMask = 0;
if(treaty.leader !is null)
allMask |= treaty.leader.mask;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
allMask |= emp.mask;
}
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
emp.mutualDefenseMask |= allMask;
}
if(prevMask != newMask)
clause.data[hookIndex].store(newMask);
}
void save(Clause@ clause, SaveFile& file) const {
uint warMask = 0;
clause.data[hookIndex].retrieve(warMask);
file << warMask;
}
void load(Clause@ clause, SaveFile& file) const {
uint warMask = 0;
if(file >= SV_0070)
file >> warMask;
clause.data[hookIndex].store(warMask);
}
#section all
};
class GainPercentageMoney : InfluenceClauseHook {
Document doc("Gain a percentage of all members' incomes.");
Argument factor(AT_Decimal, doc="What percentage to give.");
Argument count_leader(AT_Boolean, "False", doc="Whether to count the leader's income.");
Argument count_members(AT_Boolean, "True", doc="Whether to count other members' income.");
Argument give_leader(AT_Boolean, "True", doc="Whether to give the income to the leader.");
Argument give_members(AT_Boolean, "False", doc="Whether to give the income to other members.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].store(amount);
}
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
double prevAmount = 0.0;
clause.data[hookIndex].retrieve(prevAmount);
double newAmount = 0.0;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!count_leader.boolean)
continue;
}
else {
if(!count_members.boolean)
continue;
}
newAmount += factor.decimal * double(emp.TotalBudget);
}
if(int(prevAmount) != int(newAmount)) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modTotalBudget(int(newAmount) - int(prevAmount), MoT_Vassals);
}
clause.data[hookIndex].store(newAmount);
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].retrieve(amount);
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modTotalBudget(-int(amount), MoT_Vassals);
}
amount = 0.0;
clause.data[hookIndex].store(amount);
}
void save(Clause@ clause, SaveFile& file) const {
double amount = 0;
clause.data[hookIndex].retrieve(amount);
file << amount;
}
void load(Clause@ clause, SaveFile& file) const {
double amount = 0;
if(file >= SV_0070)
file >> amount;
clause.data[hookIndex].store(amount);
}
#section all
};
class GainPercentageInfluence : InfluenceClauseHook {
Document doc("Gain a percentage of all members' influence incomes.");
Argument factor(AT_Decimal, doc="What percentage to give.");
Argument count_leader(AT_Boolean, "False", doc="Whether to count the leader's influence income.");
Argument count_members(AT_Boolean, "True", doc="Whether to count other members' influence income.");
Argument give_leader(AT_Boolean, "True", doc="Whether to give the influence income to the leader.");
Argument give_members(AT_Boolean, "False", doc="Whether to give the influence income to other members.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].store(amount);
}
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
double prevAmount = 0.0;
clause.data[hookIndex].retrieve(prevAmount);
double newAmount = 0.0;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!count_leader.boolean)
continue;
}
else {
if(!count_members.boolean)
continue;
}
newAmount += factor.decimal * double(emp.getInfluenceStock());
}
if(int(prevAmount) != int(newAmount)) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modInfluenceIncome(int(newAmount) - int(prevAmount));
}
clause.data[hookIndex].store(newAmount);
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].retrieve(amount);
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modInfluenceIncome(-int(amount));
}
amount = 0.0;
clause.data[hookIndex].store(amount);
}
void save(Clause@ clause, SaveFile& file) const {
double amount = 0;
clause.data[hookIndex].retrieve(amount);
file << amount;
}
void load(Clause@ clause, SaveFile& file) const {
double amount = 0;
if(file >= SV_0070)
file >> amount;
clause.data[hookIndex].store(amount);
}
#section all
};
class GainPercentageEnergy : InfluenceClauseHook {
Document doc("Gain a percentage of all members' energy generation.");
Argument factor(AT_Decimal, doc="What percentage to give.");
Argument count_leader(AT_Boolean, "False", doc="Whether to count the leader's energy generation.");
Argument count_members(AT_Boolean, "True", doc="Whether to count other members' energy generation.");
Argument give_leader(AT_Boolean, "True", doc="Whether to give the energy generation to the leader.");
Argument give_members(AT_Boolean, "False", doc="Whether to give the energy generation to other members.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].store(amount);
}
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
double prevAmount = 0.0;
clause.data[hookIndex].retrieve(prevAmount);
double newAmount = 0.0;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!count_leader.boolean)
continue;
}
else {
if(!count_members.boolean)
continue;
}
newAmount += factor.decimal * (emp.EnergyIncome - emp.EnergyUse);
}
if(int(prevAmount) != int(newAmount)) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modEnergyIncome(newAmount - prevAmount);
}
clause.data[hookIndex].store(newAmount);
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].retrieve(amount);
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modEnergyIncome(-amount);
}
amount = 0.0;
clause.data[hookIndex].store(amount);
}
void save(Clause@ clause, SaveFile& file) const {
double amount = 0;
clause.data[hookIndex].retrieve(amount);
file << amount;
}
void load(Clause@ clause, SaveFile& file) const {
double amount = 0;
if(file >= SV_0070)
file >> amount;
clause.data[hookIndex].store(amount);
}
#section all
};
class GainPercentageResearch : InfluenceClauseHook {
Document doc("Gain a percentage of all members' research generation.");
Argument factor(AT_Decimal, doc="What percentage to give.");
Argument count_leader(AT_Boolean, "False", doc="Whether to count the leader's research generation.");
Argument count_members(AT_Boolean, "True", doc="Whether to count other members' research generation.");
Argument give_leader(AT_Boolean, "True", doc="Whether to give the research generation to the leader.");
Argument give_members(AT_Boolean, "False", doc="Whether to give the research generation to other members.");
#section server
void onStart(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].store(amount);
}
void onTick(Treaty@ treaty, Clause@ clause, double time) const override {
double prevAmount = 0.0;
clause.data[hookIndex].retrieve(prevAmount);
double newAmount = 0.0;
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!count_leader.boolean)
continue;
}
else {
if(!count_members.boolean)
continue;
}
newAmount += factor.decimal * emp.ResearchRate;
}
if(int(prevAmount) != int(newAmount)) {
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modResearchRate(newAmount - prevAmount);
}
clause.data[hookIndex].store(newAmount);
}
}
void onEnd(Treaty@ treaty, Clause@ clause) const {
double amount = 0.0;
clause.data[hookIndex].retrieve(amount);
for(uint i = 0, cnt = treaty.joinedEmpires.length; i < cnt; ++i) {
auto@ emp = treaty.joinedEmpires[i];
if(emp is treaty.leader) {
if(!give_leader.boolean)
continue;
}
else {
if(!give_members.boolean)
continue;
}
emp.modResearchRate(-amount);
}
amount = 0.0;
clause.data[hookIndex].store(amount);
}
void save(Clause@ clause, SaveFile& file) const {
double amount = 0;
clause.data[hookIndex].retrieve(amount);
file << amount;
}
void load(Clause@ clause, SaveFile& file) const {
double amount = 0;
if(file >= SV_0070)
file >> amount;
clause.data[hookIndex].store(amount);
}
#section all
};
+341
View File
@@ -0,0 +1,341 @@
import constructions;
from constructions import ConstructionHook;
import generic_hooks;
import requirement_effects;
import bonus_effects;
import target_filters;
import listed_values;
import consume_effects;
import util.formatting;
#section server
from constructions import Constructible;
#section all
class AddBuildCostAttribute : ConstructionHook {
Document doc("Add build cost based on an empire attribute value.");
Argument attribute(AT_EmpAttribute, doc="Attribute to use.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
Argument power(AT_Decimal, "1", doc="Raise the attribute to this power before multiplying.");
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
double value = obj.owner.getAttribute(attribute.integer);
if(power.decimal != 1.0)
value = pow(value, power.decimal);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddMaintainCostAttribute : ConstructionHook {
Document doc("Add maintenance cost based on an empire attribute value.");
Argument attribute(AT_EmpAttribute, doc="Attribute to use.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
Argument power(AT_Decimal, "1", doc="Raise the attribute to this power before multiplying.");
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
double value = obj.owner.getAttribute(attribute.integer);
if(power.decimal != 1.0)
value = pow(value, power.decimal);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddLaborCostAttribute : ConstructionHook {
Document doc("Add labor cost based on an empire attribute value.");
Argument attribute(AT_EmpAttribute, doc="Attribute to use.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
Argument power(AT_Decimal, "1", doc="Raise the attribute to this power before multiplying.");
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const override {
double value = obj.owner.getAttribute(attribute.integer);
if(power.decimal != 1.0)
value = pow(value, power.decimal);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddBuildCostTotalPopulation : ConstructionHook {
Document doc("Add build cost based on an empire attribute value.");
Argument add(AT_Decimal, "0", doc="Modify the value by this amount first.");
Argument add_attribute(AT_EmpAttribute, EMPTY_DEFAULT, doc="Attribute to add to the amount first.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
Argument power(AT_Decimal, "1", doc="Raise the attribute to this power before multiplying.");
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
double value = obj.owner.TotalPopulation + add.decimal;
if(add_attribute.integer != 0)
value += obj.owner.getAttribute(add_attribute.integer);
value = max(value, 0.0);
if(power.decimal != 1.0)
value = pow(value, power.decimal);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddMaintainCostTotalPopulation : ConstructionHook {
Document doc("Add maintenance cost based on an empire attribute value.");
Argument add(AT_Decimal, "0", doc="Modify the value by this amount first.");
Argument add_attribute(AT_EmpAttribute, EMPTY_DEFAULT, doc="Attribute to add to the amount first.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
Argument power(AT_Decimal, "1", doc="Raise the attribute to this power before multiplying.");
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
double value = obj.owner.TotalPopulation + add.decimal;
if(add_attribute.integer != 0)
value += obj.owner.getAttribute(add_attribute.integer);
value = max(value, 0.0);
if(power.decimal != 1.0)
value = pow(value, power.decimal);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddLaborCostTotalPopulation : ConstructionHook {
Document doc("Add labor cost based on an empire attribute value.");
Argument add(AT_Decimal, "0", doc="Modify the value by this amount first.");
Argument add_attribute(AT_EmpAttribute, EMPTY_DEFAULT, doc="Attribute to add to the amount first.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
Argument power(AT_Decimal, "1", doc="Raise the attribute to this power before multiplying.");
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const override {
double value = obj.owner.TotalPopulation + add.decimal;
if(add_attribute.integer != 0)
value += obj.owner.getAttribute(add_attribute.integer);
value = max(value, 0.0);
if(power.decimal != 1.0)
value = pow(value, power.decimal);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
tidy final class OnStart : ConstructionHook {
Document doc("Trigger a hook whenever the construction is started.");
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::", required=false));
if(hook is null) {
error("OnStart(): could not find inner hook: "+escape(hookID.str));
return false;
}
return ConstructionHook::instantiate();
}
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const override {
if(hook !is null)
hook.activate(cons.obj, cons.obj.owner);
}
#section all
};
tidy final class OnCancel : ConstructionHook {
Document doc("Trigger a hook whenever the construction is canceled.");
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::", required=false));
if(hook is null) {
error("OnStart(): could not find inner hook: "+escape(hookID.str));
return false;
}
return ConstructionHook::instantiate();
}
#section server
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const override {
if(hook !is null)
hook.activate(cons.obj, cons.obj.owner);
}
#section all
};
tidy final class Trigger : ConstructionHook {
Document doc("Runs a triggered hook on the target when the construction completes.");
Argument targ(TT_Object);
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to run.");
BonusEffect@ hook;
GenericEffect@ eff;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::", required=false));
if(hook is null)
@eff = cast<GenericEffect>(parseHook(hookID.str, "planet_effects::", required=false));
if(hook is null && eff is null) {
error("Trigger(): could not find inner hook: "+escape(hookID.str));
return false;
}
return ConstructionHook::instantiate();
}
#section server
void finish(Construction@ cons, Constructible@ qitem, any@ data) const {
auto@ objTarg = targ.fromConstTarget(cons.targets);
if(objTarg is null || objTarg.obj is null)
return;
if(hook !is null)
hook.activate(objTarg.obj, cons.obj.owner);
else if(eff !is null)
eff.enable(objTarg.obj, null);
}
#section all
};
class SlowDownDebtGrowthFactor : ConstructionHook {
Document doc("This constructible gets slowed down depending on the current debt factor.");
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const override {
double lab = qitem.totalLabor;
data.store(lab);
}
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {
double lab = 0;
data.retrieve(lab);
float growthFactor = 1.f;
float debtFactor = cons.obj.owner.DebtFactor;
for(; debtFactor > 0; debtFactor -= 1.f)
growthFactor *= 0.33f + 0.67f * (1.f - min(debtFactor, 1.f));
qitem.totalLabor = (lab - qitem.curLabor) / max(growthFactor, 0.01f) + qitem.curLabor;
}
void save(Construction@ cons, any@ data, SaveFile& file) const {
double lab = 0;
data.retrieve(lab);
file << lab;
}
void load(Construction@ cons, any@ data, SaveFile& file) const {
double lab = 0;
file >> lab;
data.store(lab);
}
#section all
};
class AddBuildCostStatusCount : ConstructionHook {
Document doc("Add build cost based on the amount of stacks of a status present.");
Argument status(AT_Status, doc="Status to count.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
double value = obj.getStatusStackCountAny(status.integer);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddMaintainCostStatusCount : ConstructionHook {
Document doc("Add maintenance cost based on the amount of stacks of a status present.");
Argument status(AT_Status, doc="Status to count.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
double value = obj.getStatusStackCountAny(status.integer);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddLaborCostStatusCount : ConstructionHook {
Document doc("Add labor cost based on the amount of stacks of a status present.");
Argument status(AT_Status, doc="Status to count.");
Argument multiply(AT_Decimal, "1", doc="Multiply attribute value by this much.");
Argument multiply_sqrt(AT_Decimal, "0", doc="Add cost based on the square root of the attribute multiplied by this.");
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const override {
double value = obj.getStatusStackCountAny(status.integer);
cost += value * multiply.decimal;
if(multiply_sqrt.decimal != 0)
cost += sqrt(value) * multiply_sqrt.decimal;
}
};
class AddBuildCostTargetVar : ConstructionHook {
Document doc("Add build cost based on a ship variable of the target.");
Argument targ(TT_Object);
Argument variable(AT_SysVar, doc="Variable to add as build cost.");
Argument multiply(AT_Decimal, "1", doc="Multiply value by this much.");
int get(Object@ obj) const {
if(obj is null || !obj.isShip)
return 0;
auto@ design = cast<Ship>(obj).blueprint.design;
if(design is null)
return 0;
return design.total(SubsystemVariable(variable.integer)) * multiply.decimal;
}
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const override {
if(targs is null)
return;
auto@ objTarg = targ.fromConstTarget(targs);
if(objTarg is null || objTarg.obj is null)
return;
cost += get(objTarg.obj);
}
};
class AddLaborCostTargetVar : ConstructionHook {
Document doc("Add labor cost based on a ship variable of the target.");
Argument targ(TT_Object);
Argument variable(AT_SysVar, doc="Variable to add as labor cost.");
Argument multiply(AT_Decimal, "1", doc="Multiply value by this much.");
double get(Object@ obj) const {
if(obj is null || !obj.isShip)
return 0;
auto@ design = cast<Ship>(obj).blueprint.design;
if(design is null)
return 0;
return design.total(SubsystemVariable(variable.integer)) * multiply.decimal;
}
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const override {
if(targs is null)
return;
auto@ objTarg = targ.fromConstTarget(targs);
if(objTarg is null || objTarg.obj is null)
return;
cost += get(objTarg.obj);
}
};
+458
View File
@@ -0,0 +1,458 @@
import saving;
import hooks;
import util.formatting;
from resources import MoneyType;
#section server
from construction.Constructible import Constructible;
#section all
export ConstructionType, Construction;
export getConstructionTypeCount, getConstructionType;
export Targets, TargetType;
tidy class ConstructionType {
uint id = 0;
string ident;
string name;
string description;
string category;
Sprite icon;
Targets targets;
int buildCost = 0;
int maintainCost = 0;
double laborCost = 0;
double timeCost = 0;
bool alwaysBorrowable = false;
bool inContext = false;
array<IConstructionHook@> hooks;
string formatTooltip(Object& obj) const {
string tt = format("[font=Medium]$1[/font]\n$2\n", name, description);
int build = getBuildCost(obj);
int maint = getMaintainCost(obj);
if(build != 0 || maint != 0)
tt += format("[nl/][vspace=6/][img=ResourceIcon::0;22][b][color=#d1cb6a]$1:[/color][/b][offset=120]$2[/offset][/img]",
locale::COST, formatMoney(build, maint));
double labor = getLaborCost(obj);
if(labor != 0)
tt += format("[nl/][vspace=6/][img=ResourceIcon::6;22][b][color=#b1b4b6]$1:[/color][/b][offset=120]$2[/offset][/img]",
locale::RESOURCE_LABOR, standardize(labor, true));
double time = getTimeCost(obj);
if(time != 0)
tt += format("[nl/][vspace=6/][img=ContextIcons::1;22][b][color=#b1b4b6]$1:[/color][/b][offset=120]$2[/offset][/img]",
locale::BUILD_TIME, formatTime(time));
string vname, vvalue;
Sprite vicon;
Color color;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(hooks[i].getVariable(obj, this, vicon, vname, vvalue, color)) {
tt += format("[nl/][vspace=6/][img=$1;22][b][color=$4]$2:[/color][/b] [offset=110][hspace=10/]$3[/offset][/img]",
getSpriteDesc(vicon), vname, vvalue, toString(color));
color = colors::White;
}
}
return tt;
}
string formatCosts(Object& obj, const Targets@ targs = null) const {
string costs;
int build = getBuildCost(obj, targs);
int maint = getMaintainCost(obj, targs);
if(build != 0 || maint != 0)
costs += formatMoney(build, maint);
double labor = getLaborCost(obj, targs);
if(labor != 0) {
if(costs.length != 0)
costs += ", ";
costs += standardize(labor, true);
costs += " "+locale::RESOURCE_LABOR;
}
string value;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(hooks[i].formatCost(obj, this, targs, value)) {
if(costs.length != 0)
costs += ", ";
costs += value;
value = "";
}
}
return costs;
}
int getBuildCost(Object& obj, const Targets@ targs = null) const {
int cost = buildCost;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].getBuildCost(obj, this, targs, cost);
return cost;
}
int getMaintainCost(Object& obj, const Targets@ targs = null) const {
int cost = maintainCost;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].getMaintainCost(obj, this, targs, cost);
return cost;
}
double getLaborCost(Object& obj, const Targets@ targs = null) const {
double cost = laborCost;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].getLaborCost(obj, this, targs, cost);
return cost;
}
double getTimeCost(Object& obj, const Targets@ targs = null) const {
double cost = timeCost;
return cost;
}
bool checkTargets(Object& obj, const Targets@ check) const {
if(check is null) {
if(targets.length == 0)
return true;
else
return false;
}
if(check.targets.length != targets.length)
return false;
for(uint i = 0, cnt = check.targets.length; i < cnt; ++i) {
if(!isValidTarget(obj, i, check.targets[i]))
return false;
}
return true;
}
bool isValidTarget(Object& obj, uint index, const Target@ targ) const {
if(index >= targets.length)
return false;
if(targ.type != targets[index].type)
return false;
if(!targ.filled)
return false;
if(targets[index].filled && targets[index] != targ)
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].isValidTarget(obj, this, index, targ))
return false;
}
return true;
}
bool getTargetError(Object& obj, uint index, const Target@ targ, string& str) const {
if(index >= targets.length)
return false;
if(targ.type != targets[index].type)
return false;
if(!targ.filled)
return false;
if(targets[index].filled && targets[index] != targ)
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].isValidTarget(obj, this, index, targ)) {
str = hooks[i].getFailReason(obj, this, index, targ);
return true;
}
}
return false;
}
string getTargetError(Object& obj, const Targets@ check) const {
string str;
for(uint i = 0, cnt = check.targets.length; i < cnt; ++i) {
if(getTargetError(obj, i, check.targets[i], str))
return str;
}
return str;
}
bool canBuild(Object& obj, const Targets@ targs = null, bool ignoreCost = false) const {
if(targs !is null && !checkTargets(obj, targs))
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canBuild(obj, this, targs, ignoreCost))
return false;
}
if(!ignoreCost && !alwaysBorrowable) {
int build = getBuildCost(obj, targs);
if(!obj.owner.canPay(build))
return false;
}
return true;
}
};
interface IConstructionHook {
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const;
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const;
void finish(Construction@ cons, Constructible@ qitem, any@ data) const;
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const;
#section all
void save(Construction@ cons, any@ data, SaveFile& file) const;
void load(Construction@ cons, any@ data, SaveFile& file) const;
string getFailReason(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const;
bool isValidTarget(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const;
bool canBuild(Object& obj, const ConstructionType@ cons, const Targets@ targs, bool ignoreCost) const;
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const;
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const;
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const;
bool consume(Construction@ cons, any@ data, const Targets@ targs) const;
void reverse(Construction@ cons, any@ data, const Targets@ targs, bool cancel = false) const;
bool getVariable(Object& obj, const ConstructionType@ cons, Sprite& sprt, string& name, string& value, Color& color) const;
bool formatCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value) const;
bool getCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value, Sprite& icon) const;
}
class ConstructionHook : Hook, IConstructionHook {
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const {}
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const {}
void finish(Construction@ cons, Constructible@ qitem, any@ data) const {}
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {}
#section all
void save(Construction@ cons, any@ data, SaveFile& file) const {}
void load(Construction@ cons, any@ data, SaveFile& file) const {}
bool consume(Construction@ cons, any@ data, const Targets@ targs) const { return true; }
void reverse(Construction@ cons, any@ data, const Targets@ targs, bool cancel) const {}
string getFailReason(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return true; }
bool canBuild(Object& obj, const ConstructionType@ cons, const Targets@ targs, bool ignoreCost) const { return true; }
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const {}
bool getVariable(Object& obj, const ConstructionType@ cons, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
bool formatCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value) const { return false; }
bool getCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value, Sprite& icon) const { return false; }
};
tidy class Construction : Savable {
const ConstructionType@ type;
Object@ obj;
array<any> data;
Targets targets;
Construction() {
}
Construction(const ConstructionType@ type) {
@this.type = type;
data.length = type.hooks.length;
targets = Targets(type.targets);
}
void save(SaveFile& file) {
file.writeIdentifier(SI_ConstructionType, type.id);
file << obj;
file << targets;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].save(this, data[i], file);
}
void load(SaveFile& file) {
uint tid = file.readIdentifier(SI_ConstructionType);
@type = getConstructionType(tid);
data.length = type.hooks.length;
file >> obj;
file >> targets;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].load(this, data[i], file);
}
#section server
void start(Constructible@ qitem) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].start(this, qitem, data[i]);
}
void cancel(Constructible@ qitem) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
type.hooks[i].cancel(this, qitem, data[i]);
type.hooks[i].reverse(this, data[i], targets, true);
}
}
void finish(Constructible@ qitem) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].finish(this, qitem, data[i]);
if(qitem.maintainCost != 0)
obj.owner.modMaintenance(qitem.maintainCost, MoT_Misc);
}
void tick(Constructible@ qitem, double time) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].tick(this, qitem, data[i], time);
}
#section all
};
array<ConstructionType@> constructions;
dictionary constructionIdents;
int getConstructionID(const string& ident) {
ConstructionType@ type;
constructionIdents.get(ident, @type);
if(type !is null)
return int(type.id);
return -1;
}
string getConstructionIdent(int id) {
if(id < 0 || id >= int(constructions.length))
return "-";
return constructions[id].ident;
}
string getConstructionName(int id) {
if(id < 0 || id >= int(constructions.length))
return "-";
return constructions[id].name;
}
Sprite getConstructionIcon(int id) {
if(id < 0 || id >= int(constructions.length))
return Sprite();
return constructions[id].icon;
}
uint getConstructionTypeCount() {
return constructions.length;
}
const ConstructionType@ getConstructionType(uint id) {
if(id < constructions.length)
return constructions[id];
else
return null;
}
const ConstructionType@ getConstructionType(const string& name) {
ConstructionType@ cons;
constructionIdents.get(name, @cons);
return cons;
}
void addConstructionType(ConstructionType@ cons) {
cons.id = constructions.length;
constructions.insertLast(cons);
constructionIdents.set(cons.ident, @cons);
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = constructions.length; i < cnt; ++i) {
ConstructionType@ type = constructions[i];
file.addIdentifier(SI_ConstructionType, type.id, type.ident);
}
}
void parseLine(string& line, ConstructionType@ type, ReadFile@ file) {
//Hook line
auto@ hook = cast<IConstructionHook>(parseHook(line, "construction_effects::", instantiate=false, file=file));
if(hook !is null)
type.hooks.insertLast(hook);
}
void loadConstructions(const string& filename) {
ReadFile file(filename, true);
string key, value;
ConstructionType@ type;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
string line = file.line;
parseLine(line, type, file);
}
else if(key.equals_nocase("Construction")) {
if(type !is null)
addConstructionType(type);
@type = ConstructionType();
type.ident = value;
}
else if(type is null) {
file.error("Missing Construction ID line");
}
else if(key.equals_nocase("Name")) {
type.name = localize(value);
}
else if(key.equals_nocase("Description")) {
type.description = localize(value);
}
else if(key.equals_nocase("Icon")) {
type.icon = getSprite(value);
}
else if(key.equals_nocase("Target")) {
parseTarget(type.targets, value);
}
else if(key.equals_nocase("Build Cost")) {
type.buildCost = toInt(value);
}
else if(key.equals_nocase("Maintenance Cost")) {
type.maintainCost = toInt(value);
}
else if(key.equals_nocase("Labor Cost")) {
type.laborCost = toDouble(value);
}
else if(key.equals_nocase("Time Cost")) {
type.timeCost = toDouble(value);
}
else if(key.equals_nocase("Always Borrowable")) {
type.alwaysBorrowable = toBool(value);
}
else if(key.equals_nocase("Category")) {
type.category = value;
}
else if(key.equals_nocase("In Context")) {
type.inContext = toBool(value);
}
else {
string line = file.line;
parseLine(line, type, file);
}
}
if(type !is null)
addConstructionType(type);
}
void preInit() {
FileList list("data/constructions", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadConstructions(list.path[i]);
}
void init() {
for(uint i = 0, cnt = constructions.length; i < cnt; ++i) {
auto@ type = constructions[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n) {
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook "+addrstr(type.hooks[n])+" on construction "+type.ident);
else
cast<Hook>(type.hooks[n]).initTargets(type.targets);
}
}
}
+543
View File
@@ -0,0 +1,543 @@
import hooks;
import cargo;
import buildings;
from buildings import IBuildingHook;
import constructions;
from constructions import IConstructionHook;
import orbitals;
from orbitals import IOrbitalEffect;
import icons;
#section server
from construction.Constructible import Constructible;
#section all
class ConsumeEffect : Hook, IConstructionHook, IBuildingHook, IOrbitalEffect {
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
return true;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
return false;
}
bool consume(Object& obj, const Targets@ targs) const {
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel = false) const {
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
return false;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
return false;
}
//Buildings
uint hookIndex = 0;
void initialize(BuildingType@ type, uint index) { hookIndex = index; }
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void complete(Object& obj, SurfaceBuilding@ bld) const {}
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const {}
void remove(Object& obj, SurfaceBuilding@ bld) const {}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {}
void save(SurfaceBuilding@ bld, SaveFile& file) const {}
void load(SurfaceBuilding@ bld, SaveFile& file) const {}
bool canBuildOn(Object& obj, bool ignoreState = false) const { return canConsume(obj, null, ignoreState); }
bool canRemove(Object& obj) const { return true; }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color, bool isOption) const {
if(isOption)
return getVariable(obj, sprt, name, value, color);
return false;
}
bool consume(Object& obj) const { return consume(obj, null); }
void reverse(Object& obj) const { reverse(obj, null); }
void modBuildTime(Object& obj, double& time) const {}
bool canProgress(Object& obj) const { return true; }
//Orbitals
void onEnable(Orbital& obj, any@ data) const {}
void onDisable(Orbital& obj, any@ data) const {}
void onCreate(Orbital& obj, any@ data) const {}
void onDestroy(Orbital& obj, any@ data) const {}
void onTick(Orbital& obj, any@ data, double time) const {}
void onOwnerChange(Orbital& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {}
void onRegionChange(Orbital& obj, any@ data, Region@ prevRegion, Region@ newRegion) const {}
void onMakeGraphics(Orbital& obj, any@ data, OrbitalNode@ node) const {}
bool checkRequirements(OrbitalRequirements@ reqs, bool apply) const { return true; }
void revertRequirements(OrbitalRequirements@ reqs) const {}
bool canBuildBy(Object@ obj, bool ignoreCost = true) const { return canConsume(obj, null, ignoreCost); }
bool canBuildAt(Object@ obj, const vec3d& pos) const { return true; }
bool canBuildOn(Orbital& obj) const { return true; }
string getBuildError(Object@ obj, const vec3d& pos) const { return ""; }
bool shouldDisable(Orbital& obj, any@ data) const { return false; }
bool shouldEnable(Orbital& obj, any@ data) const { return true; }
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
void write(any@ data, Message& msg) const {}
void read(any@ data, Message& msg) const {}
void onKill(Orbital& obj, any@ data, Empire@ killedBy) const {}
bool getValue(Player& pl, Orbital& obj, any@ data, uint index, double& value) const { return false; }
bool sendValue(Player& pl, Orbital& obj, any@ data, uint index, double value) const { return false; }
bool getDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@& value) const { return false; }
bool sendDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@ value) const { return false; }
bool getObject(Player& pl, Orbital& obj, any@ data, uint index, Object@& value) const { return false; }
bool sendObject(Player& pl, Orbital& obj, any@ data, uint index, Object@ value) const { return false; }
bool getData(Orbital& obj, string& txt, bool enabled) const { return false; }
void reverse(Object& obj, bool cancel) const { reverse(obj, null, cancel); }
//Constructions
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const {}
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const {}
void finish(Construction@ cons, Constructible@ qitem, any@ data) const {}
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {}
#section all
void save(Construction@ cons, any@ data, SaveFile& file) const {}
void load(Construction@ cons, any@ data, SaveFile& file) const {}
bool consume(Construction@ cons, any@ data, const Targets@ targs) const { return consume(cons.obj, targs); }
void reverse(Construction@ cons, any@ data, const Targets@ targs, bool cancel) const { reverse(cons.obj, targs, cancel); }
string getFailReason(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return true; }
bool canBuild(Object& obj, const ConstructionType@ cons, const Targets@ targs, bool ignoreCost) const { return canConsume(obj, targs, ignoreCost); }
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const {}
bool getVariable(Object& obj, const ConstructionType@ cons, Sprite& sprt, string& name, string& value, Color& color) const {
return getVariable(obj, sprt, name, value, color);
}
bool formatCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value) const { return formatCost(obj, targs, value); }
bool getCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value, Sprite& icon) const { return getCost(obj, value, icon); }
};
class ConsumeFTL : ConsumeEffect {
Document doc("Requires a payment of FTL to build this construction.");
Argument cost("Amount", AT_Decimal, doc="FTL Cost.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(ignoreCost)
return true;
return obj.owner.FTLStored >= cost.decimal;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = format(locale::FTL_COST, toString(cost.decimal, 0));
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(cost.decimal, true);
icon = icons::FTL;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
if(obj.owner.consumeFTL(cost.decimal, partial=false, record=false) == 0.0)
return false;
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
if(!cancel)
obj.owner.modFTLStored(cost.decimal);
}
#section all
};
class ConsumeInfluence : ConsumeEffect {
Document doc("Requires a payment of influence to build this construction.");
Argument cost("Amount", AT_Integer, doc="Influence Cost.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(ignoreCost)
return true;
return obj.owner.Influence >= cost.integer;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = format(locale::RESOURCE_INFLUENCE, toString(cost.integer, 0));
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(cost.integer, true);
icon = icons::Influence;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
value = standardize(cost.integer, true);
sprt = icons::Influence;
name = locale::RESOURCE_INFLUENCE + " "+locale::COST;
color = colors::Influence;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
if(!obj.owner.consumeInfluence(cost.integer))
return false;
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
if(!cancel)
obj.owner.modInfluence(cost.integer);
}
#section all
};
class ConsumeResearch : ConsumeEffect {
Document doc("Requires a payment of Research to build this construction.");
Argument cost("Amount", AT_Integer, doc="Research Cost.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(ignoreCost)
return true;
return obj.owner.ResearchPoints >= cost.integer;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = toString(cost.integer, 0)+" "+locale::RESOURCE_RESEARCH;
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(cost.integer, true);
icon = icons::Research;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
value = standardize(cost.integer, true);
sprt = icons::Research;
name = locale::RESOURCE_RESEARCH + " "+locale::COST;
color = colors::Research;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
if(!obj.owner.consumeResearchPoints(cost.integer))
return false;
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
obj.owner.freeResearchPoints(cost.integer);
}
#section all
};
class ConsumeEnergy : ConsumeEffect {
Document doc("Requires a payment of Energy to build this construction.");
Argument cost("Amount", AT_Decimal, doc="Energy Cost.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(ignoreCost)
return true;
return obj.owner.EnergyStored >= cost.decimal;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = toString(cost.decimal, 0)+" "+locale::RESOURCE_ENERGY;
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(cost.decimal, true);
icon = icons::Energy;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
value = standardize(cost.decimal, true);
sprt = icons::Energy;
name = locale::RESOURCE_ENERGY + " "+locale::COST;
color = colors::Energy;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
if(obj.owner.consumeEnergy(cost.decimal, false) == 0.0)
return false;
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
if(!cancel)
obj.owner.modEnergyStored(cost.decimal);
}
#section all
};
class ConsumePopulation : ConsumeEffect {
Document doc("Requires a payment of Population to build this construction.");
Argument cost("Amount", AT_Decimal, doc="Population Cost.");
Argument allow_abandon(AT_Boolean, "False", doc="Whether to allow the planet to build this so it would go below 1 population and abandon.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(!obj.hasSurfaceComponent)
return false;
if(ignoreCost)
return true;
if(!allow_abandon.boolean)
return obj.population - 1.0 > cost.decimal;
return obj.population > cost.decimal;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = toString(cost.decimal, 0)+" "+locale::POPULATION;
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(cost.decimal, true);
icon = icons::Population;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
value = standardize(cost.decimal, true);
sprt = icons::Population;
name = locale::POPULATION + " "+locale::COST;
color = colors::White;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
if(!obj.hasSurfaceComponent)
return false;
double avail = obj.population;
if(!allow_abandon.boolean)
avail -= 1.0;
if(avail < cost.decimal)
return false;
obj.addPopulation(-cost.decimal);
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
if(!cancel)
obj.addPopulation(cost.decimal);
}
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {
if(allow_abandon.boolean && cons.obj.population <= 0.1)
cons.obj.forceAbandon();
}
#section all
};
class ConsumeCargo : ConsumeEffect {
Document doc("Requires a payment of cargo to build this construction.");
Argument type(AT_Cargo, doc="Type of cargo to take.");
Argument amount(AT_Decimal, doc="Amount of cargo taken to build.");
Argument hide(AT_Boolean, "False", doc="If the planet has _no_ cargo of this type, hide the project.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(!obj.hasCargo)
return false;
double val = obj.getCargoStored(type.integer);
if(hide.boolean && val < 0.001)
return false;
if(ignoreCost)
return true;
return val >= amount.decimal;
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = standardize(amount.decimal, true)+" "+getCargoType(type.integer).name;
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(amount.decimal, true);
icon = getCargoType(type.integer).icon;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
auto@ cargo = getCargoType(type.integer);
value = standardize(amount.decimal, true);
sprt = cargo.icon;
name = cargo.name + " "+locale::COST;
color = cargo.color;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
double consAmt = obj.consumeCargo(type.integer, amount.decimal, partial=false);
return consAmt >= amount.decimal - 0.001;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
obj.addCargo(type.integer, amount.decimal);
}
#section all
};
class ConsumeCargoAttribute : ConsumeEffect {
Document doc("Requires a payment of cargo to build this construction based on an attribute.");
Argument type(AT_Cargo, doc="Type of cargo to take.");
Argument attribute(AT_EmpAttribute, doc="Attribute to get value from.");
Argument base_amount(AT_Decimal, "0", doc="Base amount of cargo taken to build.");
Argument multiply(AT_Decimal, "1", doc="Multiply value of attribute.");
Argument hide(AT_Boolean, "False", doc="If the planet has _no_ cargo of this type, hide the project.");
double getCost(Empire& emp) {
return base_amount.decimal + emp.getAttribute(attribute.integer) * multiply.decimal;
}
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(!obj.hasCargo)
return false;
double val = obj.getCargoStored(type.integer);
if(hide.boolean && val < 0.001)
return false;
if(ignoreCost)
return true;
return val >= getCost(obj.owner);
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = standardize(getCost(obj.owner), true)+" "+getCargoType(type.integer).name;
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(getCost(obj.owner), true);
icon = getCargoType(type.integer).icon;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
auto@ cargo = getCargoType(type.integer);
value = standardize(getCost(obj.owner), true);
sprt = cargo.icon;
name = cargo.name + " "+locale::COST;
color = cargo.color;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
double cost = getCost(obj.owner);
double consAmt = obj.consumeCargo(type.integer, cost, partial=false);
return consAmt >= cost - 0.001;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
obj.addCargo(type.integer, getCost(obj.owner));
}
#section all
};
class ConsumeCargoStatusCount : ConsumeEffect {
Document doc("Requires a payment of cargo to build this construction, based on the amount of stacks of a status present.");
Argument type(AT_Cargo, doc="Type of cargo to take.");
Argument status(AT_Status, doc="Status to count.");
Argument amount(AT_Decimal, doc="Amount of cargo taken to build per status.");
Argument hide(AT_Boolean, "False", doc="If the planet has _no_ cargo of this type, hide the project.");
Argument allow_cancel(AT_Boolean, "False", doc="Refund the cost when canceling. Only use in specific circumstances when you know the status doesn't get added any other way.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(!obj.hasCargo)
return false;
double val = obj.getCargoStored(type.integer);
if(hide.boolean && val < 0.001)
return false;
if(ignoreCost)
return true;
return val >= get(obj);
}
double get(Object& obj) const {
return amount.decimal * obj.getStatusStackCountAny(status.integer);
}
bool formatCost(Object& obj, const Targets@ targs, string& value) const {
value = standardize(get(obj), true)+" "+getCargoType(type.integer).name;
return true;
}
bool getCost(Object& obj, string& value, Sprite& icon) const {
value = standardize(get(obj), true);
icon = getCargoType(type.integer).icon;
return true;
}
bool getVariable(Object& obj, Sprite& sprt, string& name, string& value, Color& color) const {
auto@ cargo = getCargoType(type.integer);
value = standardize(get(obj), true);
sprt = cargo.icon;
name = cargo.name + " "+locale::COST;
color = cargo.color;
return true;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
double consAmt = obj.consumeCargo(type.integer, get(obj), partial=false);
return consAmt >= amount.decimal - 0.001;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
double consAmt = get(obj);
if(!cancel || allow_cancel.boolean)
obj.addCargo(type.integer, consAmt);
}
#section all
};
class ConsumeStatus : ConsumeEffect {
Document doc("Consumes an instance of a status on the object.");
Argument type(AT_Status, doc="Type of status to take.");
Argument amount(AT_Integer, "1", doc="Amount of cargo taken to build per status.");
Argument hide(AT_Boolean, "False", doc="If the object has _no_ statuses of this type, hide the option.");
bool canConsume(Object& obj, const Targets@ targs, bool ignoreCost) const {
if(!obj.hasStatuses)
return false;
int val = obj.getStatusStackCountAny(type.integer);
if(hide.boolean && val < amount.integer)
return false;
if(ignoreCost)
return true;
return val >= amount.integer;
}
#section server
bool consume(Object& obj, const Targets@ targs) const override {
int count = obj.getStatusStackCount(type.integer);
if(count < amount.integer)
return false;
for(int i = 0; i < amount.integer; ++i)
obj.removeStatusInstanceOfType(type.integer);
return true;
}
void reverse(Object& obj, const Targets@ targs, bool cancel) const override {
obj.addStatus(type.integer);
}
#section all
};
+473
View File
@@ -0,0 +1,473 @@
#priority init 6000
import settings.game_settings;
import traits;
export EmpireColor, getEmpireColor, getEmpireColorCount;
array<EmpireColor@> colors;
final class EmpireColor {
uint id;
Color color;
const Material@ background;
string backgroundDef;
};
EmpireColor@ getEmpireColor(uint id) {
if(id >= colors.length)
return null;
return colors[id];
}
EmpireColor@ getEmpireColor(const Color& col) {
EmpireColor@ closest;
double dist = INFINITY;
for(uint i = 0, cnt = colors.length; i < cnt; ++i) {
double d = sqr(int(col.r) - int(colors[i].color.r));
d += sqr(int(col.g) - int(colors[i].color.g));
d += sqr(int(col.b) - int(colors[i].color.b));
if(d < dist) {
dist = d;
@closest = colors[i];
}
}
return closest;
}
uint getEmpireColorCount() {
return colors.length;
}
export EmpirePortrait, getEmpirePortrait, getEmpirePortraitCount;
array<EmpirePortrait@> portraits;
dictionary portraitIdents;
final class EmpirePortrait {
uint id;
string ident;
const Material@ portrait;
string portraitDef;
};
EmpirePortrait@ getEmpirePortrait(uint id) {
if(id >= portraits.length)
return null;
return portraits[id];
}
EmpirePortrait@ getEmpirePortrait(const string& ident) {
EmpirePortrait@ portrait;
portraitIdents.get(ident, @portrait);
return portrait;
}
uint getEmpirePortraitCount() {
return portraits.length;
}
export EmpireFlag, getEmpireFlag, getEmpireFlagCount;
array<EmpireFlag@> flags;
final class EmpireFlag {
uint id;
const Material@ flag;
string flagDef;
};
EmpireFlag@ getEmpireFlag(uint id) {
if(id >= flags.length)
return null;
return flags[id];
}
EmpireFlag@ getEmpireFlag(const string& ident) {
for(uint i = 0, cnt = flags.length; i < cnt; ++i)
if(flags[i].flagDef == ident)
return flags[i];
return null;
}
uint getEmpireFlagCount() {
return flags.length;
}
export EmpireWeaponSkin, getEmpireWeaponSkin, getEmpireWeaponSkinCount;
array<EmpireWeaponSkin@> skins;
final class EmpireWeaponSkin {
uint id;
Sprite icon;
string ident;
};
EmpireWeaponSkin@ getEmpireWeaponSkin(uint id) {
if(id >= skins.length)
return null;
return skins[id];
}
uint getEmpireWeaponSkinCount() {
return skins.length;
}
export RacePreset, getRacePreset, getRacePresetCount;
array<RacePreset@> presets;
final class RacePreset {
uint id;
string ident;
string name;
string tagline;
string description;
string lore;
string portrait;
string shipset;
string weaponSkin;
string dlc;
bool isHard = false;
bool aiSupport = true;
array<const Trait@> traits;
void apply(EmpireSettings& settings) const {
settings.raceName = name;
settings.portrait = portrait;
settings.traits = traits;
if(settings.shipset.length == 0)
settings.shipset = shipset;
settings.effectorSkin = weaponSkin;
}
bool equals(EmpireSettings& settings) const {
if(settings.raceName != name)
return false;
if(settings.portrait != portrait)
return false;
if(settings.traits != traits)
return false;
return true;
}
};
export exportRace, importRace, loadRaces;
const int RACE_SERIALIZE_VERSION = 1;
void exportRace(EmpireSettings& settings, const string& filename) {
JSONTree tree;
JSONNode@ root = tree.root.makeObject();
root["__VERSION__"] = RACE_SERIALIZE_VERSION;
root["name"] = settings.raceName;
root["portrait"] = settings.portrait;
root["weaponSkin"] = settings.effectorSkin;
root["shipset"] = settings.shipset;
JSONNode@ sysList = root["traits"].makeArray();
for(uint i = 0, cnt = settings.traits.length; i < cnt; ++i)
sysList.pushBack() = settings.traits[i].ident;
tree.writeFile(filename, true);
}
bool importRace(EmpireSettings& settings, const string& filename) {
JSONTree tree;
tree.readFile(filename);
JSONNode@ root = tree.root;
if(!root.isObject() || !root["name"].isString() || !root["portrait"].isString())
return false;
settings.raceName = root["name"].getString();
settings.portrait = root["portrait"].getString();
auto@ skinElem = root["weaponSkin"];
if(skinElem.isString())
settings.effectorSkin = skinElem.getString();
auto@ shipset = root["shipset"];
if(shipset.isString())
settings.shipset = shipset.getString();
JSONNode@ traits = root["traits"];
if(!traits.isArray())
return false;
settings.traits.length = 0;
uint cnt = traits.size();
for(uint i = 0; i < cnt; ++i) {
JSONNode@ node = traits[i];
if(!node.isString())
continue;
auto@ trait = getTrait(node.getString());
if(trait !is null && trait.available)
settings.traits.insertLast(trait);
}
return true;
}
void loadRaces(array<EmpireSettings@>& list, const string& folder, bool recursive = true) {
FileList files(folder, "*.race", recursive);
uint cnt = files.length;
for(uint i = 0; i < cnt; ++i) {
EmpireSettings settings;
if(importRace(settings, files.path[i]))
list.insertLast(settings);
}
}
RacePreset@ getRacePreset(uint id) {
if(id >= presets.length)
return null;
return presets[id];
}
uint getRacePresetCount() {
return presets.length;
}
export EmpirePortraitCreation;
class EmpirePortraitCreation {
array<EmpireColor@> availColors;
array<EmpirePortrait@> availPortraits;
array<EmpireFlag@> availFlags;
void reset() {
availColors.length = 0;
availPortraits.length = 0;
availFlags.length = 0;
}
void randomize(EmpireSettings& settings, bool fillOnly = false) {
if(settings.color.color == colors::White.color || !fillOnly) {
if(availColors.length == 0)
availColors = colors;
int index = 0;
settings.color = availColors[index].color;
availColors.removeAt(index);
}
if(settings.portrait == uint(-1) || !fillOnly) {
if(availPortraits.length == 0)
availPortraits = portraits;
int index = randomi(0, availPortraits.length-1);
settings.portrait = availPortraits[index].ident;
availPortraits.removeAt(index);
}
if(settings.flag == uint(-1) || !fillOnly) {
if(availFlags.length == 0)
availFlags = flags;
int index = randomi(0, availFlags.length-1);
settings.flag = availFlags[index].flagDef;
availFlags.removeAt(index);
}
}
void apply(EmpireSettings& settings, Empire@ emp) {
//Fill in the random variables
randomize(settings, fillOnly = true);
//Set materials
emp.color = settings.color;
auto@ color = getEmpireColor(emp.color);
emp.backgroundDef = color.backgroundDef;
@emp.background = color.background;
auto@ prt = getEmpirePortrait(settings.portrait);
if(prt is null)
@prt = getEmpirePortrait(emp.id % getEmpirePortraitCount());
emp.portraitDef = prt.portraitDef;
@emp.portrait = prt.portrait;
auto@ flag = getEmpireFlag(settings.flag);
if(flag is null)
@flag = getEmpireFlag(emp.id % getEmpireFlagCount());
emp.flagDef = flag.flagDef;
emp.flagID = flag.id;
@emp.flag = flag.flag;
}
};
void load(const string& filename) {
ReadFile file(filename, true);
EmpireColor@ prevColor;
EmpireWeaponSkin@ skin;
RacePreset@ prevPreset;
while(file++) {
if(file.key.equals_nocase("Color")) {
EmpireColor col;
col.id = colors.length;
col.color = toColor(file.value);
@prevColor = col;
colors.insertLast(col);
}
else if(file.key.equals_nocase("WeaponSkin")) {
if(file.indent > 0 && prevPreset !is null) {
prevPreset.weaponSkin = file.value;
}
else {
@skin = EmpireWeaponSkin();
skin.id = skins.length;
skin.ident = file.value;
skins.insertLast(skin);
}
}
else if(file.key.equals_nocase("Preset")) {
RacePreset preset;
preset.id = presets.length;
preset.ident = file.value;
@prevPreset = preset;
presets.insertLast(preset);
}
else if(file.key.equals_nocase("Name")) {
if(prevPreset !is null) {
prevPreset.name = localize(file.value);
}
else {
file.error("Name outside Preset block.");
}
}
else if(file.key.equals_nocase("Description")) {
if(prevPreset !is null) {
prevPreset.description = localize(file.value);
}
else {
file.error("Description outside Preset block.");
}
}
else if(file.key.equals_nocase("Tagline")) {
if(prevPreset !is null) {
prevPreset.tagline = localize(file.value);
}
else {
file.error("Tagline outside Preset block.");
}
}
else if(file.key.equals_nocase("Hard")) {
if(prevPreset !is null) {
prevPreset.isHard = toBool(file.value);
}
else {
file.error("Hard outside Preset block.");
}
}
else if(file.key.equals_nocase("DLC")) {
if(prevPreset !is null) {
prevPreset.dlc = file.value;
}
else {
file.error("DLC outside Preset block.");
}
}
else if(file.key.equals_nocase("AI Support")) {
if(prevPreset !is null) {
prevPreset.aiSupport = toBool(file.value);
}
else {
file.error("AI Support outside Preset block.");
}
}
else if(file.key.equals_nocase("Lore")) {
if(prevPreset !is null) {
prevPreset.lore = localize(file.value);
}
else {
file.error("TaLore outside Preset block.");
}
}
else if(file.key.equals_nocase("Icon")) {
if(skin !is null) {
skin.icon = getSprite(file.value);
}
else {
file.error("Icon outside WeaponSkin block.");
}
}
else if(file.key.equals_nocase("Portrait")) {
if(file.indent > 0 && prevPreset !is null) {
prevPreset.portrait = file.value;
}
}
else if(file.key.equals_nocase("Background")) {
if(prevColor !is null) {
prevColor.backgroundDef = file.value;
@prevColor.background = getMaterial(file.value);
}
else {
file.error("Background outside Color block.");
}
}
else if(file.key.equals_nocase("Shipset")) {
if(prevPreset is null) {
file.error("Shipset outside Preset block.");
}
else {
prevPreset.shipset = file.value;
}
}
else if(file.key.equals_nocase("Trait")) {
if(prevPreset is null) {
file.error("Trait outside Preset block.");
}
else {
auto@ trait = getTrait(file.value);
if(trait !is null)
prevPreset.traits.insertLast(trait);
else
file.error("Could not find trait: "+file.value);
}
}
}
}
void init() {
auto@ matFlags = getMatGroup("EmpireFlags");
for(uint i = 0, cnt = matFlags.materialCount; i < cnt; ++i) {
EmpireFlag flag;
flag.id = flags.length;
@flag.flag = matFlags.getMaterial(i);
flag.flagDef = matFlags.getMaterialName(i);
flags.insertLast(flag);
}
auto@ matPorts = getMatGroup("EmpirePortraits");
for(uint i = 0, cnt = matPorts.materialCount; i < cnt; ++i) {
EmpirePortrait prt;
prt.id = portraits.length;
prt.portraitDef = matPorts.getMaterialName(i);
prt.ident = prt.portraitDef;
@prt.portrait = matPorts.getMaterial(i);
portraits.insertLast(prt);
portraitIdents.set(prt.ident, @prt);
}
initTraits();
FileList list("data/empires", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
load(list.path[i]);
}
array<Color> EMPIRE_COLORS = {
Color(0x00c3ffff), //Blue
Color(0xff6c00ff), //Orange
Color(0x00ff9cff), //Teal
Color(0x884fffff), //Purple
Color(0xd6bf2fff), //Yellow
Color(0xd62f83ff), //Pink
Color(0x93d62fff), //Lime
Color(0x476bbaff), //Marine
};
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
import random_events;
import target_filters;
import bonus_effects;
class SelectRandomOwnedPlanet : RandomEventHook {
Document doc("When the event is triggered, fill the specified target with a random planet owned by the empire, meeting all target filters.");
Argument objTarget(TT_Object);
bool consider(CurrentEvent& evt) const override {
Target@ targ = objTarget.fromTarget(evt.targets);
if(targ.filled)
return true;
Object@ selected;
DataList@ objs = evt.owner.getPlanets();
Object@ obj;
double count = 0;
while(receive(objs, obj)) {
@targ.obj = obj;
targ.filled = true;
if(evt.isValidTarget(objTarget.integer, targ)) {
count += 1;
if(randomd() < 1.0 / count)
@selected = obj;
}
}
if(selected is null) {
targ.filled = false;
return false;
}
@targ.obj = selected;
targ.filled = true;
return true;
}
};
class SendZoomTo : RandomOptionHook {
Document doc("Tell the client to zoom to show this object when the option is triggered.");
Argument objTarget(TT_Object);
#section server
void trigger(CurrentEvent& evt, const EventOption& option, const Target@ on) const override {
Target@ targ = objTarget.fromTarget(evt.targets);
if(targ is null || targ.obj is null || evt.owner is null)
return;
Player@ pl = evt.owner.player;
if(pl !is null)
sendClientZoom(pl, targ.obj);
}
#section all
};
class SelectRandomEmpire : RandomEventHook {
Document doc("When the event is triggered, fill the specified target with a random empire.");
Argument empTarget(TT_Empire);
Argument require_contact(AT_Boolean, "True", doc="Whether to only select empires that are in contact with the event's owner.");
Argument allow_self(AT_Boolean, "False", doc="Whether to allow the owner of the effect to be selected.");
bool consider(CurrentEvent& evt) const override {
Target@ targ = empTarget.fromTarget(evt.targets);
if(targ.filled)
return true;
Empire@ selected;
Empire@ owner = evt.owner;
double count = 0;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
@targ.emp = getEmpire(i);
targ.filled = true;
if(!targ.emp.major)
continue;
if(require_contact.boolean && owner.ContactMask & targ.emp.mask == 0)
continue;
if(!allow_self.boolean && owner is targ.emp)
continue;
if(!evt.isValidTarget(empTarget.integer, targ))
continue;
count += 1;
if(randomd() < 1.0 / count)
@selected = targ.emp;
}
if(selected is null) {
targ.filled = false;
return false;
}
@targ.emp = selected;
targ.filled = true;
return true;
}
};
+378
View File
@@ -0,0 +1,378 @@
#section server-side
from regions.regions import getRegion;
#section all
import orbitals;
const double HYPERDRIVE_COST = 0.08;
const double HYPERDRIVE_START_COST = 25.0;
const double HYPERDRIVE_CHARGE_TIME = 15.0;
bool canHyperdrive(Object& obj) {
Ship@ ship = cast<Ship>(obj);
if(ship is null || !ship.hasLeaderAI)
return false;
if(isFTLBlocked(ship))
return false;
return ship.blueprint.hasTagActive(ST_Hyperdrive);
}
double hyperdriveSpeed(Object& obj) {
Ship@ ship = cast<Ship>(obj);
return ship.blueprint.getEfficiencySum(SV_HyperdriveSpeed);
}
double hyperdriveMaxSpeed(Object& obj) {
Ship@ ship = cast<Ship>(obj);
return ship.blueprint.design.total(SV_HyperdriveSpeed);
}
int hyperdriveCost(Object& obj, const vec3d& position) {
Ship@ ship = cast<Ship>(obj);
if(ship is null)
return 0;
auto@ dsg = ship.blueprint.design;
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return 0;
return ceil(log(dsg.size) * (dsg.total(HV_Mass)*0.5/dsg.size) * sqrt(position.distanceTo(obj.position)) * HYPERDRIVE_COST + HYPERDRIVE_START_COST + owner.HyperdriveStartCostMod) * owner.FTLCostFactor;
}
int hyperdriveCost(array<Object@>& objects, const vec3d& destination) {
int cost = 0;
for(uint i = 0, cnt = objects.length; i < cnt; ++i) {
if(!canHyperdrive(objects[i]))
continue;
cost += hyperdriveCost(objects[i], destination);
}
return cost;
}
double hyperdriveRange(Object& obj) {
Ship@ ship = cast<Ship>(obj);
if(ship is null)
return 0.0;
int scale = ship.blueprint.design.size;
return hyperdriveRange(obj, scale, playerEmpire.FTLStored);
}
double hyperdriveRange(Object& obj, int scale, int stored) {
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return INFINITY;
return sqr(max(double(stored) - (HYPERDRIVE_START_COST - owner.HyperdriveStartCostMod) * owner.FTLCostFactor, 0.0) / (log(double(scale)) * HYPERDRIVE_COST * owner.FTLCostFactor));
}
bool canHyperdriveTo(Object& obj, const vec3d& pos) {
return !isFTLBlocked(obj, pos);
}
const double FLING_BEACON_RANGE = 12500.0;
const double FLING_BEACON_RANGE_SQ = sqr(FLING_BEACON_RANGE);
const double FLING_COST = 8.0;
const double FLING_CHARGE_TIME = 15.0;
const double FLING_TIME = 15.0;
bool canFling(Object& obj) {
if(isFTLBlocked(obj))
return false;
if(!obj.hasLeaderAI)
return false;
if(obj.isShip) {
return true;
}
else {
if(obj.isOrbital) {
if(obj.owner.isFlingBeacon(obj))
return false;
Orbital@ orb = cast<Orbital>(obj);
auto@ core = getOrbitalModule(orb.coreModule);
return core is null || core.canFling;
}
if(obj.isPlanet)
return true;
return false;
}
}
bool canFlingTo(Object& obj, const vec3d& pos) {
return !isFTLBlocked(obj, pos);
}
double flingSpeed(Object& obj, const vec3d& pos) {
return obj.position.distanceTo(pos) / FLING_TIME;
}
int flingCost(Object& obj, vec3d position) {
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return 0;
if(obj.isShip) {
Ship@ ship = cast<Ship>(obj);
auto@ dsg = ship.blueprint.design;
int scale = dsg.size;
double massFactor = dsg.total(HV_Mass) * 0.3/dsg.size;
double scaleFactor;
if(dsg.hasTag(ST_Station))
scaleFactor = pow(double(scale), 0.75);
else
scaleFactor = sqrt(double(scale));
return ceil(FLING_COST * scaleFactor * massFactor * owner.FTLCostFactor);
}
else {
if(obj.isOrbital)
return ceil(FLING_COST * obj.radius * 3.0 * owner.FTLCostFactor);
else if(obj.isPlanet)
return ceil(FLING_COST * obj.radius * 30.0 * owner.FTLCostFactor);
return INFINITY;
}
}
int flingCost(array<Object@>& objects, const vec3d& destination) {
int cost = 0;
for(uint i = 0, cnt = objects.length; i < cnt; ++i)
cost += flingCost(objects[i], destination);
return cost;
}
double flingRange(Object& obj) {
if(flingCost(obj, obj.position) > obj.owner.FTLStored)
return 0.0;
return INFINITY;
}
const double SLIPSTREAM_CHARGE_TIME = 15.0;
const double SLIPSTREAM_LIFETIME = 10.0 * 60.0;
bool canSlipstream(Object& obj) {
Ship@ ship = cast<Ship>(obj);
if(ship is null || !ship.hasLeaderAI)
return false;
if(isFTLBlocked(ship))
return false;
return ship.blueprint.hasTagActive(ST_Slipstream);
}
int slipstreamCost(Object& obj, int scale, double distance) {
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return 0;
Ship@ ship = cast<Ship>(obj);
double baseCost = ship.blueprint.design.total(SV_SlipstreamCost);
double optDist = ship.blueprint.design.total(SV_SlipstreamOptimalDistance);
if(distance < optDist)
return baseCost * obj.owner.FTLCostFactor;
return baseCost * ceil(distance / optDist) * obj.owner.FTLCostFactor;
}
double slipstreamRange(Object& obj, int scale, int stored) {
Ship@ ship = cast<Ship>(obj);
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return INFINITY;
double baseCost = ship.blueprint.design.total(SV_SlipstreamCost);
double optDist = ship.blueprint.design.total(SV_SlipstreamOptimalDistance);
if(stored < baseCost)
return 0.0;
return floor(double(stored) / baseCost / obj.owner.FTLCostFactor) * optDist;
}
double slipstreamLifetime(Object& obj) {
Ship@ ship = cast<Ship>(obj);
return ship.blueprint.getEfficiencyFactor(SV_SlipstreamDuration) * ship.blueprint.design.total(SV_SlipstreamDuration);
}
void slipstreamModifyPosition(Object& obj, vec3d& position) {
double radius = slipstreamInaccuracy(obj, position);
vec2d offset = random2d(radius);
position += vec3d(offset.x, randomd(-radius * 0.2, radius * 0.2), offset.y);
}
double slipstreamInaccuracy(Object& obj, const vec3d& position) {
double dist = obj.position.distanceTo(position);
return dist * 0.01;
}
bool canSlipstreamTo(Object& obj, const vec3d& point) {
auto@ reg = obj.region;
if(reg !is null) {
if(reg.BlockFTLMask & obj.owner.mask != 0)
return false;
}
@reg = getRegion(point);
if(reg !is null) {
if(reg.BlockFTLMask & obj.owner.mask != 0)
return false;
}
return true;
}
bool isFTLBlocked(Object& obj, const vec3d& point) {
auto@ reg = getRegion(point);
if(reg is null)
return false;
if(reg.BlockFTLMask & obj.owner.mask != 0)
return true;
return false;
}
bool isFTLBlocked(Object& obj) {
auto@ reg = obj.region;
if(reg is null)
return false;
if(reg.BlockFTLMask & obj.owner.mask != 0)
return true;
return false;
}
const double JUMPDRIVE_COST = 0.06;
const double JUMPDRIVE_START_COST = 50.0;
const double JUMPDRIVE_CHARGE_TIME = 25.0;
bool canJumpdrive(Object& obj) {
Ship@ ship = cast<Ship>(obj);
if(ship is null || !ship.hasLeaderAI)
return false;
if(isFTLBlocked(ship))
return false;
return ship.blueprint.hasTagActive(ST_Jumpdrive);
}
int jumpdriveCost(Object& obj, const vec3d& fromPos, const vec3d& position) {
Ship@ ship = cast<Ship>(obj);
if(ship is null)
return 0;
auto@ dsg = ship.blueprint.design;
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return 0;
double dist = position.distanceTo(fromPos);
dist = min(dist, jumpdriveRange(obj));
return ceil(log(dsg.size) * (dsg.total(HV_Mass)*0.5/dsg.size) * sqrt(dist) * JUMPDRIVE_COST + JUMPDRIVE_START_COST) * owner.FTLCostFactor;
}
int jumpdriveCost(Object& obj, const vec3d& position) {
Ship@ ship = cast<Ship>(obj);
if(ship is null)
return 0;
auto@ dsg = ship.blueprint.design;
Region@ reg = obj.region;
Empire@ owner = obj.owner;
if(reg !is null && owner !is null && reg.FreeFTLMask & owner.mask != 0)
return 0;
double dist = position.distanceTo(obj.position);
dist = min(dist, jumpdriveRange(obj));
return ceil(log(dsg.size) * (dsg.total(HV_Mass)*0.5/dsg.size) * sqrt(dist) * JUMPDRIVE_COST + JUMPDRIVE_START_COST) * owner.FTLCostFactor;
}
int jumpdriveCost(array<Object@>& objects, const vec3d& destination) {
int cost = 0;
for(uint i = 0, cnt = objects.length; i < cnt; ++i) {
if(!canHyperdrive(objects[i]))
continue;
cost += jumpdriveCost(objects[i], destination);
}
return cost;
}
double jumpdriveRange(Object& obj) {
Ship@ ship = cast<Ship>(obj);
return ship.blueprint.design.total(SV_JumpRange);
}
double jumpdriveRange(Object& obj, int scale, int stored) {
Ship@ ship = cast<Ship>(obj);
return ship.blueprint.design.total(SV_JumpRange);
}
bool canJumpdriveTo(Object& obj, const vec3d& pos) {
return !isFTLBlocked(obj, pos);
}
const double FLUX_CD_RANGE = 300.0;
bool canFluxTo(Object& obj, const vec3d& pos) {
if(obj.owner.HasFlux == 0)
return false;
auto@ reg = getRegion(pos);
auto@ curReg = obj.region;
if(curReg is null)
return false;
if(reg is null)
return false;
if(reg is curReg)
return false;
if(reg.VisionMask & obj.owner.mask == 0)
return false;
if(isFTLBlocked(obj) || isFTLBlocked(obj, pos))
return false;
if(obj.hasStatuses) {
if(obj.hasStatusEffect(fluxStatus))
return false;
}
return true;
}
vec3d getFluxDest(Object& obj, const vec3d& pos) {
auto@ reg = getRegion(pos);
auto@ curReg = obj.region;
vec3d dir;
if(curReg !is null)
dir = (obj.position - curReg.position) / curReg.radius;
else
dir = random3d(0.6);
if(reg !is null)
return reg.position + (dir * reg.radius);
else
return pos;
}
from statuses import getStatusID;
int fluxStatus = -1;
void init() {
fluxStatus = getStatusID("FluxCooldown");
}
#section server-side
void commitFlux(Object& obj, const vec3d& pos) {
vec3d fluxPos = getFluxDest(obj, pos);
#section server
playParticleSystem("FluxJump", obj.position, obj.rotation, obj.radius * 4.0, obj.visibleMask);
playParticleSystem("FluxJump", fluxPos, obj.rotation, obj.radius * 4.0, obj.visibleMask);
#section server-side
if(obj.hasStatuses) {
double dist = fluxPos.distanceTo(obj.position);
double cd = dist / FLUX_CD_RANGE;
obj.addStatus(fluxStatus, timer=cd);
}
if(obj.hasLeaderAI) {
obj.teleportTo(fluxPos, movementPart=true);
}
else {
obj.position = fluxPos;
obj.velocity = vec3d();
obj.acceleration = vec3d();
}
}
#section all
@@ -0,0 +1,629 @@
#priority init 1500
import generic_hooks;
from bonus_effects import BonusEffect;
import resources;
#section server
import systems;
import regions.regions;
import object_creation;
import attributes;
import oddity_navigation;
const ResourceClass@ foodClass;
const ResourceClass@ waterClass;
const ResourceClass@ scalableClass;
void init() {
@foodClass = getResourceClass("Food");
@waterClass = getResourceClass("WaterType");
@scalableClass = getResourceClass("Scalable");
coordination.length = getEmpireCount();
}
void EGCoordinationTick(Empire& emp, double time) {
auto@ coord = getCoordinate(emp);
if(coord !is null)
coord.tick(emp, time);
}
bool checkSlot(uint index, const ResourceType@ resource) {
switch(index) {
case 0:
return resource.cls is foodClass;
case 1:
return resource.cls is waterClass;
case 2:
return resource.level == 1;
case 3:
return resource.level == 2;
}
return false;
}
final class Coordinate : Savable {
Mutex mtx;
array<Planet@> slots(4);
double sendTimer = 0.0;
set_int targetIds;
array<Planet@> curTargets;
array<ColonyShip@> curShips;
set_int penaltyIds;
array<Planet@> curPenalties;
array<double> penaltiesUntil;
array<RefugeeData@> spreading;
void tick(Empire& emp, double time) {
if(spreading.length == 0)
return;
Lock lck(mtx);
//Update colony targets
for(int i = curTargets.length-1; i >= 0; --i) {
Planet@ pl = curTargets[i];
ColonyShip@ colShip = curShips[i];
if(colShip is null || !colShip.valid || pl is null || !pl.valid) {
curTargets.removeAt(i);
curShips.removeAt(i);
if(pl !is null) {
targetIds.erase(pl.id);
Empire@ owner = pl.owner;
if(owner !is emp && owner !is null && owner.valid) {
if(!penaltyIds.contains(pl.id)) {
curPenalties.insertLast(pl);
penaltiesUntil.insertLast(gameTime + 90.0);
penaltyIds.insert(pl.id);
}
}
}
}
}
//Update colony penalties
double curTime = gameTime;
for(int i = curPenalties.length-1; i >= 0; --i) {
if(curTime >= penaltiesUntil[i]) {
if(curPenalties[i] !is null)
penaltyIds.erase(curPenalties[i].id);
penaltiesUntil.removeAt(i);
curPenalties.removeAt(i);
}
}
//Manage resource type slots
for(uint i = 0, cnt = slots.length; i < cnt; ++i) {
Planet@ pl = slots[i];
if(pl is null)
continue;
if(!pl.valid) {
@slots[i] = null;
continue;
}
Empire@ owner = pl.owner;
if(owner !is emp && owner !is null) {
if(owner.valid) {
@slots[i] = null;
continue;
}
else if(!targetIds.contains(pl.id)) {
@slots[i] = null;
continue;
}
}
if(owner is emp && pl.primaryResourceUsable) {
uint resLevel = pl.primaryResourceLevel;
uint plLevel = pl.level;
if(resLevel >= 2 || plLevel > resLevel || pl.primaryResourceExported) {
@slots[i] = null;
continue;
}
}
}
//Send colonizations
double speed = 1.0;
speed *= max(pow(emp.TotalPopulation / 10.0, 0.6), 1.0);
//Slow down expansion speed for lower difficulty AIs
if(emp.isAI) {
int diff = emp.difficulty;
if(diff == 0)
speed *= 0.3;
else if(diff == 1)
speed *= 0.65;
}
sendTimer -= time * speed;
if(sendTimer <= 0.0) {
Planet@ bestPlanet;
RefugeeData@ bestBeacon;
double bestWeight = 0.0;
uint cnt = spreading.length;
uint offset = randomi(0, cnt-1);
for(uint i = 0; i < cnt; ++i) {
uint index = (i+offset) % cnt;
auto@ rd = spreading[index];
if(rd.obj is null || !rd.obj.valid) {
spreading.removeAt(index);
--i; --cnt;
continue;
}
Planet@ pl = rd.nextTarget;
if(pl !is null) {
double w = getWeight(emp, rd, pl);
if(rd.lastBeacon)
w *= 0.9;
if(w > bestWeight) {
@bestPlanet = pl;
@bestBeacon = rd;
bestWeight = w;
}
}
rd.lastBeacon = false;
}
if(bestPlanet !is null) {
send(bestBeacon.obj, bestPlanet);
@bestBeacon.nextTarget = null;
bestBeacon.lastBeacon = true;
sendTimer += 60.0;
}
}
}
double getWeight(Empire& emp, RefugeeData& rd, Planet& pl) {
Empire@ owner = pl.visibleOwnerToEmp(emp);
double w = 1.0;
//Deal with sending population to planets that aren't full
if(owner is emp) {
double curPop = pl.population;
double maxPop = pl.maxPopulation;
if(curPop >= maxPop - 0.0001)
return 0.0;
//Track how much population we're currently sending
for(uint j = 0, jcnt = curTargets.length; j < jcnt; ++j) {
if(curTargets[j] is pl)
curPop += 1.0;
}
if(curPop < double(maxPop) - 0.0001)
w *= 200.0;
else
return 0.0;
}
else if(owner is null || owner.valid) {
return 0.0;
}
else {
//Don't target quarantined planets
if(pl.quarantined)
return 0.0;
//Don't colonize twice
if(targetIds.contains(pl.id))
return 0.0;
if(penaltyIds.contains(pl.id))
return 0.0;
}
//Deal with slots for particular types of resources
auto@ resource = getResource(pl.primaryResourceType);
if(resource is null)
return 0.0;
for(uint i = 0, cnt = slots.length; i < cnt; ++i) {
if(slots[i] !is null)
continue;
if(checkSlot(i, resource)) {
w *= 100.0;
break;
}
}
//Deal with generic resource value
if(resource.cls is foodClass)
w *= 1.5;
else if(resource.cls is waterClass)
w *= 1.5;
w /= ceil(pl.position.distanceTo(rd.obj.position) / 5000.0);
return w;
}
void save(SaveFile& file) {
file << sendTimer;
for(uint i = 0, cnt = slots.length; i < cnt; ++i)
file << slots[i];
uint cnt = curTargets.length;
file << cnt;
for(uint i = 0; i < cnt; ++i) {
file << curTargets[i];
file << curShips[i];
}
cnt = curPenalties.length;
file << cnt;
for(uint i = 0; i < cnt; ++i) {
file << curPenalties[i];
file << penaltiesUntil[i];
}
}
void load(SaveFile& file) {
file >> sendTimer;
for(uint i = 0, cnt = slots.length; i < cnt; ++i)
file >> slots[i];
uint cnt = 0;
file >> cnt;
for(uint i = 0; i < cnt; ++i) {
Planet@ targ;
ColonyShip@ ship;
file >> targ;
file >> ship;
if(targ !is null && ship !is null) {
curTargets.insertLast(targ);
curShips.insertLast(ship);
targetIds.insert(targ.id);
}
}
file >> cnt;
for(uint i = 0; i < cnt; ++i) {
Planet@ targ;
double until = 0.0;
file >> targ;
file >> until;
if(targ !is null) {
curPenalties.insertLast(targ);
penaltiesUntil.insertLast(until);
penaltyIds.insert(targ.id);
}
}
}
void send(Empire& emp, Planet@ toPlanet) {
Object@ best;
double bestDist = INFINITY;
for(uint i = 0, cnt = spreading.length; i < cnt; ++i) {
Object@ obj = spreading[i].obj;
if(obj is null || !obj.valid)
continue;
double d = getPathDistance(emp, obj.position, toPlanet.position);
if(d < bestDist) {
@best = obj;
bestDist = d;
}
}
if(best !is null)
send(best, toPlanet);
}
void send(Object@ obj, Planet@ bestPlanet) {
auto@ resource = getResource(bestPlanet.primaryResourceType);
if(resource !is null) {
for(uint i = 0, cnt = slots.length; i < cnt; ++i) {
if(slots[i] !is null)
continue;
if(checkSlot(i, resource)) {
@slots[i] = bestPlanet;
break;
}
}
}
auto@ colShip = createColonizer(obj, bestPlanet, 1.0, 1.0);
if(colShip !is null) {
curTargets.insertLast(bestPlanet);
curShips.insertLast(colShip);
targetIds.insert(bestPlanet.id);
}
}
};
void save(SaveFile& file) {
uint cnt = coordination.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file << coordination[i];
}
void load(SaveFile& file) {
uint cnt = 0;
file >> cnt;
coordination.length = cnt;
for(uint i = 0; i < cnt; ++i)
file >> coordination[i];
}
array<Coordinate> coordination;
Coordinate@ getCoordinate(Empire@ emp) {
if(emp is null)
return null;
if(uint(emp.index) >= coordination.length)
return null;
return coordination[emp.index];
}
final class SysData {
Region@ region;
array<Planet@> planets;
};
final class RefugeeData : Savable {
Object@ obj;
double updateTimer = 0.0;
bool lastBeacon = false;
bool registered = false;
Planet@ nextTarget;
array<SysData@>@ systems;
array<SysData@>@ updateData;
bool foundGate = false;
uint sysUpdate = 0;
void save(SaveFile& file) {
file << obj;
file << updateTimer;
file << lastBeacon;
}
void load(SaveFile& file) {
file >> obj;
file >> updateTimer;
file >> lastBeacon;
}
};
#section all
class RefugeeColonization : GenericEffect {
Document doc("Automatically sends population to nearby planets with colony/refugee ships.");
#section server
void enable(Object& obj, any@ data) const override {
RefugeeData rd;
@rd.obj = obj;
data.store(@rd);
{
auto@ coord = getCoordinate(obj.owner);
Lock lck(coord.mtx);
coord.spreading.insertLast(rd);
rd.registered = true;
}
}
void disable(Object& obj, any@ data) const override {
RefugeeData@ rd;
data.retrieve(@rd);
if(rd !is null) {
auto@ coord = getCoordinate(obj.owner);
Lock lck(coord.mtx);
coord.spreading.remove(rd);
rd.registered = false;
}
}
void ownerChange(Object& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {
RefugeeData@ rd;
data.retrieve(@rd);
if(prevOwner !is null) {
auto@ coord = getCoordinate(prevOwner);
Lock lck(coord.mtx);
coord.spreading.remove(rd);
}
if(newOwner !is null) {
auto@ coord = getCoordinate(newOwner);
Lock lck(coord.mtx);
coord.spreading.insertLast(rd);
rd.registered = true;
}
}
void tick(Object& obj, any@ data, double time) const override {
RefugeeData@ rd;
data.retrieve(@rd);
if(rd.nextTarget is null)
rd.updateTimer -= time * 10.0;
else
rd.updateTimer -= time;
if(!rd.registered) {
auto@ coord = getCoordinate(obj.owner);
if(coord !is null) {
Lock lck(coord.mtx);
rd.registered = true;
coord.spreading.insertLast(rd);
}
}
if(rd.updateTimer <= 0.0 && rd.systems !is null) {
rd.updateTimer += randomd(10.0, 20.0);
Empire@ emp = obj.owner;
auto@ coord = getCoordinate(emp);
Lock lck(coord.mtx);
//Send colonizations
Region@ reg = obj.region;
if(reg is null)
@reg = findNearestRegion(obj.position);
Planet@ bestPlanet;
double bestWeight = 0.0;
for(uint i = 0, cnt = rd.systems.length; i < cnt; ++i) {
auto@ sys = rd.systems[i];
for(uint n = 0, ncnt = sys.planets.length; n < ncnt; ++n) {
Planet@ pl = sys.planets[n];
double w = coord.getWeight(emp, rd, pl);
if(w > bestWeight) {
bestWeight = w;
@bestPlanet = pl;
}
}
}
@rd.nextTarget = bestPlanet;
}
//Update our internal representation of the surrounding area
if(rd.updateData is null || rd.sysUpdate >= rd.updateData.length) {
if(rd.updateData !is null)
@rd.systems = rd.updateData;
@rd.updateData = array<SysData@>();
rd.sysUpdate = 0;
rd.foundGate = false;
Region@ reg = obj.region;
if(reg is null)
@reg = findNearestRegion(obj.position);
set_int visited;
visitSystem(obj.owner, rd, reg, visited);
}
else {
updateSystem(obj.owner, rd, rd.updateData[rd.sysUpdate]);
rd.sysUpdate += 1;
}
}
void updateSystem(Empire& emp, RefugeeData& rd, SysData& sys) const {
if(sys.region.planetCount == sys.planets.length)
return;
sys.planets.length = 0;
auto@ datalist = sys.region.getPlanets();
Object@ obj;
while(receive(datalist, obj)) {
Planet@ pl = cast<Planet>(obj);
if(pl !is null)
sys.planets.insertLast(pl);
}
}
void visitSystem(Empire& emp, RefugeeData& rd, Region& reg, set_int& visited) const {
visited.insert(reg.id);
bool found = false;
if(rd.systems !is null) {
for(uint i = 0, cnt = rd.systems.length; i < cnt; ++i) {
if(rd.systems[i].region is reg) {
rd.updateData.insertLast(rd.systems[i]);
found = true;
break;
}
}
}
if(!found) {
SysData sd;
@sd.region = reg;
rd.updateData.insertLast(sd);
}
uint curPresent = reg.PlanetsMask;
bool isBorder = curPresent & ~(emp.mask | emp.ForcedPeaceMask.value) != 0;
bool isEmpty = curPresent & emp.mask == 0;
auto@ system = getSystem(reg);
for(uint i = 0, cnt = system.spatialAdjacentCount; i < cnt; ++i) {
auto@ other = getSystem(system.spatialAdjacent[i]);
if(other is null)
continue;
if(other.object.SeenMask & emp.mask == 0)
continue;
if(visited.contains(other.object.id))
continue;
uint present = other.object.PlanetsMask;
if(present & emp.mask == 0) {
if(present & ~emp.ForcedPeaceMask.value != 0 && isBorder)
continue;
if(isEmpty)
continue;
}
visitSystem(emp, rd, other.object, visited);
}
//Can't do this: beacons themselves are gatemask for trade even though they can't port
//if(!rd.foundGate && reg.GateMask & emp.mask != 0 && !isEmpty) {
// rd.foundGate = true;
// for(uint i = 0, cnt = systemCount; i < cnt; ++i) {
// auto@ sys = getSystem(i);
// if(sys.object.GateMask & emp.mask == 0)
// continue;
// if(sys.object is reg)
// continue;
// if(visited.contains(sys.object.id))
// continue;
// visitSystem(emp, rd, sys.object, visited);
// }
//}
}
void save(any@ data, SaveFile& file) const override {
RefugeeData@ rd;
data.retrieve(@rd);
if(data !is null)
file << rd;
else
file << RefugeeData();
}
void load(any@ data, SaveFile& file) const override {
RefugeeData rd;
file >> rd;
data.store(@rd);
}
#section all
};
class TriggerRefugees : BonusEffect {
Document doc("Immediately trigger the next refugee ship to leave to the targeted planet.");
#section server
void activate(Object@ target, Empire@ emp) const override {
if(emp is null)
return;
if(target is null || !target.isPlanet)
return;
auto@ coord = getCoordinate(emp);
{
Lock lck(coord.mtx);
coord.send(emp, cast<Planet>(target));
}
}
#section all
};
File diff suppressed because it is too large Load Diff
+362
View File
@@ -0,0 +1,362 @@
import buildings;
from buildings import IBuildingHook;
import resources;
import anomalies;
import camps;
import research;
import buildings;
import artifacts;
import random_events;
import util.formatting;
import systems;
import saving;
import influence;
from attitudes import Attitude, IAttitudeHook;
from influence import InfluenceStore, IInfluenceEffectEffect;
from statuses import IStatusHook, Status, StatusInstance;
from resources import integerSum, decimalSum;
from traits import ITraitEffect;
from influence import InfluenceStore;
from pickups import IPickupHook;
from anomalies import IAnomalyHook;
from abilities import Ability, IAbilityHook;
from research import ITechnologyHook;
import constructions;
from constructions import IConstructionHook;
import orbitals;
from orbitals import IOrbitalEffect;
import attributes;
import hook_globals;
import research;
#section server
from construction.Constructible import Constructible;
#section all
tidy class GenericEffect : Hook, IResourceHook, IBuildingHook, IStatusHook, IOrbitalEffect, SubsystemHook, RegionChangeable, LeaderChangeable {
uint hookIndex = 0;
//Generic reusable hooks
void enable(Object& obj, any@ data) const {}
void disable(Object& obj, any@ data) const {}
void tick(Object& obj, any@ data, double time) const {}
void ownerChange(Object& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {}
void regionChange(Object& obj, any@ data, Region@ fromRegion, Region@ toRegion) const {}
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
//Lets this be used as a resource hook
void initialize(ResourceType@ type, uint index) { hookIndex = index; }
bool canTerraform(Object@ from, Object@ to) const { return true; }
void applyGraphics(Object& obj, Node& node) const {}
void onTerritoryAdd(Object& obj, Resource@ r, Territory@ terr) const {}
void onTerritoryRemove(Object& obj, Resource@ r, Territory@ terr) const {}
bool get_hasEffect() const { return false; }
bool mergesEffect(Object& obj, const IResourceHook@ other) const {
if(getClass(other) !is getClass(this))
return false;
return mergesEffect(cast<const GenericEffect>(other));
}
bool mergesEffect(const GenericEffect@ eff) const { return true; }
string formatEffect(Object& obj, array<const IResourceHook@>& hooks) const { return "---"; }
const IResourceHook@ get_carriedHook() const { return null; }
const IResourceHook@ get_displayHook() const { return this; }
void onGenerate(Object& obj, Resource@ native) const {}
void nativeTick(Object&, Resource@ native, double time) const {}
void onDestroy(Object&, Resource@ native) const {}
void nativeSave(Resource@ native, SaveFile& file) const {}
void nativeLoad(Resource@ native, SaveFile& file) const {}
bool shouldVanish(Object& obj, Resource@ native) const { return false; }
void onAdd(Object& obj, Resource@ r) const { enable(obj, r.data[hookIndex]); }
void onRemove(Object& obj, Resource@ r) const { disable(obj, r.data[hookIndex]); }
void onTick(Object& obj, Resource@ r, double time) const { tick(obj, r.data[hookIndex], time); }
void onTradeDeliver(Civilian& civ, Object@ origin, Object@ target) const {}
void onTradeDestroy(Civilian& civ, Object@ origin, Object@ target, Object@ destroyer) const {}
void onOwnerChange(Object& obj, Resource@ r, Empire@ prevOwner, Empire@ newOwner) const {
ownerChange(obj, r.data[hookIndex], prevOwner, newOwner);
}
void onRegionChange(Object& obj, Resource@ r, Region@ fromRegion, Region@ toRegion) const {
regionChange(obj, r.data[hookIndex], fromRegion, toRegion);
}
void save(Resource@ r, SaveFile& file) const {
save(r.data[hookIndex], file);
}
void load(Resource@ r, SaveFile& file) const {
load(r.data[hookIndex], file);
}
//Lets this be used as a building hook
void initialize(BuildingType@ type, uint index) { hookIndex = index; }
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void complete(Object& obj, SurfaceBuilding@ bld) const { enable(obj, bld.data[hookIndex]); }
void remove(Object& obj, SurfaceBuilding@ bld) const { disable(obj, bld.data[hookIndex]); }
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const {
ownerChange(obj, bld.data[hookIndex], prevOwner, newOwner);
}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {
tick(obj, bld.data[hookIndex], time);
}
bool canBuildOn(Object& obj, bool ignoreState = false) const { return true; }
bool canRemove(Object& obj) const { return true; }
void save(SurfaceBuilding@ bld, SaveFile& file) const { save(bld.data[hookIndex], file); }
void load(SurfaceBuilding@ bld, SaveFile& file) const { load(bld.data[hookIndex], file); }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color, bool isOption) const {
return false;
}
bool getCost(Object& obj, string& value, Sprite& icon) const { return false; }
void modBuildTime(Object& obj, double& time) const {}
bool canProgress(Object& obj) const { return true; }
//Lets this be used as a status hook
// Planet effects do not deal with status stacks, so they will only
// trigger once per status, regardless of collapsing.
void onCreate(Object& obj, Status@ status, any@ data) { enable(obj, data); }
void onDestroy(Object& obj, Status@ status, any@ data) { disable(obj, data); }
void onObjectDestroy(Object& obj, Status@ status, any@ data) {}
bool onTick(Object& obj, Status@ status, any@ data, double time) { tick(obj, data, time); return true; }
void onAddStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data) {}
void onRemoveStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data) {}
bool onOwnerChange(Object& obj, Status@ status, any@ data, Empire@ prevOwner, Empire@ newOwner) {
ownerChange(obj, data, prevOwner, newOwner); return true; }
bool onRegionChange(Object& obj, Status@ status, any@ data, Region@ prevRegion, Region@ newRegion) {
regionChange(obj, data, prevRegion, newRegion); return true; }
void save(Status@ status, any@ data, SaveFile& file) { save(data, file); }
void load(Status@ status, any@ data, SaveFile& file) { load(data, file); }
bool shouldApply(Empire@ emp, Region@ region, Object@ obj) const { return true; }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
bool consume(Object& obj) const { return true; }
void reverse(Object& obj) const {}
//Lets this be used as an orbital hook
void onEnable(Orbital& obj, any@ data) const { enable(obj, data); }
void onDisable(Orbital& obj, any@ data) const { disable(obj, data); }
void onCreate(Orbital& obj, any@ data) const {}
void onDestroy(Orbital& obj, any@ data) const {}
void onTick(Orbital& obj, any@ data, double time) const { tick(obj, data, time); }
void onOwnerChange(Orbital& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {
ownerChange(obj, data, prevOwner, newOwner);
}
void onRegionChange(Orbital& obj, any@ data, Region@ prevRegion, Region@ newRegion) const {
regionChange(obj, data, prevRegion, newRegion);
}
void onMakeGraphics(Orbital& obj, any@ data, OrbitalNode@ node) const {}
bool checkRequirements(OrbitalRequirements@ reqs, bool apply) const { return true; }
void revertRequirements(OrbitalRequirements@ reqs) const {}
bool canBuildBy(Object@ obj, bool ignoreCost) const { return true; }
bool canBuildOn(Orbital& obj) const { return true; }
bool shouldDisable(Orbital& obj, any@ data) const { return false; }
bool shouldEnable(Orbital& obj, any@ data) const { return true; }
void onKill(Orbital& obj, any@ data, Empire@ killedBy) const {}
void write(any@ data, Message& msg) const {}
void read(any@ data, Message& msg) const {}
bool getValue(Player& pl, Orbital& obj, any@ data, uint index, double& value) const { return false; }
bool sendValue(Player& pl, Orbital& obj, any@ data, uint index, double value) const { return false; }
bool getDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@& value) const { return false; }
bool sendDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@ value) const { return false; }
bool getObject(Player& pl, Orbital& obj, any@ data, uint index, Object@& value) const { return false; }
bool sendObject(Player& pl, Orbital& obj, any@ data, uint index, Object@ value) const { return false; }
bool getData(Orbital& obj, string& txt, bool enabled) const { return false; }
bool canBuildAt(Object@ obj, const vec3d& pos) const { return true; }
string getBuildError(Object@ obj, const vec3d& pos) const { return ""; }
void reverse(Object& obj, bool cancel) const {}
//Subsystem hooks
void start(SubsystemEvent& event) const { enable(event.obj, event.data); }
void tick(SubsystemEvent& event, double time) const { tick(event.obj, event.data, time); }
void suspend(SubsystemEvent& event) const { disable(event.obj, event.data); }
void resume(SubsystemEvent& event) const { enable(event.obj, event.data); }
void destroy(SubsystemEvent& event) const {}
void end(SubsystemEvent& event) const { disable(event.obj, event.data); }
void change(SubsystemEvent& event) const {}
void ownerChange(SubsystemEvent& event, Empire@ prevOwner, Empire@ newOwner) const {
ownerChange(event.obj, event.data, prevOwner, newOwner);
}
void regionChange(SubsystemEvent& event, Region@ prevRegion, Region@ newRegion) const {
regionChange(event.obj, event.data, prevRegion, newRegion);
}
void leaderChange(SubsystemEvent& event, Object@ prevLeader, Object@ newLeader) const {}
DamageEventStatus damage(SubsystemEvent& event, DamageEvent& damage, const vec2u& position) const {
return DE_Continue;
}
DamageEventStatus globalDamage(SubsystemEvent& event, DamageEvent& damage, const vec2u& position, vec2d& endPoint) const {
return DE_Continue;
}
void preRetrofit(SubsystemEvent& event) const {}
void postRetrofit(SubsystemEvent& event) const {}
void save(SubsystemEvent& event, SaveFile& file) const { save(event.data, file); }
void load(SubsystemEvent& event, SaveFile& file) const { load(event.data, file); }
};
interface TriggerableGeneric {
};
interface RegionChangeable {
void regionChange(SubsystemEvent& event, Region@ prevRegion, Region@ newRegion) const;
};
interface LeaderChangeable {
void leaderChange(SubsystemEvent& event, Object@ prevLeader, Object@ newLeader) const;
};
interface ShowsRange {
bool getShowRange(Object& obj, double& range, Color& color) const;
};
tidy class EmpireEffect : GenericEffect, IInfluenceEffectEffect, ITraitEffect, IAttitudeHook {
void enable(Empire& emp, any@ data) const {}
void disable(Empire& emp, any@ data) const {}
void tick(Empire& emp, any@ data, double time) const {}
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
//Generic effects on objects
void enable(Object& obj, any@ data) const { if(obj.owner !is null) enable(obj.owner, data); }
void disable(Object& obj, any@ data) const { if(obj.owner !is null) disable(obj.owner, data); }
void tick(Object& obj, any@ data, double time) const { if(obj.owner !is null) tick(obj.owner, data, time); }
void ownerChange(Object& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {
if(prevOwner !is null)
disable(prevOwner, data);
if(newOwner !is null)
enable(newOwner, data);
}
void regionChange(Object& obj, any@ data, Region@ fromRegion, Region@ toRegion) const {}
//Influence effects
void set_dataIndex(uint ind) { hookIndex = ind; }
void init(InfluenceEffectType@ type) {}
void onStart(InfluenceEffect@ effect) const { enable(effect.owner, effect.data[hookIndex]); }
bool onTick(InfluenceEffect@ effect, double time) const { tick(effect.owner, effect.data[hookIndex], time); return false; }
void onDismiss(InfluenceEffect@ effect, Empire@ byEmpire) const {}
void onEnd(InfluenceEffect@ effect) const { disable(effect.owner, effect.data[hookIndex]); }
bool canDismiss(const InfluenceEffect@ effect, Empire@ byEmpire) const { return true; }
void save(InfluenceEffect@ effect, SaveFile& file) const { save(effect.data[hookIndex], file); }
void load(InfluenceEffect@ effect, SaveFile& file) const { load(effect.data[hookIndex], file); }
//Trait effects
void preInit(Empire& emp, any@ data) const {}
void init(Empire& emp, any@ data) const { enable(emp, data); }
void postInit(Empire& emp, any@ data) const {}
//Attitude effects
Ability@ showAbility(Attitude& att, Empire& emp, Ability@ abl) const { return null; }
bool canTake(Empire& emp) const { return true; }
void enable(Attitude& att, Empire& emp, any@ data) const { enable(emp, data); }
void disable(Attitude& att, Empire& emp, any@ data) const { disable(emp, data); }
void tick(Attitude& att, Empire& emp, any@ data, double time) const { tick(emp, data, time); }
};
tidy class BonusEffect : Hook, IPickupHook, IAnomalyHook, IAbilityHook, IConstructionHook, IRandomOptionHook {
void activate(Object@ obj, Empire@ emp) const {};
//For use as pickup hook
bool canPickup(Pickup& pickup, Object& obj) const { return true; }
void onPickup(Pickup& pickup, Object& obj) const { activate(obj, obj.owner); }
void onClear(Pickup& pickup, Object& obj) const {}
//For use as an anomaly hook
void init(AnomalyType@ type) {}
void choose(Anomaly@ obj, Empire@ emp, Targets@ targets) const override { activate(obj, emp); }
bool giveOption(Anomaly@ obj, Empire@ emp) const override { return true; }
bool isValidTarget(Empire@ emp, uint index, const Target@ targ) const { return true; }
//For use as an ability hook
void create(Ability@ abl, any@ data) const {}
void destroy(Ability@ abl, any@ data) const {}
void enable(Ability@ abl, any@ data) const {}
void disable(Ability@ abl, any@ data) const {}
void tick(Ability@ abl, any@ data, double time) const {}
void save(Ability@ abl, any@ data, SaveFile& file) const {}
void load(Ability@ abl, any@ data, SaveFile& file) const {}
void changeTarget(Ability@ abl, any@ data, uint index, Target@ oldTarget, Target@ newTarget) const {}
void modEnergyCost(const Ability@ abl, const Targets@ targs, double& cost) const {}
string getFailReason(const Ability@ abl, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(const Ability@ abl, uint index, const Target@ targ) const { return true; }
bool canActivate(const Ability@ abl, const Targets@ targs, bool ignoreCost) const { return true; }
void activate(Ability@ abl, any@ data, const Targets@ targs) const { activate(abl.obj, abl.emp); }
bool consume(Ability@ abl, any@ data, const Targets@ targs) const { return true; }
void reverse(Ability@ abl, any@ data, const Targets@ targs) const {}
bool getVariable(const Ability@ abl, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
bool formatCost(const Ability@ abl, const Targets@ targs, string& value) const override { return false; }
bool isChanneling(const Ability@ abl, const any@ data) const { return false; }
//Construction effects
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const {}
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const {}
void finish(Construction@ cons, Constructible@ qitem, any@ data) const { activate(cons.obj, cons.obj.owner); }
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {}
#section all
void save(Construction@ cons, any@ data, SaveFile& file) const {}
void load(Construction@ cons, any@ data, SaveFile& file) const {}
bool consume(Construction@ cons, any@ data, const Targets@ targs) const { return true; }
void reverse(Construction@ cons, any@ data, const Targets@ targs, bool cancel) const {}
string getFailReason(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return true; }
bool canBuild(Object& obj, const ConstructionType@ cons, const Targets@ targs, bool ignoreCost) const { return true; }
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const {}
bool getVariable(Object& obj, const ConstructionType@ cons, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
bool formatCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value) const { return false; }
bool getCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value, Sprite& icon) const { return false; }
//Random events
bool shouldAdd(CurrentEvent& evt, const EventOption& option) const { return true; }
void trigger(CurrentEvent& evt, const EventOption& option, const Target@ targ) const {
if(targ is null)
activate(null, evt.owner);
else if(targ.type == TT_Object && targ.obj !is null)
activate(targ.obj, evt.owner);
else if(targ.type == TT_Empire && targ.emp !is null)
activate(null, targ.emp);
else
activate(null, evt.owner);
}
};
tidy class EmpireTrigger : BonusEffect, ITraitEffect, ITechnologyHook, IAttitudeHook {
//For use as a trait effect
void preInit(Empire& emp, any@ data) const {}
void init(Empire& emp, any@ data) const override { activate(null, emp); }
void postInit(Empire& emp, any@ data) const {}
void tick(Empire& emp, any@ data, double time) const {}
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
//For use as a technology hook
void unlock(TechnologyNode@ node, Empire& emp) const { activate(null, emp); }
bool getSecondaryUnlock(TechnologyNode@ node, Empire@ emp, string& text) const { return false; }
bool canSecondaryUnlock(TechnologyNode@ node, Empire& emp) const { return true; }
bool consumeSecondary(TechnologyNode@ node, Empire& emp) const { return true; }
void reverseSecondary(TechnologyNode@ node, Empire& emp) const {}
bool canUnlock(TechnologyNode@ node, Empire& emp) const { return true; }
bool canBeSecret(TechnologyNode@ node, Empire& emp) const { return true; }
void onStateChange(TechnologyNode@ node, Empire@ emp) const {}
void tick(TechnologyNode@ node, Empire& emp, double time) const {}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& description) const {}
void modPointCost(const TechnologyNode@ node, Empire& emp, double& pointCost) const {}
void modTimeCost(const TechnologyNode@ node, Empire& emp, double& timeCost) const {}
//Attitude hooks
Ability@ showAbility(Attitude& att, Empire& emp, Ability@ abl) const { return null; }
bool canTake(Empire& emp) const { return true; }
void enable(Attitude& att, Empire& emp, any@ data) const { activate(null, emp); }
void disable(Attitude& att, Empire& emp, any@ data) const {}
void tick(Attitude& att, Empire& emp, any@ data, double time) const {}
};
+7
View File
@@ -0,0 +1,7 @@
namespace icons {
const Sprite Replace(spritesheet::EditIcons, 7);
const Sprite Satellite(spritesheet::GuiOrbitalIcons, 14, Color(0xe759ffff));
};
namespace colors {
};
File diff suppressed because it is too large Load Diff
+119
View File
@@ -0,0 +1,119 @@
namespace icons {
const Sprite Loyalty(spritesheet::AttributeIcons, 1);
const Sprite Population(spritesheet::ResourceIcon, 8);
const Sprite Pressure(spritesheet::AttributeIcons, 0);
const Sprite Effectiveness(spritesheet::StatusIcons, 0);
const Sprite Planet(spritesheet::PlanetType, 2);
const Sprite Artifact(spritesheet::ArtifactIcon, 0);
const Sprite Anomaly(spritesheet::AnomalyIcons, 0);
const Sprite Asteroid(material::AsteroidIcon);
const Sprite Building(material::Warehouse);
const Sprite Orbital(spritesheet::GuiOrbitalIcons, 0, Color(0x9e33ddff));
const Sprite Ship(spritesheet::ActionBarIcons, 2);
const Sprite Project(spritesheet::ResourceIcon, 6);
const Sprite Money(spritesheet::ResourceIcon, 0);
const Sprite Influence(spritesheet::ResourceIcon, 1);
const Sprite Energy(spritesheet::ResourceIcon, 2);
const Sprite Labor(spritesheet::ResourceIcon, 6);
const Sprite Defense(spritesheet::ResourceIcon, 5);
const Sprite Research(spritesheet::ResourceIcon, 4);
const Sprite FTL(spritesheet::ResourceIcon, 3);
const Sprite Empty;
const Sprite Health(spritesheet::AttributeIcons, 6);
const Sprite Strength(spritesheet::AttributeIcons, 3);
const Sprite Supply(spritesheet::AttributeIcons, 4);
const Sprite Shield(spritesheet::ResourceIcon, 5, Color(0x429cffff));
const Sprite FoodRequirement(spritesheet::ResourceClassIcons, 3);
const Sprite WaterRequirement(spritesheet::ResourceClassIcons, 4);
const Sprite FoodWaterRequirement(spritesheet::ResourceClassIcons, 7);
const Sprite InfluenceWeight(material::SupportIcon);
const Sprite InfluencePlayCost = Influence;
const Sprite InfluencePurchaseCost(spritesheet::ConvertIcon, 0);
const Sprite InfluenceUpkeep(material::SupplyIcon);
const Sprite Duration(spritesheet::ContextIcons, 1);
const Sprite Manage(spritesheet::ActionBarIcons, 0);
const Sprite ManageSupports(spritesheet::ActionBarIcons, 2);
const Sprite Colonize(spritesheet::ActionBarIcons, 1);
const Sprite ProjectDefense(spritesheet::ActionBarIcons, 3);
const Sprite ColonizeThis(spritesheet::ActionBarIcons, 4);
const Sprite UnderSiege(spritesheet::QuickbarIcons, 7);
const Sprite Hyperdrive(spritesheet::ActionBarIcons, 5);
const Sprite Slipstream(spritesheet::ActionBarIcons, 6);
const Sprite Gate(spritesheet::ActionBarIcons, 7);
const Sprite Fling(spritesheet::ActionBarIcons, 8);
const Sprite Explore(spritesheet::ActionBarIcons, 9);
const Sprite HyperExplore(spritesheet::ActionBarIcons, 10);
const Sprite Ability(spritesheet::ActionBarIcons, 7);
const Sprite Customize(spritesheet::StatusIcons, 0);
const Sprite NotReady(spritesheet::CardCategoryIcons, 0);
const Sprite Ready(spritesheet::CardCategoryIcons, 4);
const Sprite Obsolete(spritesheet::CardCategoryIcons, 0);
const Sprite Unobsolete(spritesheet::CardCategoryIcons, 3);
const Sprite Back(spritesheet::MenuIcons, 11);
const Sprite Close(spritesheet::MenuIcons, 8);
const Sprite Remove(spritesheet::MenuIcons, 8);
const Sprite Delete(spritesheet::MenuIcons, 8);
const Sprite Create(spritesheet::AttributeIcons, 2);
const Sprite Add(spritesheet::AttributeIcons, 2);
const Sprite Plus(spritesheet::AttributeIcons, 2);
const Sprite Minus(material::Minus);
const Sprite Exclaim(spritesheet::MenuIcons, 5);
const Sprite Info(spritesheet::MenuIcons, 3);
const Sprite Details(spritesheet::MenuIcons, 10);
const Sprite Chat(spritesheet::MenuIcons, 6);
const Sprite Go(spritesheet::MenuIcons, 9);
const Sprite Refresh(spritesheet::MenuIcons, 12);
const Sprite Repeat(spritesheet::MenuIcons, 12);
const Sprite Reset(spritesheet::MenuIcons, 12, colors::Red);
const Sprite Import(spritesheet::MenuIcons, 13);
const Sprite Export(spritesheet::MenuIcons, 13);
const Sprite Forward(spritesheet::MenuIcons, 10);
const Sprite Load(spritesheet::MenuIcons, 1);
const Sprite Save(spritesheet::MenuIcons, 2);
const Sprite Edit(material::TabDesigns);
const Sprite Action(spritesheet::CardCategoryIcons, 0);
const Sprite Undo(spritesheet::EditIcons, 0);
const Sprite Redo(spritesheet::EditIcons, 2);
const Sprite UndoDisabled(spritesheet::EditIcons, 1);
const Sprite RedoDisabled(spritesheet::EditIcons, 3);
const Sprite Clear(spritesheet::EditIcons, 8);
const Sprite Paint(spritesheet::EditIcons, 4);
const Sprite Move(spritesheet::EditIcons, 5);
const Sprite Eyedrop(spritesheet::EditIcons, 6);
const Sprite Zoom(spritesheet::EditIcons, 6);
const Sprite Search(spritesheet::EditIcons, 6);
const Sprite Donate(spritesheet::ActionBarIcons, 4, colors::Green);
const Sprite Upvote(material::ThumbsUp);
const Sprite Next(spritesheet::MenuIcons, 9);
const Sprite Previous(spritesheet::MenuIcons, 11);
};
namespace colors {
const Color Money(0xd1cb6aff);
const Color Influence(0x0087c7ff);
const Color Energy(0x42b4bdff);
const Color Defense(0xaf7926ff);
const Color Labor(0xb1b4b6ff);
const Color Research(0x8c4ec9ff);
const Color FTL(0x00c0ffff);
const Color FTLResource(0x9bd29cff);
const Color Planet(0x8cc94eff);
const Color Artifact(0xfe82ffff);
};
@@ -0,0 +1,9 @@
import abilities;
from abilities import addAbilityType;
_Type definition;
void init() {
if(definition.implementationClass.length != 0)
@definition.implementation = getClass(definition.implementationClass);
addAbilityType(definition);
}
@@ -0,0 +1,9 @@
import region_effects;
from region_effects import addRegionEffect;
_Type definition;
void init() {
if(definition.implementationClass.length != 0)
@definition.implementation = getClass(definition.implementationClass);
addRegionEffect(definition);
}
File diff suppressed because it is too large Load Diff
+711
View File
@@ -0,0 +1,711 @@
import hooks;
import influence;
import attributes;
import systems;
import saving;
from bonus_effects import BonusEffect;
import empire_effects;
#section server
from influence_global import modInfluenceStackSize, getLastInfluenceVoteId, getActiveInfluenceVotes, getInfluenceVotesSince, getLastInfluenceEffectId, getInfluenceEffectsSince, getSenateLeader;
#section all
#section server
tidy final class VisionEffect {
array<bool> currentVision;
array<Empire@> empires;
uint mask = 0;
//A new system that matches 'mask' should be
//given vision over roughly every interval seconds.
double interval = 30.0;
double intervalMod = 0.8;
double minInterval = 2.5;
double maxInterval = 40.0;
double timer = 0.0;
uint sysIndex = 0;
void save(SaveFile& file) {
file << sysIndex;
file << timer;
file << interval;
file << intervalMod;
file << minInterval;
file << maxInterval;
file << mask;
uint cnt = currentVision.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file << currentVision[i];
cnt = empires.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file << empires[i];
}
void load(SaveFile& file) {
if(file < SV_0015) {
init();
return;
}
file >> sysIndex;
file >> timer;
file >> interval;
file >> intervalMod;
file >> minInterval;
file >> maxInterval;
file >> mask;
uint cnt = 0;
file >> cnt;
currentVision.length = cnt;
for(uint i = 0; i < cnt; ++i)
file >> currentVision[i];
file >> cnt;
empires.length = cnt;
for(uint i = 0; i < cnt; ++i)
file >> empires[i];
}
void init() {
currentVision.length = systemCount;
for(uint i = 0, cnt = currentVision.length; i < cnt; ++i)
currentVision[i] = false;
}
void update(double time) {
timer -= time;
if(timer >= 0.0)
return;
double sysInt = interval / double(currentVision.length);
const SystemDesc@ found;
timer -= sysInt;
while(timer < 0) {
timer += sysInt;
auto@ sys = getSystem(sysIndex);
if(!currentVision[sysIndex]) {
if(sys.object.TradeMask & mask != 0) {
@found = sys;
break;
}
}
else {
if(sys.object.TradeMask & mask == 0) {
for(uint i = 0, cnt = empires.length; i < cnt; ++i)
sys.object.revokeVision(empires[i]);
currentVision[sysIndex] = false;
}
}
sysIndex = (sysIndex + 1) % currentVision.length;
if(sysIndex == 0 && found is null) {
interval = min(interval / intervalMod, maxInterval);
timer = sysInt;
return;
}
}
if(found !is null) {
for(uint i = 0, cnt = empires.length; i < cnt; ++i)
found.object.grantVision(empires[i]);
currentVision[sysIndex] = true;
timer = sysInt * double(currentVision.length - sysIndex);
interval = max(interval * intervalMod, minInterval);
}
else {
timer = sysInt;
}
}
void disable() {
for(uint n = 0, ncnt = currentVision.length; n < ncnt; ++n) {
if(currentVision[n]) {
auto@ sys = getSystem(n);
for(uint i = 0, cnt = empires.length; i < cnt; ++i)
sys.object.revokeVision(empires[i]);
}
}
}
};
#section all
class GrantVisionOver : InfluenceEffectEffect {
Document doc("Grants vision over a target empire.");
Argument targ(TT_Empire);
#section server
void onStart(InfluenceEffect@ eff) const override {
Empire@ to = arguments[0].fromTarget(eff.targets).emp;
VisionEffect ve;
ve.init();
ve.empires.insertLast(eff.owner);
ve.mask = to.mask;
eff.data[hookIndex].store(@ve);
}
bool onTick(InfluenceEffect@ eff, double time) const override {
VisionEffect@ ve;
eff.data[hookIndex].retrieve(@ve);
if(ve is null)
return true;
ve.update(time);
return false;
}
void onEnd(InfluenceEffect@ eff) const override {
VisionEffect@ ve;
eff.data[hookIndex].retrieve(@ve);
if(ve !is null)
ve.disable();
@ve = null;
eff.data[hookIndex].store(@ve);
}
void save(InfluenceEffect@ effect, SaveFile& file) const {
VisionEffect@ ve;
effect.data[hookIndex].retrieve(@ve);
ve.save(file);
}
void load(InfluenceEffect@ effect, SaveFile& file) const {
VisionEffect ve;
effect.data[hookIndex].store(@ve);
ve.load(file);
}
#section all
};
class GrantEveryoneVisionOver : InfluenceEffectEffect {
Document doc("Grants vision over a empire to everyone.");
Argument targ(TT_Empire);
#section server
void onStart(InfluenceEffect@ eff) const override {
Empire@ to = arguments[0].fromTarget(eff.targets).emp;
VisionEffect ve;
ve.init();
ve.mask = to.mask;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(emp.major && emp !is to)
ve.empires.insertLast(emp);
}
eff.data[hookIndex].store(@ve);
}
bool onTick(InfluenceEffect@ eff, double time) const override {
VisionEffect@ ve;
eff.data[hookIndex].retrieve(@ve);
if(ve is null)
return true;
ve.update(time);
return false;
}
void onEnd(InfluenceEffect@ eff) const override {
VisionEffect@ ve;
eff.data[hookIndex].retrieve(@ve);
if(ve !is null)
ve.disable();
@ve = null;
eff.data[hookIndex].store(@ve);
}
void save(InfluenceEffect@ effect, SaveFile& file) const {
VisionEffect@ ve;
effect.data[hookIndex].retrieve(@ve);
ve.save(file);
}
void load(InfluenceEffect@ effect, SaveFile& file) const {
VisionEffect ve;
effect.data[hookIndex].store(@ve);
ve.load(file);
}
#section all
};
//CancelOnWar(<Target>)
// Cancel the effect when the owner becomes at war with the target.
class CancelOnWar : InfluenceEffectEffect {
Document doc("Ends the influence effect when war is declared between this empire and the target.");
Argument targ(TT_Empire);
#section server
bool onTick(InfluenceEffect@ eff, double time) const override {
Empire@ to = arguments[0].fromTarget(eff.targets).emp;
if(eff.owner !is null && eff.owner.isHostile(to))
eff.end();
return false;
}
#section all
};
class CancelIfNotLeader : InfluenceEffectEffect {
Document doc("Cancel the effect if the owner is not the senate leader.");
#section server
bool onTick(InfluenceEffect@ eff, double time) const override {
if(eff.owner !is getSenateLeader())
eff.end();
return false;
}
#section all
};
class CancelIfAttributeLT : InfluenceEffectEffect {
Document doc("Cancel the effect if the owner's attribute is too low.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument value(AT_Decimal, "1", doc="Value to test against.");
#section server
bool onTick(InfluenceEffect@ eff, double time) const override {
Empire@ owner = eff.owner;
if(owner is null || !owner.valid)
return false;
if(owner.getAttribute(attribute.integer) < value.decimal)
eff.end();
return false;
}
#section all
};
//ModAttribute(<Attribute>, <Mode>, <Value>)
// Modify an empire attribute while the effect is active.
// Mode is one of: Add, AddBase, AddFactor, Multiply
class ModAttribute : InfluenceEffectEffect {
Document doc("Changes an empire's specified attribute.");
Argument attr("Attribute", AT_EmpAttribute, doc="ID of the empire attribute to affect.");
Argument mode("Mode", AT_AttributeMode, doc="How to change the attribute (Add, AddBase, AddFactor, Multiply).");
Argument val("Value", AT_Decimal, doc="Value to change by.");
#section server
void onStart(InfluenceEffect@ eff) const override {
eff.owner.modAttribute(uint(arguments[0].integer), arguments[1].integer, arguments[2].decimal);
}
void onEnd(InfluenceEffect@ eff) const override {
double value = arguments[2].decimal;
if(arguments[1].integer == int(AC_Multiply))
value = 1.0 / value;
else
value = -value;
eff.owner.modAttribute(uint(arguments[0].integer), arguments[1].integer, value);
}
#section all
};
//ModAttributeAll(<Attribute>, <Mode>, <Value>)
// Modify an attribute on all empires while an effect is active.
// Mode is one of: Add, AddBase, AddFactor, Multiply
class ModAttributeAll : InfluenceEffectEffect {
Document doc("Changes all empires' specified attribute.");
Argument attr("Attribute", AT_EmpAttribute, doc="ID of the empire attribute to affect.");
Argument mode("Mode", AT_AttributeMode, doc="How to change the attribute (Add, AddBase, AddFactor, Multiply).");
Argument val("Value", AT_Decimal, doc="Value to change by.");
#section server
void onStart(InfluenceEffect@ eff) const override {
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(!emp.major)
continue;
emp.modAttribute(uint(arguments[0].integer), arguments[1].integer, arguments[2].decimal);
}
}
void onEnd(InfluenceEffect@ eff) const override {
double value = arguments[2].decimal;
if(arguments[1].integer == int(AC_Multiply))
value = 1.0 / value;
else
value = -value;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(!emp.major)
continue;
emp.modAttribute(uint(arguments[0].integer), arguments[1].integer, value);
}
}
#section all
};
//ModAttributeOther(<Attribute>, <Mode>, <Value>)
// Modify an attribute on all other empires while an effect is active.
// Mode is one of: Add, AddBase, AddFactor, Multiply
class ModAttributeOther: InfluenceEffectEffect {
Document doc("Changes all other empires' specified attribute.");
Argument attr("Attribute", AT_EmpAttribute, doc="ID of the empire attribute to affect.");
Argument mode("Mode", AT_AttributeMode, doc="How to change the attribute (Add, AddBase, AddFactor, Multiply).");
Argument val("Value", AT_Decimal, doc="Value to change by.");
#section server
void onStart(InfluenceEffect@ eff) const override {
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is eff.owner)
continue;
emp.modAttribute(uint(arguments[0].integer), arguments[1].integer, arguments[2].decimal);
}
}
void onEnd(InfluenceEffect@ eff) const override {
double value = arguments[2].decimal;
if(arguments[1].integer == int(AC_Multiply))
value = 1.0 / value;
else
value = -value;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is eff.owner)
continue;
emp.modAttribute(uint(arguments[0].integer), arguments[1].integer, value);
}
}
#section all
};
//ModAttributeTarget(<Target>, <Attribute>, <Mode>, <Value>)
// Modify an attribute on a particular empire while the effect is active.
// Mode is one of: Add, AddBase, AddFactor, Multiply
class ModAttributeTarget: InfluenceEffectEffect {
Document doc("Changes a targeted empire's specified attribute.");
Argument targ(TT_Empire);
Argument attr("Attribute", AT_EmpAttribute, doc="ID of the empire attribute to affect.");
Argument mode("Mode", AT_AttributeMode, doc="How to change the attribute (Add, AddBase, AddFactor, Multiply).");
Argument val("Value", AT_Decimal, doc="Value to change by.");
#section server
void onStart(InfluenceEffect@ eff) const override {
Target@ targ = arguments[0].fromTarget(eff.targets);
if(targ is null || targ.emp is null)
return;
targ.emp.modAttribute(uint(arguments[1].integer), arguments[2].integer, arguments[3].decimal);
}
void onEnd(InfluenceEffect@ eff) const override {
Target@ targ = arguments[0].fromTarget(eff.targets);
if(targ is null || targ.emp is null)
return;
double value = arguments[3].decimal;
if(arguments[2].integer == int(AC_Multiply))
value = 1.0 / value;
else
value = -value;
targ.emp.modAttribute(uint(arguments[1].integer), arguments[2].integer, value);
}
#section all
};
//ModInfluenceStackSize(<Amount>)
// Increase the size of the influence stack by <Amount>.
class ModInfluenceStackSize : InfluenceEffectEffect {
Document doc("Changes how many cards are available to purchase at a time while active.");
Argument val("Amount", AT_Integer, doc="Number of cards to add.");
#section server
void onStart(InfluenceEffect@ eff) const override {
modInfluenceStackSize(+arguments[0].integer);
}
void onEnd(InfluenceEffect@ eff) const override {
modInfluenceStackSize(-arguments[0].integer);
}
#section all
};
//ProtectSystem(<Target>)
// Declare the system as protected.
class ProtectSystem : InfluenceEffectEffect {
Document doc("Prevents an empire's planets in a targeted system from sieges while active.");
Argument targ(TT_Object);
#section server
bool onTick(InfluenceEffect@ eff, double time) const override {
Target@ targ = arguments[0].fromTarget(eff.targets);
if(targ is null || targ.obj is null || !targ.obj.isRegion)
return false;
cast<Region>(targ.obj).ProtectedMask |= eff.owner.mask;
return false;
}
void onEnd(InfluenceEffect@ eff) const override {
Target@ targ = arguments[0].fromTarget(eff.targets);
if(targ is null || targ.obj is null || !targ.obj.isRegion)
return;
cast<Region>(targ.obj).ProtectedMask &= ~eff.owner.mask;
}
#section all
};
//GainLeverageWhenVoteStarted(<Quality Factor> = 1.0)
// Whenever a vote is started, gain leverage on the starter.
class GainLeverageWhenVoteStarted : InfluenceEffectEffect {
Document doc("Gives leverage against any empire which starts a vote to this empire.");
Argument qual("Quality Factor", AT_Decimal, "1.0", doc="Magic quality value to determine how much is rewarded.");
#section server
void onStart(InfluenceEffect@ eff) const override {
int last = getLastInfluenceVoteId();
eff.data[hookIndex].store(last);
}
bool onTick(InfluenceEffect@ eff, double time) const override {
int last = -1;
eff.data[hookIndex].retrieve(last);
auto@ list = getInfluenceVotesSince(last);
if(list is null)
return false;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ vote = list[i];
if(vote.startedBy !is eff.owner && vote.startedBy.valid && eff.owner.ContactMask & vote.startedBy.mask != 0)
eff.owner.gainRandomLeverage(vote.startedBy, arguments[0].decimal);
last = max(last, int(vote.id));
}
eff.data[hookIndex].store(last);
return false;
}
void save(InfluenceEffect@ eff, SaveFile& file) const override {
int last = -1;
eff.data[hookIndex].retrieve(last);
file << last;
}
void load(InfluenceEffect@ eff, SaveFile& file) const override {
int last = -1;
if(file >= SV_0089)
file >> last;
else
last = getLastInfluenceVoteId();
eff.data[hookIndex].store(last);
}
#section all
};
//GainLeverageWhenEffectStarted(<Quality Factor> = 1.0)
// Whenever a effect is started, gain leverage on the starter.
class GainLeverageWhenEffectStarted : InfluenceEffectEffect {
Document doc("Gives leverage against any empire which starts an effect to this empire.");
Argument qual("Quality Factor", AT_Decimal, "1.0", doc="Magic quality value to determine how much is rewarded.");
#section server
void onStart(InfluenceEffect@ eff) const override {
int last = getLastInfluenceEffectId();
eff.data[hookIndex].store(last);
}
bool onTick(InfluenceEffect@ eff, double time) const override {
int last = 0;
eff.data[hookIndex].retrieve(last);
auto@ list = getInfluenceEffectsSince(last);
if(list is null)
return false;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ effect = list[i];
if(effect.owner !is eff.owner && effect.owner.valid && eff.owner.ContactMask & effect.owner.mask != 0)
eff.owner.gainRandomLeverage(effect.owner, arguments[0].decimal);
last = max(last, int(effect.id));
}
eff.data[hookIndex].store(last);
return false;
}
void save(InfluenceEffect@ eff, SaveFile& file) const override {
int last = -1;
eff.data[hookIndex].retrieve(last);
file << last;
}
void load(InfluenceEffect@ eff, SaveFile& file) const override {
int last = -1;
if(file >= SV_0089)
file >> last;
else
last = getLastInfluenceEffectId();
eff.data[hookIndex].store(last);
}
#section all
};
class OnEnable : InfluenceEffectEffect {
BonusEffect@ hook;
Document doc("Trigger a bonus effect when the effect enables.");
Argument function(AT_Hook, "bonus_effects::EmpireTrigger");
Argument all_empires(AT_Boolean, "False", doc="When set, trigger the hook on all empires, instead of just the effect owner.");
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::", required=false));
if(hook is null) {
error("OnEnable(): could not find inner hook: "+escape(arguments[0].str));
return false;
}
return InfluenceEffectEffect::instantiate();
}
#section server
void onStart(InfluenceEffect@ eff) const override {
if(hook !is null) {
if(all_empires.boolean) {
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(emp.valid && emp.major)
hook.activate(null, emp);
}
}
else {
hook.activate(null, eff.owner);
}
}
}
#section all
};
class OnDisable : InfluenceEffectEffect {
BonusEffect@ hook;
Document doc("Trigger a bonus effect when the effect disables.");
Argument function(AT_Hook, "bonus_effects::EmpireTrigger");
Argument all_empires(AT_Boolean, "False", doc="When set, trigger the hook on all empires, instead of just the effect owner.");
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::", required=false));
if(hook is null) {
error("OnDisable(): could not find inner hook: "+escape(arguments[0].str));
return false;
}
return InfluenceEffectEffect::instantiate();
}
#section server
void onEnd(InfluenceEffect@ eff) const override {
if(hook !is null) {
if(all_empires.boolean) {
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
auto@ emp = getEmpire(i);
if(emp.valid && emp.major)
hook.activate(null, emp);
}
}
else {
hook.activate(null, eff.owner);
}
}
}
#section all
};
class OnAllEmpires : InfluenceEffectEffect {
EmpireEffect@ eff;
Document doc("Apply an effect to all empires, instead of just the owner of the effect.");
Argument hookID("Hook", AT_Hook, "empire_effects::EmpireEffect");
Argument apply_on_owner(AT_Boolean, "True", doc="Whether to also apply the effect on the owner, or just others.");
bool instantiate() override {
@eff = cast<EmpireEffect>(parseHook(hookID.str, "empire_effects::", required=false));
if(eff is null) {
error("OnAllEmpires(): could not find inner hook: "+escape(hookID.str));
return false;
}
return InfluenceEffectEffect::instantiate();
}
void onStart(InfluenceEffect@ effect) const override {
array<any> arr(getEmpireCount());
effect.data[hookIndex].store(@arr);
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is effect.owner && !apply_on_owner.boolean)
continue;
eff.enable(emp, arr[i]);
}
}
bool onTick(InfluenceEffect@ effect, double time) const override {
array<any>@ arr;
effect.data[hookIndex].retrieve(@arr);
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is effect.owner && !apply_on_owner.boolean)
continue;
eff.tick(emp, arr[i], time);
}
return false;
}
void onEnd(InfluenceEffect@ effect) const override {
array<any>@ arr;
effect.data[hookIndex].retrieve(@arr);
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is effect.owner && !apply_on_owner.boolean)
continue;
eff.disable(emp, arr[i]);
}
}
void save(InfluenceEffect@ effect, SaveFile& file) const {
array<any>@ arr;
effect.data[hookIndex].retrieve(@arr);
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is effect.owner && !apply_on_owner.boolean)
continue;
eff.save(arr[i], file);
}
}
void load(InfluenceEffect@ effect, SaveFile& file) const {
array<any> arr(getEmpireCount());
effect.data[hookIndex].store(@arr);
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ emp = getEmpire(i);
if(!emp.major)
continue;
if(emp is effect.owner && !apply_on_owner.boolean)
continue;
eff.load(arr[i], file);
}
}
};
+349
View File
@@ -0,0 +1,349 @@
import hooks;
import buildings;
from buildings import IBuildingHook;
import abilities;
from abilities import IAbilityHook;
import statuses;
from statuses import IStatusHook;
import util.formatting;
import icons;
import constructions;
from constructions import IConstructionHook;
#section server
from construction.Constructible import Constructible;
#section all
class ListedValue : Hook, IBuildingHook, IAbilityHook, IStatusHook, IConstructionHook {
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
return false;
}
//For use as an ability hook
void create(Ability@ abl, any@ data) const {}
void destroy(Ability@ abl, any@ data) const {}
void enable(Ability@ abl, any@ data) const {}
void disable(Ability@ abl, any@ data) const {}
void tick(Ability@ abl, any@ data, double time) const {}
void save(Ability@ abl, any@ data, SaveFile& file) const {}
void load(Ability@ abl, any@ data, SaveFile& file) const {}
void changeTarget(Ability@ abl, any@ data, uint index, Target@ oldTarget, Target@ newTarget) const {}
void modEnergyCost(const Ability@ abl, const Targets@ targs, double& cost) const {}
string getFailReason(const Ability@ abl, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(const Ability@ abl, uint index, const Target@ targ) const { return true; }
bool canActivate(const Ability@ abl, const Targets@ targs, bool ignoreCost) const { return true; }
void activate(Ability@ abl, any@ data, const Targets@ targs) const {}
bool consume(Ability@ abl, any@ data, const Targets@ targs) const { return true; }
void reverse(Ability@ abl, any@ data, const Targets@ targs) const {}
bool getVariable(const Ability@ abl, Sprite& sprt, string& name, string& value, Color& color) const {
return getVariable(abl.obj, abl.emp, sprt, name, value, color);
}
bool formatCost(const Ability@ abl, const Targets@ targs, string& value) const override { return false; }
bool isChanneling(const Ability@ abl, const any@ data) const { return false; }
//Lets this be used as a building hook
void initialize(BuildingType@ type, uint index) {}
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void complete(Object& obj, SurfaceBuilding@ bld) const {}
void remove(Object& obj, SurfaceBuilding@ bld) const {}
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const {}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {}
bool canBuildOn(Object& obj, bool ignoreState = false) const { return true; }
bool canRemove(Object& obj) const { return true; }
void save(SurfaceBuilding@ bld, SaveFile& file) const {}
void load(SurfaceBuilding@ bld, SaveFile& file) const {}
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color, bool isOption) const {
return getVariable(obj, obj !is null ? obj.owner : playerEmpire, sprt, name, value, color);
}
void modBuildTime(Object& obj, double& time) const {}
bool canProgress(Object& obj) const { return true; }
//Status hooks
void onCreate(Object& obj, Status@ status, any@ data) {}
void onDestroy(Object& obj, Status@ status, any@ data) {}
void onObjectDestroy(Object& obj, Status@ status, any@ data) {}
bool onTick(Object& obj, Status@ status, any@ data, double time) { return true; }
void onAddStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data) {}
void onRemoveStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data) {}
bool onOwnerChange(Object& obj, Status@ status, any@ data, Empire@ prevOwner, Empire@ newOwner) { return true; }
bool onRegionChange(Object& obj, Status@ status, any@ data, Region@ prevRegion, Region@ newRegion) { return true; }
void save(Status@ status, any@ data, SaveFile& file) {}
void load(Status@ status, any@ data, SaveFile& file) {}
bool shouldApply(Empire@ emp, Region@ region, Object@ obj) const { return true; }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color) const {
return getVariable(obj, obj !is null ? obj.owner : playerEmpire, sprt, name, value, color);
}
//Constructions
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const {}
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const {}
void finish(Construction@ cons, Constructible@ qitem, any@ data) const {}
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {}
#section all
void save(Construction@ cons, any@ data, SaveFile& file) const {}
void load(Construction@ cons, any@ data, SaveFile& file) const {}
bool consume(Construction@ cons, any@ data, const Targets@ targs) const { return true; }
void reverse(Construction@ cons, any@ data, const Targets@ targs, bool cancel) const {}
string getFailReason(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return true; }
bool canBuild(Object& obj, const ConstructionType@ cons, const Targets@ targs, bool ignoreCost) const { return true; }
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const {}
bool getVariable(Object& obj, const ConstructionType@ cons, Sprite& sprt, string& name, string& value, Color& color) const { return getVariable(obj, obj.owner, sprt, name, value, color); }
bool formatCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value) const { return false; }
bool getCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value, Sprite& icon) const { return false; }
bool getCost(Object& obj, string& value, Sprite& icon) const { return false; }
bool consume(Object& obj) const { return true; }
void reverse(Object& obj) const {}
};
class ShowValue : ListedValue {
Document doc("Show a value in the tooltip.");
Argument name(AT_Locale, doc="Name of the value.");
Argument amount(AT_Decimal, doc="Amount of the value.");
Argument icon(AT_Sprite, EMPTY_DEFAULT, doc="Icon to show for the value");
Argument suffix(AT_Locale, EMPTY_DEFAULT, doc="Suffix behind the value.");
Argument color(AT_Color, EMPTY_DEFAULT, doc="Color of the value's name.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
sprt = getSprite(this.icon.str);
name = this.name.str;
value = standardize(this.amount.decimal, true);
if(suffix.str.length != 0)
value += " "+suffix.str;
if(this.color.str.length != 0)
color = toColor(this.color.str);
return true;
}
};
class ShowAttributeValue : ListedValue {
Document doc("Show a value in the tooltip.");
Argument name(AT_Locale, doc="Name of the value.");
Argument attribute(AT_EmpAttribute, doc="Attribute of the value to show.");
Argument base_amount(AT_Decimal, "0", doc="Base amount to add independent of the attribute value.");
Argument multiplier(AT_Decimal, "1.0", doc="Multiplier to the attribute value to add to the base amount and show.");
Argument icon(AT_Sprite, EMPTY_DEFAULT, doc="Icon to show for the value");
Argument suffix(AT_Locale, EMPTY_DEFAULT, doc="Suffix behind the value.");
Argument color(AT_Color, EMPTY_DEFAULT, doc="Color of the value's name.");
Argument hide_zero(AT_Boolean, "False", doc="Don't show the attribute if it is zero.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
Empire@ owner = emp;
if(obj !is null && owner is null)
@owner = obj.owner;
double v = base_amount.decimal;
if(owner !is null)
v += multiplier.decimal * owner.getAttribute(attribute.integer);
if(v == 0 && hide_zero.boolean)
return false;
sprt = getSprite(this.icon.str);
name = this.name.str;
value = standardize(v, true);
if(suffix.str.length != 0)
value += " "+suffix.str;
if(this.color.str.length != 0)
color = toColor(this.color.str);
return true;
}
};
class ShowEnergyValue : ListedValue {
Document doc("Show an energy value in the tooltip.");
Argument amount(AT_Decimal, doc="Amount of the value.");
Argument name(AT_Locale, "#RESOURCE_ENERGY", doc="Name of the value.");
Argument apply_penalty(AT_Boolean, "True", doc="Whether the value should be multiplied by the current energy storage penalty.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
double v = amount.decimal;
Empire@ owner = emp;
if(obj !is null && owner is null)
@owner = obj.owner;
if(owner !is null && apply_penalty.boolean)
v *= owner.EnergyEfficiency;
sprt = icons::Energy;
color = colors::Energy;
name = this.name.str;
value = toString(v, 0);
return true;
}
};
class ShowMoneyValue : ListedValue {
Document doc("Show a money value in the tooltip.");
Argument amount(AT_Integer, doc="Amount of the value.");
Argument name(AT_Locale, "#RESOURCE_MONEY", doc="Name of the value.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
sprt = icons::Money;
color = colors::Money;
name = this.name.str;
value = formatMoney(amount.integer);
return true;
}
};
class ShowInfluenceValue : ListedValue {
Document doc("Show an influence value in the tooltip.");
Argument amount(AT_Integer, doc="Amount of the value.");
Argument name(AT_Locale, "#RESOURCE_INFLUENCE", doc="Name of the value.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
sprt = icons::Influence;
color = colors::Influence;
name = this.name.str;
value = toString(amount.integer, 0);
return true;
}
};
class ShowResearchValue : ListedValue {
Document doc("Show a research value in the tooltip.");
Argument amount(AT_Decimal, doc="Amount of the value.");
Argument name(AT_Locale, "#RESOURCE_RESEARCH", doc="Name of the value.");
Argument apply_efficiency(AT_Boolean, "True", doc="Whether the value should be multiplied by the current research efficiency.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
double v = amount.decimal;
Empire@ owner = emp;
if(obj !is null && owner is null)
@owner = obj.owner;
if(owner !is null && apply_efficiency.boolean)
v *= owner.ResearchEfficiency;
sprt = icons::Research;
color = colors::Research;
name = this.name.str;
value = toString(v, 0);
return true;
}
};
class ShowLaborValue : ListedValue {
Document doc("Show a labor value in the tooltip.");
Argument amount(AT_Decimal, doc="Amount of the value.");
Argument name(AT_Locale, "#RESOURCE_LABOR", doc="Name of the value.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
sprt = icons::Labor;
color = colors::Labor;
name = this.name.str;
value = toString(amount.decimal, 0);
return true;
}
};
class ShowShipSizeValue : ListedValue {
Document doc("Show a value in the tooltip based on ship size.");
Argument name(AT_Locale, doc="Name of the value.");
Argument amount(AT_Decimal, "0", doc="Base amount of the value.");
Argument per_shipsize(AT_Decimal, "0", doc="When on a ship, increase the value by the ship design size multiplied by this.");
Argument icon(AT_Sprite, EMPTY_DEFAULT, doc="Icon to show for the value");
Argument suffix(AT_Locale, EMPTY_DEFAULT, doc="Suffix behind the value.");
Argument color(AT_Color, EMPTY_DEFAULT, doc="Color of the value's name.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
sprt = getSprite(this.icon.str);
name = this.name.str;
double v = this.amount.decimal;
if(per_shipsize.decimal != 0 && obj !is null && obj.isShip)
v += cast<Ship>(obj).blueprint.design.size * per_shipsize.decimal;
value = standardize(v, true);
if(suffix.str.length != 0)
value += " "+suffix.str;
if(this.color.str.length != 0)
color = toColor(this.color.str);
return true;
}
};
class ShowTotalPopulation : ListedValue {
Document doc("Show the empire's total population.");
Argument name(AT_Locale, doc="Name of the value.");
Argument icon(AT_Sprite, EMPTY_DEFAULT, doc="Icon to show for the value");
Argument suffix(AT_Locale, EMPTY_DEFAULT, doc="Suffix behind the value.");
Argument color(AT_Color, EMPTY_DEFAULT, doc="Color of the value's name.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
Empire@ owner = emp;
if(obj !is null && owner is null)
@owner = obj.owner;
double v = 0;
if(owner !is null)
v = owner.TotalPopulation;
sprt = getSprite(this.icon.str);
name = this.name.str;
value = standardize(v, true);
if(suffix.str.length != 0)
value += " "+suffix.str;
if(this.color.str.length != 0)
color = toColor(this.color.str);
return true;
}
};
class ShowLevelValue : ListedValue {
Document doc("Show a value dependent on the planet level of the object.");
Argument name(AT_Locale, doc="Name of the value.");
Argument values(AT_Locale, doc="Values for each level.");
Argument icon(AT_Sprite, EMPTY_DEFAULT, doc="Icon to show for the value");
Argument suffix(AT_Locale, EMPTY_DEFAULT, doc="Suffix behind the value.");
Argument color(AT_Color, EMPTY_DEFAULT, doc="Color of the value's name.");
Argument value_color(AT_Color, "#00c0ff", doc="Color of the highlighted value.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
uint lv = 0;
if(obj !is null && obj.hasSurfaceComponent)
lv = obj.level;
sprt = getSprite(this.icon.str);
name = this.name.str;
value = format("[levels=$1;$22]", lv, value_color.str);
value += values.str;
value += "[/levels]";
if(this.color.str.length != 0)
color = toColor(this.color.str);
return true;
}
};
class ShowFTLValue : ListedValue {
Document doc("Show an FTL value in the tooltip.");
Argument amount(AT_Decimal, doc="Amount of the value.");
Argument name(AT_Locale, "#RESOURCE_FTL", doc="Name of the value.");
Argument suffix(AT_Locale, EMPTY_DEFAULT, doc="Suffix behind the value.");
bool getVariable(Object@ obj, Empire@ emp, Sprite& sprt, string& name, string& value, Color& color) const {
double v = amount.decimal;
Empire@ owner = emp;
if(obj !is null && owner is null)
@owner = obj.owner;
sprt = icons::FTL;
color = colors::FTL;
name = this.name.str;
value = standardize(v, true);
if(suffix.str.length != 0)
value += " "+suffix.str;
return true;
}
};
File diff suppressed because it is too large Load Diff
+177
View File
@@ -0,0 +1,177 @@
#priority init 1550
import hooks;
import settings.map_lib;
export SystemType, SystemUniqueness;
export getSystemType, getSystemTypeCount;
export getDistributedSystemType;
enum SystemUniqueness {
SU_NonUnique,
SU_Galaxy,
SU_Global,
};
tidy final class SystemType {
uint id;
string ident;
SystemUniqueness unique = SU_NonUnique;
double frequency = 0;
array<Hook@> hooks;
array<string> baseNames;
array<const SystemType@> bases;
void generate(SystemData@ data, SystemDesc@ system) const {
Object@ current;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
auto@ hook = cast<IMapHook@>(hooks[i]);
if(hook !is null)
hook.trigger(data, system, current);
}
for(uint i = 0, cnt = bases.length; i < cnt; ++i)
bases[i].generate(data, system);
}
void postGenerate(SystemData@ data, SystemDesc@ system) const {
Object@ current;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
auto@ hook = cast<IMapHook@>(hooks[i]);
if(hook !is null)
hook.postTrigger(data, system, current);
}
for(uint i = 0, cnt = bases.length; i < cnt; ++i)
bases[i].postGenerate(data, system);
}
};
interface IMapHook {
void trigger(SystemData@ data, SystemDesc@ system, Object@& current) const;
void postTrigger(SystemData@ data, SystemDesc@ system, Object@& current) const;
};
class MapHook : IMapHook, Hook {
void trigger(SystemData@ data, SystemDesc@ system, Object@& current) const {}
void postTrigger(SystemData@ data, SystemDesc@ system, Object@& current) const {}
};
void parseLine(int indent, const string& line, SystemType@ type) {
auto@ hook = cast<IMapHook@>(parseHook(type.hooks, indent, line, "map_effects::"));
if(hook is null && !isScriptDebug)
error(" Invalid map hook: "+escape(line));
}
void loadSystems(const string& filename) {
ReadFile file(filename, true);
string key, value;
SystemType@ type;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
if(type is null) {
error("Missing 'System: ID' line in " + filename);
continue;
}
string line = file.line;
parseLine(file.indent, line, type);
}
else if(key == "System") {
if(type !is null)
addSystemType(type);
@type = SystemType();
type.ident = value;
}
else if(type is null) {
error("Missing 'System: ID' line in " + filename);
}
else if(key == "Frequency") {
type.frequency = toDouble(value);
if(type.unique != SU_NonUnique)
type.frequency *= config::UNIQUE_SYSTEM_OCCURANCE / 0.3;
}
else if(key == "Inherit") {
type.baseNames.insertLast(value);
}
else if(key == "Unique") {
if(value.equals_nocase("global"))
type.unique = SU_Global;
else if(value.equals_nocase("galaxy"))
type.unique = SU_Galaxy;
else
error("Error: Unknown system uniqueness: "+value);
type.frequency *= config::UNIQUE_SYSTEM_OCCURANCE / 0.3;
}
else {
string line = file.line;
parseLine(file.indent, line, type);
}
}
if(type !is null)
addSystemType(type);
}
void init() {
FileList list("data/systems", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadSystems(list.path[i]);
for(uint i = 0, cnt = systemTypes.length; i < cnt; ++i) {
SystemType@ type = systemTypes[i];
for(uint n = 0, ncnt = type.baseNames.length; n < ncnt; ++n) {
const SystemType@ base = getSystemType(type.baseNames[n]);
if(base !is null)
type.bases.insertLast(base);
else
error(" Error: Base system type not found: "+type.baseNames[n]);
}
}
}
SystemType@[] systemTypes;
dictionary idents;
double totalFrequency = 0;
const SystemType@ getSystemType(uint id) {
if(id >= systemTypes.length)
return null;
return systemTypes[id];
}
const SystemType@ getSystemType(const string& ident) {
SystemType@ anomaly;
if(idents.get(ident, @anomaly))
return anomaly;
return null;
}
uint getSystemTypeCount() {
return systemTypes.length;
}
const SystemType@ getDistributedSystemType() {
uint count = systemTypes.length;
double num = randomd(0, totalFrequency);
for(uint i = 0, cnt = systemTypes.length; i < cnt; ++i) {
const SystemType@ type = systemTypes[i];
double freq = type.frequency;
if(num <= freq)
return type;
num -= freq;
}
return systemTypes[systemTypes.length-1];
}
void addSystemType(SystemType@ type) {
type.id = systemTypes.length;
systemTypes.insertLast(type);
idents.set(type.ident, @type);
totalFrequency += type.frequency;
}
+154
View File
@@ -0,0 +1,154 @@
#priority init 10000
import saving;
/*enum PresetStats {
};*/
const array<string> preset_stats = {};
string getObjectStatMode(int id) {
switch(id)
{
case OSM_Set: return "Set";
case OSM_Add: return "Add";
case OSM_Multiply: return "Multiply";
}
return "Set";
}
int getObjectStatMode(const string& ident) {
if(ident.equals_nocase("set"))
return OSM_Set;
if(ident.equals_nocase("add"))
return OSM_Add;
if(ident.equals_nocase("multiply"))
return OSM_Multiply;
return OSM_Set;
}
#section client
int getObjectStatId(const string& ident, bool create = true) {
return getObjectStat_client(ident);
}
string getObjectStatIdent(int id) {
return getObjectStatIdent_client(id);
}
#section server-side
const double OBJECT_STAT_SYNC_RESOLUTION = 0.01;
tidy class ObjectStatType {
int id;
string ident;
bool isInt = false;
bool shouldSync = true;
ObjectStatType(const string& name)
{
ident = name;
isInt = name.contains("#");
shouldSync = !name.contains("&");
}
uint64 key(Empire@ forEmpire) const {
return OBJ_STAT_MASK | uint64(forEmpire.id) << 32 | uint64(id);
}
void mod(Object@ obj, Empire@ emp, int mode, double value) const {
if(isInt) {
int dirtyResolution = 0;
if(!shouldSync)
dirtyResolution = -1;
obj.modStatInt(key(emp), ObjectStatMode(mode), int(value), dirtyResolution);
}
else {
double dirtyResolution = OBJECT_STAT_SYNC_RESOLUTION;
if(!shouldSync)
dirtyResolution = -1.0;
obj.modStatDouble(key(emp), ObjectStatMode(mode), int64(value), dirtyResolution);
}
}
void reverse(Object@ obj, Empire@ emp, int mode, double value) const {
switch(mode) {
case OSM_Set:
throw("Cannot reverse a stat modified with Set mode.");
return;
case OSM_Multiply:
if(value == 0.0) {
throw("Cannot reverse a stat multiplied by 0.");
return;
}
value = 1.0 / value;
break;
case OSM_Add:
value *= -1.0;
break;
}
mod(obj, emp, mode, value);
}
};
array<ObjectStatType@> objectStats;
dictionary objectStatIdents;
void preInit() {
for(uint i = 0, cnt = preset_stats.length; i < cnt; ++i)
getObjectStat(preset_stats[i], create=true);
}
uint getObjectStatCount() {
return objectStats.length;
}
const ObjectStatType@ getObjectStat(int id) {
if(id < 0 || uint(id) >= objectStats.length)
return null;
return objectStats[id];
}
const ObjectStatType@ getObjectStat(const string& ident, bool create = true) {
int id = -1;
if(!objectStatIdents.get(ident, id)) {
if(create) {
id = int(objectStats.length);
ObjectStatType stat(ident);
stat.id = id;
objectStats.insertLast(stat);
objectStatIdents.set(ident, id);
return stat;
}
else {
return null;
}
}
return objectStats[id];
}
int getObjectStatId(const string& ident, bool create = true) {
auto@ stat = getObjectStat(ident, create);
if(stat is null)
return -1;
else
return stat.id;
}
int getObjectStatId_client(string ident) {
int id = -1;
if(objectStatIdents.get(ident, id))
return id;
return -1;
}
string getObjectStatIdent(int id) {
if(id < 0 || uint(id) >= objectStats.length)
return "";
return objectStats[id].ident;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = objectStats.length; i < cnt; ++i)
file.addIdentifier(SI_ObjectStat, int(i), objectStats[i].ident);
}
File diff suppressed because it is too large Load Diff
+723
View File
@@ -0,0 +1,723 @@
#priority init 1000
import saving;
import hooks;
import system_pathing;
import resources;
import tile_resources;
#section server-side
from regions.regions import getRegion;
import SystemDesc@ getSystem(Region@ region) from "game_start";
#section all
export OrbitalModule, OrbitalSection;
export getOrbitalModule, getOrbitalModuleCount;
export OrbitalRequirements;
export OrbitalValues, canBuildOrbital;
array<OrbitalModule@> modules;
dictionary idents;
enum OrbitalValues {
OV_DRY_Design,
OV_DRY_Progress,
OV_DRY_Financed,
OV_DRY_Free,
OV_DRY_SetFinanced,
OV_DRY_ModLabor,
OV_DRY_ETA,
OV_PackUp,
OV_Trade,
OV_FRAME_Usable,
OV_FRAME_CostFactor,
OV_FRAME_LaborFactor,
OV_FRAME_LaborPenaltyFactor,
OV_FRAME_Target,
};
bool canBuildOrbital(Object@ obj, const vec3d& pos, bool initial = true) {
//Find target system
Region@ target = getRegion(pos);
if(target is null)
return false;
//Cannot build without vision
if(initial && target.MemoryMask & obj.owner.mask == 0 && target.VisionMask & obj.owner.visionMask == 0)
return false;
//Check trade pathing
if(initial || !obj.isShip) {
if(obj.region is null)
return false;
TradePath path(obj.owner);
path.generate(getSystem(obj.region), getSystem(target));
if(!path.isUsablePath)
return false;
}
return true;
}
tidy final class OrbitalModule {
uint id;
string ident;
string name;
string blurb;
string description;
Sprite icon;
Sprite distantIcon;
Sprite strategicIcon;
double iconSize = 0.035;
const Material@ material;
const Model@ model;
double size = 10.0;
int maintenance = 0;
int buildCost = 0;
double laborCost = 0;
double health = 0;
double armor = 0;
double spin = 30.0;
double mass = -1.0;
bool isCore = true;
bool isSolid = true;
bool isStandalone = true;
bool isUnique = true;
bool combatRepair = true;
bool canFling = true;
array<IOrbitalEffect@> hooks;
array<Hook@> ai;
array<uint> affinities(TR_COUNT, 0);
array<const ResourceType@> requirements;
uint totalRequirementCount = 0;
bool canBuildBy(Object@ obj, bool ignoreCost = true) const {
if(!isCore)
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canBuildBy(obj, ignoreCost))
return false;
}
return true;
}
bool canBuildAt(Object@ obj, const vec3d& pos) const {
if(!isCore)
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canBuildAt(obj, pos))
return false;
}
return true;
}
bool canBuild(Object@ obj, const vec3d& pos, bool initial = true) const {
if(!canBuildBy(obj))
return false;
if(!canBuildAt(obj, pos))
return false;
if(!canBuildOrbital(obj, pos, initial))
return false;
return true;
}
bool canBuildOn(Orbital& orbital) const {
if(isCore)
return false;
if(isUnique) {
if(orbital.hasModule(id))
return false;
}
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canBuildOn(orbital))
return false;
}
return true;
}
bool checkRequirements(OrbitalRequirements@ reqs, bool apply) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].checkRequirements(reqs, apply)) {
if(apply) {
for(uint n = 0; n < i; ++n)
hooks[n].revertRequirements(reqs);
}
return false;
}
}
return true;
}
string getTooltip() const {
string tip = format("[font=Medium][img=$2;32/] $1[/font]\n$3",
name, getSpriteDesc(icon), description);
bool reqs = false;
for(uint i = 0; i < TR_COUNT; ++i) {
if(affinities[i] > 0) {
if(!reqs) {
tip += "\n";
reqs = true;
}
tip += "\n";
tip += format(locale::ORB_REQ_AFFINITY,
affinities[i], getTileResourceName(i),
getTileResourceSpriteSpec(i));
}
}
for(uint i = 0, cnt = requirements.length; i < cnt; ++i) {
if(!reqs) {
tip += "\n";
reqs = true;
}
tip += "\n";
tip += format(locale::ORB_REQ_RESOURCE,
requirements[i].name, getSpriteDesc(requirements[i].icon));
}
return tip;
}
};
interface IOrbitalEffect {
void onEnable(Orbital& obj, any@ data) const;
void onDisable(Orbital& obj, any@ data) const;
void onCreate(Orbital& obj, any@ data) const;
void onDestroy(Orbital& obj, any@ data) const;
void onTick(Orbital& obj, any@ data, double time) const;
void onOwnerChange(Orbital& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const;
void onRegionChange(Orbital& obj, any@ data, Region@ prevRegion, Region@ newRegion) const;
void onMakeGraphics(Orbital& obj, any@ data, OrbitalNode@ node) const;
bool checkRequirements(OrbitalRequirements@ reqs, bool apply) const;
void revertRequirements(OrbitalRequirements@ reqs) const;
bool canBuildBy(Object@ obj, bool ignoreCost = true) const;
bool canBuildAt(Object@ obj, const vec3d& pos) const;
bool canBuildOn(Orbital& obj) const;
string getBuildError(Object@ obj, const vec3d& pos) const;
bool shouldDisable(Orbital& obj, any@ data) const;
bool shouldEnable(Orbital& obj, any@ data) const;
void save(any@ data, SaveFile& file) const;
void load(any@ data, SaveFile& file) const;
void onKill(Orbital& obj, any@ data, Empire@ killedBy) const;
void write(any@ data, Message& msg) const;
void read(any@ data, Message& msg) const;
bool getValue(Player& pl, Orbital& obj, any@ data, uint index, double& value) const;
bool sendValue(Player& pl, Orbital& obj, any@ data, uint index, double value) const;
bool getDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@& value) const;
bool sendDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@ value) const;
bool getObject(Player& pl, Orbital& obj, any@ data, uint index, Object@& value) const;
bool sendObject(Player& pl, Orbital& obj, any@ data, uint index, Object@ value) const;
bool getData(Orbital& obj, string& txt, bool enabled) const;
bool getCost(Object& obj, string& value, Sprite& icon) const;
bool consume(Object& obj) const;
void reverse(Object& obj, bool cancel) const;
};
class OrbitalEffect : Hook, IOrbitalEffect {
void onEnable(Orbital& obj, any@ data) const {}
void onDisable(Orbital& obj, any@ data) const {}
void onCreate(Orbital& obj, any@ data) const {}
void onDestroy(Orbital& obj, any@ data) const {}
void onTick(Orbital& obj, any@ data, double time) const {}
void onOwnerChange(Orbital& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {}
void onRegionChange(Orbital& obj, any@ data, Region@ prevRegion, Region@ newRegion) const {}
void onMakeGraphics(Orbital& obj, any@ data, OrbitalNode@ node) const {}
bool checkRequirements(OrbitalRequirements@ reqs, bool apply) const { return true; }
void revertRequirements(OrbitalRequirements@ reqs) const {}
bool canBuildBy(Object@ obj, bool ignoreCost) const { return true; }
bool canBuildAt(Object@ obj, const vec3d& pos) const { return true; }
bool canBuildOn(Orbital& obj) const { return true; }
string getBuildError(Object@ obj, const vec3d& pos) const { return ""; }
bool shouldDisable(Orbital& obj, any@ data) const { return false; }
bool shouldEnable(Orbital& obj, any@ data) const { return true; }
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
void write(any@ data, Message& msg) const {}
void read(any@ data, Message& msg) const {}
void onKill(Orbital& obj, any@ data, Empire@ killedBy) const {}
bool getValue(Player& pl, Orbital& obj, any@ data, uint index, double& value) const { return false; }
bool sendValue(Player& pl, Orbital& obj, any@ data, uint index, double value) const { return false; }
bool getDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@& value) const { return false; }
bool sendDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@ value) const { return false; }
bool getObject(Player& pl, Orbital& obj, any@ data, uint index, Object@& value) const { return false; }
bool sendObject(Player& pl, Orbital& obj, any@ data, uint index, Object@ value) const { return false; }
bool getData(Orbital& obj, string& txt, bool enabled) const { return false; }
bool getCost(Object& obj, string& value, Sprite& icon) const { return false; }
bool consume(Object& obj) const { return true; }
void reverse(Object& obj, bool cancel) const {}
};
tidy final class OrbitalSection : Serializable, Savable {
const OrbitalModule@ type;
int id = -1;
array<any> data;
bool enabled = true;
OrbitalSection() {
}
OrbitalSection(const OrbitalModule@ type) {
@this.type = type;
data.length = type.hooks.length;
}
void write(Message& msg) {
msg.writeSmall(type.id);
msg.writeSmall(id);
msg.writeBit(enabled);
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].write(data[i], msg);
}
void read(Message& msg) {
@type = getOrbitalModule(msg.readSmall());
id = msg.readSmall();
enabled = msg.readBit();
data.length = type.hooks.length;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].read(data[i], msg);
}
OrbitalSection(SaveFile& file) {
load(file);
}
void save(SaveFile& file) {
file << id;
file.writeIdentifier(SI_Orbital, type.id);
file << enabled;
if(enabled) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].save(data[i], file);
}
}
void load(SaveFile& file) {
file >> id;
@type = getOrbitalModule(file.readIdentifier(SI_Orbital));
file >> enabled;
data.length = type.hooks.length;
if(enabled) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].load(data[i], file);
}
}
void enable(Orbital& obj) {
enabled = true;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onEnable(obj, data[i]);
}
void disable(Orbital& obj) {
enabled = false;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onDisable(obj, data[i]);
}
void create(Orbital& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onCreate(obj, data[i]);
}
void destroy(Orbital& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onDestroy(obj, data[i]);
}
void tick(Orbital& obj, double time) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onTick(obj, data[i], time);
}
void ownerChange(Orbital& obj, Empire@ prevOwner, Empire@ newOwner) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onOwnerChange(obj, data[i], prevOwner, newOwner);
}
void regionChange(Orbital& obj, Region@ prevRegion, Region@ newRegion) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onRegionChange(obj, data[i], prevRegion, newRegion);
}
void makeGraphics(Orbital& obj, OrbitalNode@ node) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onMakeGraphics(obj, data[i], node);
}
bool shouldDisable(Orbital& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(type.hooks[i].shouldDisable(obj, data[i]))
return true;
}
return false;
}
void kill(Orbital& obj, Empire@ killedBy) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onKill(obj, data[i], killedBy);
}
bool shouldEnable(Orbital& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].shouldEnable(obj, data[i]))
return false;
}
return true;
}
string getData(Orbital& obj) const {
string txt;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(type.hooks[i].getData(obj, txt, enabled))
return txt;
}
return txt;
}
};
const OrbitalModule@ getOrbitalModule(uint id) {
if(id >= modules.length)
return null;
return modules[id];
}
const OrbitalModule@ getOrbitalModule(const string& ident) {
OrbitalModule@ mod;
if(idents.get(ident, @mod))
return mod;
return null;
}
uint getOrbitalModuleCount() {
return modules.length;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = modules.length; i < cnt; ++i) {
auto type = modules[i];
file.addIdentifier(SI_Orbital, type.id, type.ident);
}
}
tidy final class OrbitalRequirements {
array<const ResourceType@> available;
array<bool> used;
array<uint> tmp;
void init(const array<Resource>& list) {
uint cnt = list.length;
available.length = 0;
used.length = 0;
available.reserve(cnt);
used.reserve(cnt);
for(uint i = 0; i < cnt; ++i) {
if(list[i].usable) {
available.insertLast(list[i].type);
used.insertLast(false);
}
}
}
void init(const array<Resource@>& list) {
uint cnt = list.length;
available.length = 0;
used.length = 0;
available.reserve(cnt);
used.reserve(cnt);
for(uint i = 0; i < cnt; ++i) {
if(list[i].usable) {
available.insertLast(list[i].type);
used.insertLast(false);
}
}
}
void init(Object& obj, bool direct = false) {
if(!obj.hasResources) {
available.length = 0;
used.length = 0;
return;
}
if(direct) {
uint cnt = obj.availableResourceCount;
available.length = 0;
used.length = 0;
available.reserve(cnt);
used.reserve(cnt);
for(uint i = 0; i < cnt; ++i) {
if(obj.availableResourceUsable[i]) {
available.insertLast(getResource(obj.availableResourceType[i]));
used.insertLast(false);
}
}
}
else {
array<Resource> resources;
resources.syncFrom(obj.getAvailableResources());
init(resources);
}
}
void _revert() {
for(uint i = 0, cnt = tmp.length; i < cnt; ++i)
used[tmp[i]] = false;
tmp.length = 0;
}
bool add(const OrbitalModule@ mod) {
return check(mod, true);
}
bool check(const OrbitalModule@ mod, bool apply = false) {
tmp.length = 0;
tmp.reserve(16);
//First, compute specific resource requirements
for(uint i = 0, cnt = mod.requirements.length; i < cnt; ++i) {
bool found = false;
for(uint n = 0, ncnt = available.length; n < ncnt; ++n) {
if(used[n])
continue;
if(available[n] is mod.requirements[i]) {
found = true;
used[n] = true;
tmp.insertLast(n);
}
}
if(!found) {
_revert();
return false;
}
}
//Find matches for affinities
for(uint i = 0; i < TR_COUNT; ++i) {
uint amount = mod.affinities[i];
for(uint c = 0; c < amount; ++c) {
uint mask = 1<<i;
uint found = uint(-1);
bool specif = false;
for(uint n = 0, ncnt = available.length; n < ncnt; ++n) {
if(used[n])
continue;
auto@ res = available[n];
for(uint j = 0, jcnt = res.affinities.length; j < jcnt; ++j) {
uint aff = res.affinities[j];
if(aff & mask != 0) {
bool isSpecif = aff == mask;
if(found == uint(-1) || (isSpecif && !specif)) {
found = n;
specif = isSpecif;
}
}
}
}
if(found == uint(-1)) {
_revert();
return false;
}
used[found] = true;
tmp.insertLast(found);
}
}
//Hook requirements
if(!mod.checkRequirements(this, apply)) {
_revert();
return false;
}
if(!apply)
_revert();
return true;
}
};
void addOrbitalModule(OrbitalModule@ mod) {
mod.id = modules.length;
modules.insertLast(mod);
idents.set(mod.ident, @mod);
}
void parseLine(string& line, OrbitalModule@ mod, ReadFile@ file) {
//Hook line
auto@ hook = cast<IOrbitalEffect>(parseHook(line, "orbital_effects::", instantiate=false, file=file));
if(hook !is null)
mod.hooks.insertLast(hook);
}
int getOrbitalModuleID(const string& ident) {
auto@ type = getOrbitalModule(ident);
if(type is null)
return -1;
return int(type.id);
}
string getOrbitalModuleIdent(int id) {
auto@ type = getOrbitalModule(id);
if(type is null)
return "";
return type.ident;
}
void loadOrbitalModules(const string& filename) {
ReadFile file(filename, true);
string key, value;
OrbitalModule@ mod;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
string line = file.line;
parseLine(line, mod, file);
}
else if(key.equals_nocase("Module")) {
if(mod !is null)
addOrbitalModule(mod);
@mod = OrbitalModule();
mod.ident = value;
}
else if(mod is null) {
file.error("Missing Module: 'ID' line");
}
else if(key.equals_nocase("Name")) {
mod.name = localize(value);
}
else if(key.equals_nocase("Blurb")) {
mod.blurb = localize(value);
}
else if(key.equals_nocase("Description")) {
mod.description = localize(value);
}
else if(key.equals_nocase("Icon")) {
mod.icon = getSprite(value);
}
else if(key.equals_nocase("Icon Size")) {
mod.iconSize = toDouble(value);
}
else if(key.equals_nocase("Distant Icon")) {
mod.distantIcon = getSprite(value);
}
else if(key.equals_nocase("Strategic Icon")) {
mod.strategicIcon = getSprite(value);
}
else if(key.equals_nocase("Spin")) {
mod.spin = toDouble(value);
}
else if(key.equals_nocase("Core")) {
mod.isCore = toBool(value);
}
else if(key.equals_nocase("Standalone")) {
mod.isStandalone = toBool(value);
if(mod.isStandalone)
mod.isCore = true;
}
else if(key.equals_nocase("Solid")) {
mod.isSolid = toBool(value);
}
else if(key.equals_nocase("Unique")) {
mod.isUnique = toBool(value);
}
else if(key.equals_nocase("Maintenance")) {
mod.maintenance = toInt(value);
}
else if(key.equals_nocase("Build Cost")) {
mod.buildCost = toInt(value);
}
else if(key.equals_nocase("Labor Cost")) {
mod.laborCost = toDouble(value);
}
else if(key.equals_nocase("Health")) {
mod.health = toDouble(value);
}
else if(key.equals_nocase("Armor")) {
mod.armor = toDouble(value);
}
else if(key.equals_nocase("Size")) {
mod.size = toDouble(value);
}
else if(key.equals_nocase("Model")) {
@mod.model = getModel(value);
}
else if(key.equals_nocase("Material")) {
@mod.material = getMaterial(value);
}
else if(key.equals_nocase("Combat Repair")) {
mod.combatRepair = toBool(value);
}
else if(key.equals_nocase("Can Fling")) {
mod.canFling = toBool(value);
}
else if(key.equals_nocase("Mass")) {
mod.mass = toDouble(value);
}
else if(key.equals_nocase("Require Affinity")) {
array<string>@ parts = value.split(" ");
if(parts.length != 2) {
file.error("Invalid affinity requirement: "+value);
return;
}
uint res = getTileResource(parts[1]);
if(res == TR_NULL) {
file.error("Invalid affinity resource: "+parts[1]);
return;
}
uint amt = toUInt(parts[0]);
mod.affinities[res] += amt;
mod.totalRequirementCount += amt;
}
else if(key.equals_nocase("Require Resource")) {
auto@ res = getResource(value);
if(res is null) {
file.error("Invalid resource: "+value);
return;
}
mod.requirements.insertLast(res);
mod.totalRequirementCount += 1;
}
else if(key.equals_nocase("AI")) {
auto@ hook = parseHook(value, "ai.orbitals::", instantiate=false, file=file);
if(hook !is null)
mod.ai.insertLast(hook);
else
file.error("Could not find AI hook "+value);
}
else {
string line = file.line;
parseLine(line, mod, file);
}
}
if(mod !is null)
addOrbitalModule(mod);
}
void preInit() {
FileList list("data/orbitals", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadOrbitalModules(list.path[i]);
}
void init() {
auto@ list = modules;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ type = list[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n)
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(type.hooks[n])+" in "+type.ident);
for(uint n = 0, ncnt = type.ai.length; n < ncnt; ++n) {
if(!type.ai[n].instantiate())
error("Could not instantiate AI hook: "+addrstr(type.ai[n])+" in orbital "+type.ident);
}
}
}
+42
View File
@@ -0,0 +1,42 @@
import pickups;
from pickups import IPickupHook, PickupHook;
import hooks;
import bonus_effects;
class OnClear : PickupHook {
BonusEffect@ hook;
Document doc("Trigger an effect on the flagship that cleared this camp, immediately.");
Argument effect(AT_Hook, "bonus_effects::BonusEffect");
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(effect.str, "bonus_effects::", required=false));
if(hook is null) {
error("OnClear(): could not find inner hook: "+escape(effect.str));
return false;
}
return PickupHook::instantiate();
}
#section server
void onClear(Pickup& pickup, Object& obj) const {
if(hook !is null)
hook.activate(obj, obj.owner);
}
#section all
};
class TakeOnClear : PickupHook {
Document doc("This pickup is immediately taken when the camp is cleared.");
#section server
void onClear(Pickup& pickup, Object& obj) const {
auto@ type = getPickupType(pickup.PickupType);
if(type is null)
return;
type.onPickup(pickup, obj);
pickup.destroy();
}
#section all
};
+127
View File
@@ -0,0 +1,127 @@
#priority init 1000
import hooks;
from saving import SaveIdentifier;
export PickupType;
export getPickupTypeCount, getPickupType, addPickupType;
export getDistributedPickupType;
tidy final class PickupType {
uint id = 0;
string ident;
string name;
string description;
string verb = locale::VERB_PICKUP;
string dlc;
array<IPickupHook@> hooks;
double physicalSize = 5.0;
const Model@ model = model::Research_Station;
const Material@ material = material::GenericPBR_Research_Station;
double frequency = 1.0;
const SpriteSheet@ iconSheet = spritesheet::OrbitalIcons;
uint iconIndex = 12;
double get_totalRarity() {
return 1.0 / frequency;
}
string getName(Pickup& pickup) const {
return name;
}
bool canPickup(Pickup& pickup, Object& obj) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].canPickup(pickup, obj))
return false;
}
return true;
}
void onPickup(Pickup& pickup, Object& obj) const {
uint repeats = obj.owner.RemnantPickupMult;
if(frequency == 0.0)
repeats = 1;
for(uint n = 0; n < repeats; ++n) {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].onPickup(pickup, obj);
}
}
void onClear(Pickup& pickup, Object& obj) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].onClear(pickup, obj);
}
};
interface IPickupHook {
bool canPickup(Pickup& pickup, Object& obj) const;
void onPickup(Pickup& pickup, Object& obj) const;
void onClear(Pickup& pickup, Object& obj) const;
};
class PickupHook : Hook, IPickupHook {
bool canPickup(Pickup& pickup, Object& obj) const { return true; }
void onPickup(Pickup& pickup, Object& obj) const {}
void onClear(Pickup& pickup, Object& obj) const {}
};
array<PickupType@> list;
dictionary idents;
double totalFrequency = 0.0;
uint getPickupTypeCount() {
return list.length;
}
const PickupType@ getPickupType(uint id) {
if(id < list.length)
return list[id];
else
return null;
}
const PickupType@ getDistributedPickupType() {
double num = randomd(0, totalFrequency);
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
const PickupType@ type = list[i];
double freq = type.frequency;
if(num <= freq)
return type;
num -= freq;
}
return list[list.length-1];
}
const PickupType@ getPickupType(const string& name) {
PickupType@ type;
idents.get(name, @type);
return type;
}
void addPickupType(PickupType@ type) {
type.id = list.length;
list.insertLast(type);
idents.set(type.ident, @type);
totalFrequency += type.frequency;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
PickupType@ type = list[i];
file.addIdentifier(SI_Pickup, type.id, type.ident);
}
}
void init() {
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ type = list[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n)
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(type.hooks[n])+" in "+type.ident);
}
}
File diff suppressed because it is too large Load Diff
+522
View File
@@ -0,0 +1,522 @@
import saving;
import hooks;
enum RandomTriggerMode {
RTM_Random,
};
class RandomEvent {
uint id;
string ident;
string name;
string text;
array<EventOption@> options;
Targets targets;
RandomTriggerMode mode = RTM_Random;
double frequency = 1.0;
bool unique = true;
double timer = 180.0;
array<IRandomEventHook@> hooks;
RandomEvent() {
targets.add("Owner", TT_Empire);
}
void init() {
for(uint n = 0, ncnt = hooks.length; n < ncnt; ++n) {
if(!cast<Hook>(hooks[n]).instantiate())
error("Could not instantiate hook "+addrstr(hooks[n])+" on random event "+ident);
else
cast<Hook>(hooks[n]).initTargets(targets);
}
for(uint i = 0, cnt = options.length; i < cnt; ++i)
options[i].init(this);
}
const EventOption@ getOption(uint id) const {
for(uint i = 0, cnt = options.length; i < cnt; ++i) {
if(options[i].id == id)
return options[i];
}
return null;
}
};
class EventOption {
uint id;
string ident;
string text;
Sprite icon;
bool defaultOption = false;
bool safe = true;
array<EventResult@> inner;
EventResult result;
void init(RandomEvent@ evt) {
result.init(evt);
for(uint i = 0, cnt = inner.length; i < cnt; ++i)
inner[i].init(evt);
}
bool shouldAdd(CurrentEvent& evt) const {
for(uint i = 0, cnt = result.block.hooks.length; i < cnt; ++i) {
if(!result.block.hooks[i].shouldAdd(evt, this))
return false;
}
return true;
}
void trigger(CurrentEvent& evt) const {
result.trigger(evt, this);
double total = 0.0;
for(uint i = 0, cnt = inner.length; i < cnt; ++i)
total += inner[i].frequency;
double roll = randomd(0.0, total);
for(uint i = 0, cnt = inner.length; i < cnt; ++i) {
roll -= inner[i].frequency;
if(roll <= 0) {
inner[i].trigger(evt, this);
break;
}
}
}
};
class EventResult {
double frequency = 1.0;
array<OnBlock@> inner;
OnBlock block;
void init(RandomEvent@ evt) {
block.init(evt);
for(uint i = 0, cnt = inner.length; i < cnt; ++i)
inner[i].init(evt);
}
void trigger(CurrentEvent& evt, const EventOption& opt) const {
block.trigger(evt, opt);
for(uint i = 0, cnt = inner.length; i < cnt; ++i)
inner[i].trigger(evt, opt);
}
};
class OnBlock {
array<IRandomOptionHook@> hooks;
string targetName;
uint targetIndex = uint(-1);
void init(RandomEvent@ evt) {
for(uint n = 0, ncnt = hooks.length; n < ncnt; ++n) {
if(!cast<Hook>(hooks[n]).instantiate())
error("Could not instantiate hook "+addrstr(hooks[n])+" on random event.");
else
cast<Hook>(hooks[n]).initTargets(evt.targets);
}
if(targetName.length != 0) {
targetIndex = uint(evt.targets.getIndex(targetName));
if(targetIndex >= evt.targets.length)
error("Error: 'On' block could not find target '"+targetName+"' in event "+evt.ident);
}
}
void trigger(CurrentEvent& evt, const EventOption& opt) const {
for(uint n = 0, ncnt = hooks.length; n < ncnt; ++n) {
if(targetIndex >= evt.targets.length)
hooks[n].trigger(evt, opt, null);
else
hooks[n].trigger(evt, opt, evt.targets[targetIndex]);
}
}
};
interface EventContainer {
void create(CurrentEvent@ evt);
};
class CurrentEvent : Serializable, Savable {
int id = -1;
const RandomEvent@ type;
Targets targets;
array<const EventOption@> options;
double timer = -1;
CurrentEvent() {}
bool consider() {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].consider(this))
return false;
}
for(uint i = 0, cnt = type.options.length; i < cnt; ++i) {
if(type.options[i].shouldAdd(this))
options.insertLast(type.options[i]);
}
return options.length != 0;
}
void create() {
timer = type.timer;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].create(this);
}
Empire@ get_owner() const {
if(targets.length == 0)
return null;
return targets[0].emp;
}
void set_owner(Empire@ emp) {
if(targets.length == 0)
return;
@targets[0].emp = emp;
targets[0].filled = true;
}
bool isValidTarget(uint index, const Target@ targ) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].isValidTarget(this, index, targ))
return false;
}
return true;
}
void clear(const RandomEvent& type) {
@this.type = type;
targets = type.targets;
options.length = 0;
timer = 0;
}
void write(Message& msg) {
msg.writeSmall(id);
msg.writeSmall(type.id);
msg << targets;
msg << timer;
msg.writeSmall(options.length);
for(uint i = 0, cnt = options.length; i < cnt; ++i)
msg.writeSmall(options[i].id);
}
void read(Message& msg) {
id = msg.readSmall();
@type = getRandomEvent(msg.readSmall());
msg >> targets;
msg >> timer;
options.length = msg.readSmall();
for(uint i = 0, cnt = options.length; i < cnt; ++i)
@options[i] = type.getOption(msg.readSmall());
}
void save(SaveFile& file) {
file << id;
file.writeIdentifier(SI_RandomEvent, type.id);
file << targets;
file << timer;
uint cnt = options.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file.writeIdentifier(SI_RandomEventOption, options[i].id);
}
void load(SaveFile& file) {
file >> id;
@type = getRandomEvent(file.readIdentifier(SI_RandomEvent));
file >> targets;
file >> timer;
uint cnt = 0;
file >> cnt;
options.length = 0;
options.reserve(cnt);
for(uint i = 0; i < cnt; ++i) {
auto@ opt = type.getOption(file.readIdentifier(SI_RandomEventOption));
if(opt !is null)
options.insertLast(opt);
}
}
};
interface IRandomEventHook {
bool consider(CurrentEvent& evt) const;
void create(CurrentEvent& evt) const;
bool isValidTarget(CurrentEvent& evt, uint index, const Target@ targ) const;
};
class RandomEventHook : Hook, IRandomEventHook {
bool consider(CurrentEvent& evt) const { return true; }
void create(CurrentEvent& evt) const {}
bool isValidTarget(CurrentEvent& evt, uint index, const Target@ targ) const { return true; }
};
interface IRandomOptionHook {
bool shouldAdd(CurrentEvent& evt, const EventOption& option) const;
void trigger(CurrentEvent& evt, const EventOption& option, const Target@ targ) const;
};
class RandomOptionHook : Hook, IRandomOptionHook {
bool shouldAdd(CurrentEvent& evt, const EventOption& option) const { return true; }
void trigger(CurrentEvent& evt, const EventOption& option, const Target@ targ) const {}
};
RandomEvent@[] randomEvents;
uint optionId = 0;
dictionary idents;
const RandomEvent@ getRandomEvent(uint id) {
if(id >= randomEvents.length)
return null;
return randomEvents[id];
}
const RandomEvent@ getRandomEvent(const string& ident) {
RandomEvent@ camp;
if(idents.get(ident, @camp))
return camp;
return null;
}
int getRandomEventID(const string& ident) {
auto@ type = getRandomEvent(ident);
if(type is null)
return -1;
return int(type.id);
}
string getRandomEventIdent(int id) {
auto@ type = getRandomEvent(id);
if(type is null)
return "";
return type.ident;
}
uint getRandomEventCount() {
return randomEvents.length;
}
void addRandomEvent(RandomEvent@ type) {
type.id = randomEvents.length;
randomEvents.insertLast(type);
idents.set(type.ident, @type);
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = randomEvents.length; i < cnt; ++i) {
auto type = randomEvents[i];
file.addIdentifier(SI_RandomEvent, type.id, type.ident);
for(uint n = 0, ncnt = type.options.length; n < ncnt; ++n) {
auto@ opt = type.options[n];
file.addIdentifier(SI_RandomEventOption, opt.id, opt.ident);
}
}
}
void loadRandomEvents(const string& filename) {
ReadFile file(filename, true);
while(true) {
if(file.key.equals_nocase("Event")) {
if(!loadEvent(file))
break;
}
else {
if(!file++)
break;
}
}
}
bool loadEvent(ReadFile@ file) {
RandomEvent evt;
evt.ident = file.value;
addRandomEvent(evt);
int blockIndent = file.indent;
if(!file++)
return false;
while(true) {
if(file.indent <= blockIndent)
return true;
if(file.fullLine) {
auto@ hook = cast<IRandomEventHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
evt.hooks.insertLast(hook);
if(!file++)
return false;
if(file.indent <= blockIndent)
return true;
}
else if(file.key.equals_nocase("Option")) {
if(!loadOption(evt, file))
return false;
}
else {
if(file.key.equals_nocase("Name")) {
evt.name = localize(file.value);
}
else if(file.key.equals_nocase("Text")) {
evt.text = localize(file.value);
}
else if(file.key.equals_nocase("Frequency")) {
evt.frequency = toDouble(file.value);
}
else if(file.key.equals_nocase("Unique")) {
evt.unique = toBool(file.value);
}
else if(file.key.equals_nocase("Target")) {
parseTarget(evt.targets, file.value);
}
else if(file.key.equals_nocase("Timer")) {
evt.timer = toDouble(file.value);
}
else if(file.key.equals_nocase("Mode")) {
if(file.value.equals_nocase("Random"))
evt.mode = RTM_Random;
else
file.error("Unknown random event mode: "+file.value);
}
else {
auto@ hook = cast<IRandomEventHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
evt.hooks.insertLast(hook);
}
if(!file++)
return false;
}
}
return true;
}
bool loadOption(RandomEvent@ evt, ReadFile@ file) {
EventOption opt;
opt.id = optionId++;
if(file.value.length == 0)
opt.ident = evt.ident+"::__"+evt.options.length;
else
opt.ident = evt.ident+"::"+file.value;
evt.options.insertLast(opt);
int blockIndent = file.indent;
if(!file++)
return false;
while(true) {
if(file.indent <= blockIndent)
return true;
if(file.fullLine) {
auto@ hook = cast<IRandomOptionHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
opt.result.block.hooks.insertLast(hook);
if(!file++)
return false;
}
else if(file.key.equals_nocase("Result")) {
if(!loadResult(evt, opt, file))
return false;
}
else if(file.key.equals_nocase("On")) {
if(!loadOnBlock(evt, opt.result, file))
return false;
}
else {
if(file.key.equals_nocase("Text")) {
opt.text = localize(file.value);
}
else if(file.key.equals_nocase("Icon")) {
opt.icon = getSprite(file.value);
}
else if(file.key.equals_nocase("Default")) {
opt.defaultOption = toBool(file.value);
}
else if(file.key.equals_nocase("Safe")) {
opt.safe = toBool(file.value);
}
else {
auto@ hook = cast<IRandomOptionHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
opt.result.block.hooks.insertLast(hook);
}
if(!file++)
return false;
}
}
return true;
}
bool loadResult(RandomEvent@ evt, EventOption@ opt, ReadFile@ file) {
EventResult res;
if(file.value.length != 0) {
if(file.value[file.value.length-1] == '%')
res.frequency = toDouble(file.value.substr(0, file.value.length-1)) / 100.0;
else
res.frequency = toDouble(file.value);
}
opt.inner.insertLast(res);
int blockIndent = file.indent;
if(!file++)
return false;
while(true) {
if(file.indent <= blockIndent)
return true;
if(file.fullLine) {
auto@ hook = cast<IRandomOptionHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
res.block.hooks.insertLast(hook);
if(!file++)
return false;
}
else if(file.key.equals_nocase("On")) {
if(!loadOnBlock(evt, res, file))
return false;
}
else {
{
auto@ hook = cast<IRandomOptionHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
res.block.hooks.insertLast(hook);
}
if(!file++)
return false;
}
}
return true;
}
bool loadOnBlock(RandomEvent@ evt, EventResult@ res, ReadFile@ file) {
OnBlock block;
block.targetName = file.value;
res.inner.insertLast(block);
int blockIndent = file.indent;
if(!file++)
return false;
while(true) {
if(file.indent <= blockIndent)
return true;
{
auto@ hook = cast<IRandomOptionHook>(parseHook(file.line, "event_effects::", instantiate=false));
if(hook !is null)
block.hooks.insertLast(hook);
}
if(!file++)
return false;
}
return true;
}
void preInit() {
FileList list("data/random_events", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadRandomEvents(list.path[i]);
}
void init() {
for(uint i = 0, cnt = randomEvents.length; i < cnt; ++i)
randomEvents[i].init();
}
+88
View File
@@ -0,0 +1,88 @@
#priority init 2000
from saving import SaveIdentifier;
export RegionEffectType, RegionEffect;
export getRegionEffectCount, getRegionEffect;
class RegionEffectType {
uint id = 0;
string ident;
string name;
string description;
AnyClass@ implementation;
string implementationClass;
RegionEffect@ create() const {
RegionEffect@ eff = cast<RegionEffect>(implementation.create());
@eff.type = this;
return eff;
}
};
tidy class RegionEffect {
int id = -1;
const RegionEffectType@ type;
Empire@ forEmpire;
void start(Region& region) {
}
bool tick(Region& region, double time) {
return true;
}
void end(Region& region) {
}
void changeEffectOwner(Region& region, Empire@ prevOwner, Empire@ newOwner) {
}
void ownerChange(Region& region, Object& obj, Empire@ prevOwner, Empire@ newOwner) {
}
void enable(Region& region, Object& obj) {
}
void disable(Region& region, Object& obj) {
}
void load(SaveFile& file) {
}
void save(SaveFile& file) {
}
};
array<RegionEffectType@> effects;
dictionary effectIdents;
uint getRegionEffectCount() {
return effects.length;
}
const RegionEffectType@ getRegionEffect(uint id) {
if(id < effects.length)
return effects[id];
else
return null;
}
const RegionEffectType@ getRegionEffect(const string& name) {
RegionEffectType@ eff;
effectIdents.get(name, @eff);
return eff;
}
void addRegionEffect(RegionEffectType@ eff) {
eff.id = effects.length;
effects.insertLast(eff);
effectIdents.set(eff.ident, @eff);
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = effects.length; i < cnt; ++i) {
RegionEffectType@ type = effects[i];
file.addIdentifier(SI_RegionEffect, type.id, type.ident);
}
}
@@ -0,0 +1,43 @@
#include "include/region_effect_spec.as"
class _Type : RegionEffectType {
_Type() {
ident = "GrantVision";
implementationClass = "GrantVision";
}
};
class GrantVision : RegionEffect {
double timer = 0.0;
GrantVision(Empire@ emp, double timer) {
@this.forEmpire = emp;
this.timer = timer;
@this.type = definition;
}
#section server
void save(SaveFile& file) override {
file << timer;
}
void load(SaveFile& file) override {
file >> timer;
}
bool tick(Region& region, double time) override {
timer -= time;
if(timer <= 0)
return false;
return true;
}
void start(Region& region) override {
region.grantVision(forEmpire);
}
void end(Region& region) override {
region.revokeVision(forEmpire);
}
#section all
};
@@ -0,0 +1,24 @@
#include "include/region_effect_spec.as"
class _Type : RegionEffectType {
_Type() {
ident = "ProtectedZone";
implementationClass = "ProtectedZone";
}
};
class ProtectedZone : RegionEffect {
bool tick(Region& region, double time) override {
region.ProtectedMask |= forEmpire.mask;
return true;
}
void changeEffectOwner(Region& region, Empire@ prevOwner, Empire@ newOwner) override {
region.ProtectedMask &= ~prevOwner.mask;
region.ProtectedMask |= newOwner.mask;
}
void end(Region& region) override {
region.ProtectedMask &= ~forEmpire.mask;
}
};
@@ -0,0 +1,82 @@
#include "include/region_effect_spec.as"
export ZealotRegion, ZealotRegionEffect, createZealotRegionEffect;
const RegionEffectType@ get_ZealotRegion() {
return definition;
}
ZealotRegionEffect@ createZealotRegionEffect(Empire@ empire, Empire@ other) {
ZealotRegionEffect eff;
@eff.type = definition;
@eff.forEmpire = empire;
@eff.other = other;
return eff;
}
class _Type : RegionEffectType {
_Type() {
ident = "ZealotRegion";
implementationClass = "ZealotRegionEffect";
}
};
const uint MAX_PER_TICK = 100;
const double STR_FACTOR = 0.5 / (6.0 * 60.0);
class ZealotRegionEffect : RegionEffect {
Empire@ other;
double accStr = 0.0;
double storedTime = 0.0;
#section server
void save(SaveFile& file) override {
file << other;
file << accStr;
file << storedTime;
}
void load(SaveFile& file) override {
file >> other;
file >> accStr;
file >> storedTime;
}
bool tick(Region& region, double time) override {
storedTime += time;
if(storedTime < 1.0)
return true;
double str = region.getStrength(other) * STR_FACTOR * storedTime;
accStr += str;
storedTime = 0.0;
if(accStr > 1.0) {
uint objCount = region.objectCount;
uint index = randomi(0, objCount-1);
uint cnt = min(objCount, MAX_PER_TICK);
for(uint i = 0; i < cnt; ++i) {
Ship@ obj = cast<Ship>(region.objects[i]);
if(obj !is null && obj.owner is other) {
//Check if we can take over this ship
if(!obj.hasLeaderAI || obj.supportCount == 0) {
double size = obj.blueprint.design.size;
double chance = accStr / size;
chance *= chance;
if(chance > 1.0 || randomd() < chance) {
@obj.owner = forEmpire;
accStr -= size;
if(accStr < 1.0)
break;
}
}
}
index = (index+1) % cnt;
}
}
return true;
}
#section all
};
+397
View File
@@ -0,0 +1,397 @@
import generic_hooks;
tidy class GenericRepeatHook : EmpireEffect {
EmpireEffect@ empHook;
GenericEffect@ hook;
uint getRepeats(Empire& emp, any@ data) const {
return 0;
}
uint getRepeats(Object& obj, any@ data) const {
return getRepeats(obj.owner, data);
}
bool withHook(const string& str) {
@hook = cast<GenericEffect>(parseHook(str, "planet_effects::", required = false));
@empHook = cast<EmpireEffect>(parseHook(str, "empire_effects::", required = false));
if(hook is null && empHook is null) {
error("Repeat<>(): could not find inner hook: "+escape(str));
return false;
}
return true;
}
void enable(Empire& emp, any@ data) const override {
array<any> datlist;
data.store(@datlist);
}
void tick(Empire& emp, any@ data, double time) const override {
array<any>@ datlist;
data.retrieve(@datlist);
if(datlist is null)
return;
uint oldCnt = datlist.length;
uint newCnt = getRepeats(emp, data);
for(uint i = newCnt; i < oldCnt; ++i)
empHook.disable(emp, datlist[i]);
datlist.length = newCnt;
for(uint i = oldCnt; i < newCnt; ++i)
empHook.enable(emp, datlist[i]);
for(uint i = 0; i < newCnt; ++i)
empHook.tick(emp, datlist[i], time);
}
void disable(Empire& emp, any@ data) const override {
array<any>@ datlist;
data.retrieve(@datlist);
if(datlist is null)
return;
for(uint i = 0, cnt = datlist.length; i < cnt; ++i)
empHook.disable(emp, datlist[i]);
datlist.length = 0;
@datlist = null;
data.store(@datlist);
}
void enable(Object& obj, any@ data) const override {
if(hook is null) {
enable(obj.owner, data);
return;
}
array<any> datlist;
data.store(@datlist);
}
void tick(Object& obj, any@ data, double time) const override {
if(hook is null) {
tick(obj.owner, data, time);
return;
}
array<any>@ datlist;
data.retrieve(@datlist);
if(datlist is null)
return;
uint oldCnt = datlist.length;
uint newCnt = getRepeats(obj, data);
for(uint i = newCnt; i < oldCnt; ++i)
hook.disable(obj, datlist[i]);
datlist.length = newCnt;
for(uint i = oldCnt; i < newCnt; ++i)
hook.enable(obj, datlist[i]);
for(uint i = 0; i < newCnt; ++i)
hook.tick(obj, datlist[i], time);
}
void disable(Object& obj, any@ data) const override {
if(hook is null) {
disable(obj.owner, data);
return;
}
array<any>@ datlist;
data.retrieve(@datlist);
if(datlist is null)
return;
for(uint i = 0, cnt = datlist.length; i < cnt; ++i)
hook.disable(obj, datlist[i]);
datlist.length = 0;
@datlist = null;
data.store(@datlist);
}
void ownerChange(Object& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const override {
if(hook is null) {
disable(prevOwner, data);
enable(newOwner, data);
return;
}
array<any>@ datlist;
data.retrieve(@datlist);
if(datlist is null)
return;
for(uint i = 0, cnt = datlist.length; i < cnt; ++i)
hook.ownerChange(obj, datlist[i], prevOwner, newOwner);
}
void regionChange(Object& obj, any@ data, Region@ fromRegion, Region@ toRegion) const override {
array<any>@ datlist;
data.retrieve(@datlist);
if(datlist is null)
return;
for(uint i = 0, cnt = datlist.length; i < cnt; ++i)
hook.regionChange(obj, datlist[i], fromRegion, toRegion);
}
void save(any@ data, SaveFile& file) const override {
array<any>@ datlist;
data.retrieve(@datlist);
uint cnt = 0;
if(datlist is null) {
file << cnt;
return;
}
cnt = datlist.length;
file << cnt;
for(uint i = 0; i < cnt; ++i) {
if(hook !is null)
hook.save(datlist[i], file);
else if(empHook !is null)
empHook.save(datlist[i], file);
}
}
void load(any@ data, SaveFile& file) const override {
array<any> datlist;
uint cnt = 0;
file >> cnt;
datlist.length = cnt;
for(uint i = 0; i < cnt; ++i) {
if(hook !is null)
hook.load(datlist[i], file);
else if(empHook !is null)
empHook.load(datlist[i], file);
}
data.store(@datlist);
}
};
tidy final class Repeat : GenericRepeatHook {
Document doc("Repeat an inner hook multiple times.");
Argument amount(AT_Integer, doc="Amount of times to repeat.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
Argument per_import(AT_Integer, "0", doc="Additional repeats to add for every imported resource.");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Object& obj, any@ data) const override {
uint newCnt = arguments[0].integer;
uint perImport = arguments[2].integer;
if(perImport != 0)
newCnt += obj.usableResourceCount * perImport;
return newCnt;
}
uint getRepeats(Empire& emp, any@ data) const override {
uint newCnt = arguments[0].integer;
return newCnt;
}
#section all
};
tidy final class RepeatEmpireAttribute : GenericRepeatHook {
Document doc("Repeat a hook an amount of times as stored in an empire attribute of the owner.");
Argument attribute(AT_EmpAttribute, doc="Attribute to take repeats from. Naming a new attribute will create it with a default value of 0.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Empire& emp, any@ data) const override {
return uint(emp.getAttribute(attribute.integer));
}
#section all
};
tidy final class RepeatPlanetLevel : GenericRepeatHook {
Document doc("Repeat a hook for every planet level.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
Argument base(AT_Decimal, "0", doc="Base amount of repeats to add regardless of level.");
Argument per_level_bonus(AT_Decimal, "1", doc="Amount of repeats to add per planet level.");
bool instantiate() override {
@hook = cast<GenericEffect>(parseHook(hookID.str, "planet_effects::"));
if(hook is null) {
error("Repeat(): could not find inner hook: "+escape(hookID.str));
return false;
}
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Object& obj, any@ data) const override {
double cnt = base.decimal;
if(per_level_bonus.decimal != 0 && obj.isPlanet)
cnt += per_level_bonus.decimal * obj.level;
return cnt;
}
#section all
};
tidy final class RepeatExtended : GenericRepeatHook {
Document doc("Repeat a hook an amount of times as stored in an empire attribute of the owner.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
Argument base_attribute(AT_EmpAttribute, EMPTY_DEFAULT, doc="Attribute to add to new repeats.");
Argument multiply_attribute(AT_EmpAttribute, EMPTY_DEFAULT, doc="Attribute to multiply the whole repeat amount by.");
Argument base(AT_Decimal, "0", doc="Base amount of repeats to add.");
Argument multiplier(AT_Decimal, "1", doc="Multiplication to empire attribute before taking the repeats.");
Argument per_level_bonus(AT_Decimal, "0", doc="If this is applied to a planet, add this many repeats per planet level.");
Argument per_gametime_bonus(AT_Decimal, "0", doc="Adds more repeats for every minute of gametime that has passed since the beginning of the game.");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Object& obj, any@ data) const override {
double cnt = base.decimal;
if(base_attribute.integer != -1)
cnt += obj.owner.getAttribute(base_attribute.integer);
if(per_level_bonus.decimal != 0 && obj.isPlanet)
cnt += per_level_bonus.decimal * obj.level;
cnt += per_gametime_bonus.decimal * (gameTime / 60.0);
cnt *= multiplier.decimal;
if(multiply_attribute.integer != -1)
cnt *= obj.owner.getAttribute(multiply_attribute.integer);
return cnt;
}
uint getRepeats(Empire& emp, any@ data) const override {
double cnt = base.decimal;
if(base_attribute.integer != -1)
cnt += emp.getAttribute(base_attribute.integer);
cnt += per_gametime_bonus.decimal * (gameTime / 60.0);
cnt *= multiplier.decimal;
if(multiply_attribute.integer != -1)
cnt *= emp.getAttribute(multiply_attribute.integer);
return cnt;
}
#section all
};
tidy final class RepeatEmpirePopulation : GenericRepeatHook {
Document doc("Repeat a hook based on the difference between an attribute value and the total empire population.");
Argument interval(AT_Decimal, doc="Repeat the hook once for every <interval> population the empire has.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Empire& emp, any@ data) const override {
return floor(double(emp.TotalPopulation) / interval.decimal);
}
#section all
};
tidy final class RepeatPopulationCoverage : GenericRepeatHook {
Document doc("Repeat a hook based on the difference between an attribute value and the total empire population.");
Argument attribute(AT_EmpAttribute, doc="Attribute to require covering of population.");
Argument interval(AT_Decimal, doc="Repeat the hook once for every <interval> population that is not covered by the attribute.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Empire& emp, any@ data) const override {
double diff = emp.TotalPopulation - emp.getAttribute(attribute.integer);
if(diff <= 0)
return 0;
return ceil(diff / interval.decimal);
}
#section all
};
tidy final class RepeatPressure : GenericRepeatHook {
Document doc("Repeat a hook based on how much of a particular pressure is available locally.");
Argument type(AT_TileResource, doc="Resource of pressure to check.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
Argument multiplier(AT_Decimal, "1", doc="How many repeats per pressure.");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Object& obj, any@ data) const override {
return round(double(obj.resourcePressure[type.integer]) * multiplier.decimal);
}
#section all
};
tidy final class RepeatFoodCount : GenericRepeatHook {
Document doc("Repeat a hook for every food resource present.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Object& obj, any@ data) const override {
return obj.getFoodCount();
}
#section all
};
tidy final class RepeatEnergyStored : GenericRepeatHook {
Document doc("Repeat a hook depending on how much energy is stored.");
Argument step(AT_Decimal, doc="How much energy should be stored per repeat.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Empire& emp, any@ data) const {
return floor(emp.EnergyStored / step.decimal);
}
#section all
};
tidy final class RepeatEmpireContacts : GenericRepeatHook {
Document doc("Repeat a hook with the amount of empires that have been contacted.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
Argument maximum(AT_Integer, "-1", doc="Maximum contact count.");
bool instantiate() override {
if(!withHook(hookID.str))
return false;
return GenericEffect::instantiate();
}
#section server
uint getRepeats(Empire& emp, any@ data) const {
uint contacts = 0;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ other = getEmpire(i);
if(emp is other || !other.major)
continue;
if(emp.ContactMask & other.mask != 0)
contacts += 1;
}
if(contacts > uint(maximum.integer))
contacts = uint(maximum.integer);
return contacts;
}
#section all
};
+424
View File
@@ -0,0 +1,424 @@
import hooks;
import orbitals;
from orbitals import IOrbitalEffect;
import buildings;
from buildings import IBuildingHook;
import constructions;
from constructions import IConstructionHook;
import resources;
#section server
from construction.Constructible import Constructible;
#section server-side
from influence_global import getSenateLeader;
#section all
class Requirement : Hook, IOrbitalEffect, IBuildingHook, IConstructionHook {
bool meets(Object& obj, bool ignoreState = false) const {
return true;
}
string getFailError(Object& obj, bool ignoreState = false) const {
return "";
}
//Orbitals
void onEnable(Orbital& obj, any@ data) const {}
void onDisable(Orbital& obj, any@ data) const {}
void onCreate(Orbital& obj, any@ data) const {}
void onDestroy(Orbital& obj, any@ data) const {}
void onTick(Orbital& obj, any@ data, double time) const {}
void onOwnerChange(Orbital& obj, any@ data, Empire@ prevOwner, Empire@ newOwner) const {}
void onRegionChange(Orbital& obj, any@ data, Region@ prevRegion, Region@ newRegion) const {}
void onMakeGraphics(Orbital& obj, any@ data, OrbitalNode@ node) const {}
bool checkRequirements(OrbitalRequirements@ reqs, bool apply) const { return true; }
void revertRequirements(OrbitalRequirements@ reqs) const {}
bool canBuildBy(Object@ obj, bool ignoreCost) const { if(obj is null) return false; return meets(obj); }
bool canBuildAt(Object@ obj, const vec3d& pos) const { if(obj is null) return false; return meets(obj); }
bool canBuildOn(Orbital& obj) const { if(obj is null) return false; return meets(obj); }
string getBuildError(Object@ obj, const vec3d& pos) const { return ""; }
bool shouldDisable(Orbital& obj, any@ data) const { return false; }
bool shouldEnable(Orbital& obj, any@ data) const { return true; }
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
void write(any@ data, Message& msg) const {}
void read(any@ data, Message& msg) const {}
void onKill(Orbital& obj, any@ data, Empire@ killedBy) const {}
bool getValue(Player& pl, Orbital& obj, any@ data, uint index, double& value) const { return false; }
bool sendValue(Player& pl, Orbital& obj, any@ data, uint index, double value) const { return false; }
bool getDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@& value) const { return false; }
bool sendDesign(Player& pl, Orbital& obj, any@ data, uint index, const Design@ value) const { return false; }
bool getObject(Player& pl, Orbital& obj, any@ data, uint index, Object@& value) const { return false; }
bool sendObject(Player& pl, Orbital& obj, any@ data, uint index, Object@ value) const { return false; }
bool getData(Orbital& obj, string& txt, bool enabled) const { return false; }
void reverse(Object& obj, bool cancel) const {}
//Buildings
uint hookIndex = 0;
void initialize(BuildingType@ type, uint index) { hookIndex = index; }
void startConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void cancelConstruction(Object& obj, SurfaceBuilding@ bld) const {}
void complete(Object& obj, SurfaceBuilding@ bld) const {}
void ownerChange(Object& obj, SurfaceBuilding@ bld, Empire@ prevOwner, Empire@ newOwner) const {}
void remove(Object& obj, SurfaceBuilding@ bld) const {}
void tick(Object& obj, SurfaceBuilding@ bld, double time) const {}
void save(SurfaceBuilding@ bld, SaveFile& file) const {}
void load(SurfaceBuilding@ bld, SaveFile& file) const {}
bool canBuildOn(Object& obj, bool ignoreState = false) const { return meets(obj, ignoreState); }
bool canRemove(Object& obj) const { return true; }
void modBuildTime(Object& obj, double& time) const {}
bool canProgress(Object& obj) const { return true; }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color, bool isOption) const {
if(obj !is null && !meets(obj) && isOption) {
sprt = icons::Remove;
name = getFailError(obj);
value = "";
color = colors::Red;
return true;
}
return false;
}
//Constructions
#section server
void start(Construction@ cons, Constructible@ qitem, any@ data) const {}
void cancel(Construction@ cons, Constructible@ qitem, any@ data) const {}
void finish(Construction@ cons, Constructible@ qitem, any@ data) const {}
void tick(Construction@ cons, Constructible@ qitem, any@ data, double time) const {}
#section all
void save(Construction@ cons, any@ data, SaveFile& file) const {}
void load(Construction@ cons, any@ data, SaveFile& file) const {}
bool consume(Construction@ cons, any@ data, const Targets@ targs) const { return true; }
void reverse(Construction@ cons, any@ data, const Targets@ targs, bool cancel) const {}
string getFailReason(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return ""; }
bool isValidTarget(Object& obj, const ConstructionType@ cons, uint index, const Target@ targ) const { return true; }
bool canBuild(Object& obj, const ConstructionType@ cons, const Targets@ targs, bool ignoreCost) const { return meets(obj, ignoreCost); }
void getBuildCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getMaintainCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, int& cost) const {}
void getLaborCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, double& cost) const {}
bool getVariable(Object& obj, const ConstructionType@ cons, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
bool formatCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value) const { return false; }
bool getCost(Object& obj, const ConstructionType@ cons, const Targets@ targs, string& value, Sprite& icon) const { return false; }
bool getCost(Object& obj, string& value, Sprite& icon) const { return false; }
bool consume(Object& obj) const { return true; }
void reverse(Object& obj) const {}
};
class RequireTrait : Requirement {
Document doc("This requires the empire to have a specific trait.");
Argument trait("Trait", AT_Trait, doc="Trait to require.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(!owner.hasTrait(arguments[0].integer))
return false;
return true;
}
};
class RequireNotTrait : Requirement {
Document doc("This requires the empire to not have a specific trait.");
Argument trait("Trait", AT_Trait, doc="Trait to require.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(!owner.hasTrait(arguments[0].integer))
return true;
return false;
}
};
class RequireUnlockTag : Requirement {
Document doc("This requires the empire to have a specific unlock tag.");
Argument tag(AT_UnlockTag, doc="The unlock tag to check. Unlock tags can be named any arbitrary thing, and will be created as specified. Use the same tag value in the UnlockTag() or similar hook that should unlock it.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(!owner.isTagUnlocked(tag.integer))
return false;
return true;
}
};
class RequireSubsystemUnlocked : Requirement {
Document doc("This requires a particular subsystem to be unlocked.");
Argument subsystem(AT_Subsystem, doc="Identifier of the subsystem to check.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(!owner.isUnlocked(getSubsystemDef(subsystem.integer)))
return false;
return true;
}
};
class InDLC : Requirement {
Document doc("This is a subsystem that is only available if a particular dlc is installed.");
Argument dlc(AT_UnlockTag, doc="Name of the DLC.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(!owner.isTagUnlocked(dlc.integer))
return false;
return true;
}
};
class RequireAttributeLT : Requirement {
Document doc("This requires the empire's attribute to be less than a certain value.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument value(AT_Decimal, "1", doc="Value to test against.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(owner.getAttribute(attribute.integer) >= value.decimal)
return false;
return true;
}
};
class RequireAttributeGTE : Requirement {
Document doc("This requires the empire's attribute to be greater or equal to a certain value.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument value(AT_Decimal, "1", doc="Value to test against.");
bool meets(Object& obj, bool ignoreState = false) const {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(owner.getAttribute(attribute.integer) < value.decimal)
return false;
return true;
}
};
class RequireEither : Requirement {
Document doc("This requires either of two conditions to apply");
Argument condition_one(AT_Hook, "requirement_effects::Requirement");
Argument condition_two(AT_Hook, "requirement_effects::Requirement");
Requirement@ hook1;
Requirement@ hook2;
bool instantiate() override {
@hook1 = cast<Requirement>(parseHook(condition_one.str, "requirement_effects::"));
if(hook1 is null)
error("RequireEither(): could not find first condition: "+escape(condition_one.str));
@hook2 = cast<Requirement>(parseHook(condition_two.str, "requirement_effects::"));
if(hook2 is null)
error("RequireEither(): could not find second condition: "+escape(condition_two.str));
return Requirement::instantiate();
}
bool meets(Object& obj, bool ignoreState = false) const override {
if(hook1 !is null && hook1.meets(obj))
return true;
if(hook2 !is null && hook2.meets(obj))
return true;
return false;
}
};
class RequireNever : Requirement {
Document doc("This requirement can never be met.");
bool meets(Object& obj, bool ignoreState = false) const override {
return false;
}
};
class ConflictBuilding : Requirement {
Document doc("The object cannot have a building of a particular type to meet this requirement.");
Argument building(AT_Building, doc="Building type to conflict with.");
Argument hide(AT_Boolean, "True", doc="Hide when unavailable.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(ignoreState && !hide.boolean)
return true;
return obj.getBuildingCount(building.integer) == 0;
}
string getFailError(Object& obj, bool ignoreState = false) const {
return format(locale::CANNOT_BUILD_CONFLICT, getBuildingType(building.integer).name);
}
};
class RequireBuilding : Requirement {
Document doc("This can only work if a particular building is present.");
Argument building(AT_Building, doc="Building type to require.");
Argument hide(AT_Boolean, "True", doc="Hide when unavailable.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(ignoreState && !hide.boolean)
return true;
return obj.getBuildingCount(building.integer) != 0;
}
string getFailError(Object& obj, bool ignoreState = false) const {
return format(locale::CANNOT_BUILD_REQUIRE, getBuildingType(building.integer).name);
}
};
class RequireNativeLevel : Requirement {
Document doc("This can only work if the planet's resource is of a particular level.");
Argument level(AT_Integer, doc="Resource level to require.");
Argument hide(AT_Boolean, "True", doc="Hide when unavailable.");
Argument exact(AT_Boolean, "False", doc="Filter for exactly this level, instead of at least this level.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(ignoreState && !hide.boolean)
return true;
if(exact.boolean)
return obj.nativeResourceTotalLevel == uint(level.integer);
else
return obj.nativeResourceTotalLevel >= uint(level.integer);
}
string getFailError(Object& obj, bool ignoreState = false) const {
return format(locale::CANNOT_BUILD_LEVEL, toString(level.integer));
}
};
class RequireNativeClass : Requirement {
Document doc("This can only work if the planet's resource has a particular class.");
Argument cls(AT_Custom, doc="Resource class to require.");
Argument hide(AT_Boolean, "True", doc="Hide when unavailable.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(ignoreState && !hide.boolean)
return true;
auto@ res = getResource(obj.primaryResourceType);
if(res is null)
return false;
if(res.cls is null)
return false;
return res.cls.ident.equals_nocase(cls.str);
}
};
class RequireNativePressure : Requirement {
Document doc("This requirement can only be met if the planet has at least a specified amount of native pressure.");
Argument required_amount(AT_Integer, "1", doc="How much native pressure is required.");
Argument allow_money(AT_Boolean, "True", doc="Whether to count money pressure as native pressure.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(!obj.hasResources)
return false;
const ResourceType@ res = getResource(obj.primaryResourceType);
if(res is null)
return false;
int total = 0;
for(uint i = allow_money.boolean ? 0 : 1; i < TR_COUNT; ++i)
total += res.tilePressure[i];
return total >= required_amount.integer;
}
};
class RequireMoreMoonsThanStatus : Requirement {
Document doc("Satisfied if there are more moons than an amount of a particular status on this planet.");
Argument status(AT_Status, doc="Status type to check for.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(!obj.isPlanet)
return false;
Planet@ pl = cast<Planet>(obj);
return pl.moonCount > pl.getStatusStackCountAny(status.integer);
}
};
class RequireStatus : Requirement {
Document doc("Require that a particular status is present to build this.");
Argument status(AT_Status, doc="Status type to check for.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(!obj.hasStatuses)
return false;
return obj.getStatusStackCountAny(status.integer) > 0;
}
};
class RequireNotStatus : Requirement {
Document doc("Require that a particular status is not present to build this.");
Argument status(AT_Status, doc="Status type to check for.");
bool meets(Object& obj, bool ignoreState = false) const override {
if(!obj.hasStatuses)
return false;
return obj.getStatusStackCountAny(status.integer) == 0;
}
};
class RequirePlanet : Requirement {
Document doc("Can only be built on planets.");
bool meets(Object& obj, bool ignoreState = false) const override {
return obj.isPlanet;
}
};
class RequireOnOrbital : Requirement {
Document doc("Can only be used on orbitals of a particular type.");
Argument type(AT_OrbitalModule, doc="Orbital module to check for.");
bool meets(Object& obj, bool ignoreState = false) const override {
Orbital@ orb = cast<Orbital>(obj);
if(orb is null)
return false;
return orb.coreModule == uint(type.integer);
}
};
class RequireInSystem : Requirement {
Document doc("Can only be used inside a system.");
bool meets(Object& obj, bool ignoreState = false) const override {
return obj.region !is null;
}
};
class RequireNotManual : Requirement {
Document doc("This cannot be manually triggered by the player.");
#section client
bool meets(Object& obj, bool ignoreState = false) const override {
return false;
}
#section all
};
class RequireSenateLeader : Requirement {
Document doc("This can only be done if you are the senate leader.");
bool meets(Object& obj, bool ignoreState = false) const override {
Empire@ owner = obj.owner;
return owner is getSenateLeader();
}
};
class RequireConfigOption : Requirement {
Document doc("This can only be done if a config option is a particular value.");
Argument option(AT_Custom, doc="Config option to check.");
Argument value(AT_Decimal, "1.0", doc="Value for the option to check for.");
bool meets(Object& obj, bool ignoreState = false) const override {
return config::get(option.str) == value.decimal;
}
};
File diff suppressed because it is too large Load Diff
+444
View File
@@ -0,0 +1,444 @@
import research;
from research import TechnologyHook;
import bonus_effects;
from generic_effects import GenericEffect;
import icons;
import util.formatting;
class CivilanHPBonus : TechnologyHook {
Document doc("Increases civilian HP by a factor.");
Argument factor(AT_Decimal);
#section server
void unlock(TechnologyNode@ node, Empire& emp) const {
emp.ModHP *= factor.decimal;
}
#section all
};
class SecondaryInfluenceCost : TechnologyHook {
Document doc("This node's secondary unlock method takes an influence cost.");
Argument cost(AT_Integer, doc="Influence cost.");
bool getSecondaryUnlock(TechnologyNode@ node, Empire@ emp, string& text) const {
text = format("[img=$1;20/][b][color=$2]$3[/color][/b]",
getSpriteDesc(icons::Influence), toString(colors::Influence),
toString(cost.integer));
return true;
}
bool canSecondaryUnlock(TechnologyNode@ node, Empire& emp) const {
return emp.Influence >= cost.integer;
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
if(emp.ForbidSecondaryUnlock == 0)
desc += "\n\n"+format(locale::ALT_UNLOCK_INFLUENCE, toString(cost.integer, 0));
}
#section server
bool consumeSecondary(TechnologyNode@ node, Empire& emp) const {
return emp.consumeInfluence(cost.integer);
}
void reverseSecondary(TechnologyNode@ node, Empire& emp) const {
emp.modInfluence(cost.integer);
}
#section all
};
class SecondaryMoneyCost : TechnologyHook {
Document doc("This node's secondary unlock method takes a money cost.");
Argument cost(AT_Integer, doc="Money cost.");
bool getSecondaryUnlock(TechnologyNode@ node, Empire@ emp, string& text) const {
text = format("[img=$1;20/][b][color=$2]$3[/color][/b]",
getSpriteDesc(icons::Money), toString(colors::Money),
formatMoney(cost.integer));
return true;
}
bool canSecondaryUnlock(TechnologyNode@ node, Empire& emp) const {
return emp.canPay(cost.integer);
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
if(emp.ForbidSecondaryUnlock == 0)
desc += "\n\n"+format(locale::ALT_UNLOCK_MONEY, formatMoney(cost.integer));
}
#section server
bool consumeSecondary(TechnologyNode@ node, Empire& emp) const {
return emp.consumeBudget(cost.integer) != -1;
}
void reverseSecondary(TechnologyNode@ node, Empire& emp) const {
emp.refundBudget(cost.integer, emp.BudgetCycleId);
}
#section all
};
class SecondaryEnergyCost : TechnologyHook {
Document doc("This node's secondary unlock method takes a energy cost.");
Argument cost(AT_Decimal, doc="Energy cost.");
bool getSecondaryUnlock(TechnologyNode@ node, Empire@ emp, string& text) const {
text = format("[img=$1;20/][b][color=$2]$3[/color][/b]",
getSpriteDesc(icons::Energy), toString(colors::Energy),
toString(cost.decimal, 0));
return true;
}
bool canSecondaryUnlock(TechnologyNode@ node, Empire& emp) const {
return emp.EnergyStored >= cost.decimal;
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
if(emp.ForbidSecondaryUnlock == 0)
desc += "\n\n"+format(locale::ALT_UNLOCK_ENERGY, toString(cost.decimal, 0));
}
#section server
bool consumeSecondary(TechnologyNode@ node, Empire& emp) const {
return emp.consumeEnergy(cost.decimal, consumePartial=false) >= cost.decimal - 0.001;
}
void reverseSecondary(TechnologyNode@ node, Empire& emp) const {
emp.modEnergyStored(+cost.decimal);
}
#section all
};
class SecondaryFTLCost : TechnologyHook {
Document doc("This node's secondary unlock method takes an FTL cost.");
Argument cost(AT_Decimal, doc="FTL cost.");
bool getSecondaryUnlock(TechnologyNode@ node, Empire@ emp, string& text) const {
text = format("[img=$1;20/][b][color=$2]$3[/color][/b]",
getSpriteDesc(icons::FTL), toString(colors::FTL),
toString(cost.decimal, 0));
return true;
}
bool canSecondaryUnlock(TechnologyNode@ node, Empire& emp) const {
return emp.FTLStored >= cost.decimal;
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
if(emp.ForbidSecondaryUnlock == 0)
desc += "\n\n"+format(locale::ALT_UNLOCK_FTL, toString(cost.decimal, 0));
}
#section server
bool consumeSecondary(TechnologyNode@ node, Empire& emp) const {
return emp.consumeFTL(cost.decimal, partial=false, record=false) >= cost.decimal - 0.001;
}
void reverseSecondary(TechnologyNode@ node, Empire& emp) const {
emp.modFTLStored(+cost.decimal);
}
#section all
};
tidy final class NotSecondary : TechnologyHook {
Document doc("Only trigger the inner hook if the research was not bought using the secondary method.");
Argument function(AT_Hook, "research_effects::ITechnologyHook");
#section server
ITechnologyHook@ hook;
bool instantiate() override {
@hook = cast<ITechnologyHook>(parseHook(function.str, "research_effects::", required=false));
if(hook is null) {
error("NotSecondary(): could not find inner hook: "+escape(function.str));
return false;
}
return TechnologyHook::instantiate();
}
void unlock(TechnologyNode@ node, Empire& emp) const {
if(!node.secondaryUnlock)
hook.unlock(node, emp);
}
#section all
};
tidy final class Trigger : TechnologyHook {
Document doc("Trigger other types of hooks.");
Argument function(AT_Hook, "bonus_effects::BonusEffect");
#section server
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(function.str, "bonus_effects::", required=false));
if(hook is null) {
error("Trigger(): could not find inner hook: "+escape(function.str));
return false;
}
return TechnologyHook::instantiate();
}
void unlock(TechnologyNode@ node, Empire& emp) const {
hook.activate(null, emp);
}
#section all
};
class ResetWhenUnlocked : TechnologyHook {
Document doc("When this technology is researched, after it triggers its effects it immediately resets the node to no longer be researched, so it can be researched again.");
#section server
void unlock(TechnologyNode@ node, Empire& emp) const override {
node.bought = false;
node.unlocked = false;
node.available = true;
node.unlockable = true;
}
#section all
};
class RequireUnlockTag : TechnologyHook {
Document doc("This research node can only be researched if a particular unlock tag is unlocked, otherwise it stays unavailable, even if you have a valid path towards it.");
Argument tag(AT_UnlockTag, doc="The unlock tag to check. Unlock tags can be named any arbitrary thing, and will be created as specified. Use the same tag value in the UnlockTag() or similar hook that should unlock it.");
bool canUnlock(TechnologyNode@ node, Empire& emp) const override {
if(!emp.isTagUnlocked(tag.integer))
return false;
return true;
}
};
class ConflictUnlockTag : TechnologyHook {
Document doc("This research node can only be researched if a particular unlock tag is NOT unlocked, otherwise it will not be available, even if you have a valid path towards it.");
Argument tag(AT_UnlockTag, doc="The unlock tag to check. Unlock tags can be named any arbitrary thing, and will be created as specified. Use the same tag value in the UnlockTag() or similar hook that should unlock it.");
bool canUnlock(TechnologyNode@ node, Empire& emp) const override {
if(emp.isTagUnlocked(tag.integer))
return false;
return true;
}
};
class AutomaticallyUnlocks : TechnologyHook {
Document doc("This research node automatically unlocks itself when any nodes next to it are unlocked.");
#section server
void onStateChange(TechnologyNode@ node, Empire@ emp) const {
if(!node.bought && node.available) {
node.timer = node.getTimeCost(emp);
node.bought = true;
}
}
#section all
};
class SkipOnUnlockedSubsystem : TechnologyHook {
Document doc("This node automatically skips and becomes fully unlocked if a subsystem is already unlocked.");
Argument subsystem(AT_Subsystem, doc="Identifier of the subsystem to check for.");
void tick(TechnologyNode@ node, Empire& emp, double time) const override {
if(!node.bought && node.available) {
if(emp !is null && emp.isUnlocked(getSubsystemDef(subsystem.integer))) {
node.timer = 0.001;
node.bought = true;
}
}
}
};
class SkipOnUnlockedModule : TechnologyHook {
Document doc("This node automatically skips and becomes fully unlocked if a modifier module is already unlocked.");
Argument module(AT_Custom, doc="Identifier of the module to check for.");
void tick(TechnologyNode@ node, Empire& emp, double time) const override {
if(!node.bought && node.available) {
bool have = false;
for(uint i = 0, cnt = getSubsystemDefCount(); i < cnt; ++i) {
auto@ sys = getSubsystemDef(i);
auto@ mod = sys.module(module.str);
if(mod !is null) {
if(emp !is null && emp.isUnlocked(sys, mod)) {
have = true;
break;
}
}
}
if(have) {
node.timer = 0.001;
node.bought = true;
}
}
}
};
class SkipOnUnlockedTag : TechnologyHook {
Document doc("This node automatically skips and becomes fully unlocked if an unlock tag is already unlocked.");
Argument tag(AT_UnlockTag, doc="The unlock tag to check. Unlock tags can be named any arbitrary thing, and will be created as specified. Use the same tag value in any RequireUnlockTag() or similar hooks that check for it.");
void tick(TechnologyNode@ node, Empire& emp, double time) const override {
if(!node.bought && node.available) {
if(emp !is null && emp.isTagUnlocked(tag.integer)) {
node.timer = 0.001;
node.bought = true;
}
}
}
};
class AutoUnlockOnUnlockedTag : TechnologyHook {
Document doc("This node is automatically and immediately unlocked if a particular unlock tag is present, even if you are not currently adjacent to it.");
Argument tag(AT_UnlockTag, doc="The unlock tag to check. Unlock tags can be named any arbitrary thing, and will be created as specified. Use the same tag value in any RequireUnlockTag() or similar hooks that check for it.");
void tick(TechnologyNode@ node, Empire& emp, double time) const override {
if(!node.unlocked && !node.bought) {
if(emp !is null && emp.isTagUnlocked(tag.integer)) {
node.timer = 0.001;
node.bought = true;
node.available = true;
node.unlockable = true;
}
}
}
};
class RequireBuildShipsWith : TechnologyHook {
Document doc("This technology can only be researched if a certain amount of ships containing a particular subsystem have been constructed.");
Argument subsystem(AT_Subsystem, doc="Subsystem to check for.");
Argument amount(AT_Integer, doc="Amount of ships that need to have been constructed.");
int getCurrent(Empire& emp) const {
auto@ def = getSubsystemDef(subsystem.integer);
int count = 0;
ReadLock lock(emp.designMutex);
for(uint i = 0, cnt = emp.designCount; i < cnt; ++i) {
const Design@ dsg = emp.designs[i];
if(dsg.hasSubsystem(def))
count += dsg.built;
}
return count;
}
bool canUnlock(TechnologyNode@ node, Empire& emp) const override {
return getCurrent(emp) >= amount.integer;
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
int count = 0;
if(emp !is null)
count = getCurrent(emp);
Color col;
if(count >= amount.integer)
col = colors::Green;
else
col = colors::Red;
auto@ def = getSubsystemDef(subsystem.integer);
string req = format(locale::RESEARCH_REQ_BUILDSHIPS, toString(amount.integer), def.name, toString(count));
req = format(locale::RESEARCH_REQ, req, toString(col));
desc += "\n\n"+req;
}
};
class RequireEmpireAttributeGTE : TechnologyHook {
Document doc("This technology can only be researched if an empire attribute has at least a particular value.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument value(AT_Decimal, doc="Required value.");
Argument text(AT_Locale, doc="Requirement text to display.");
bool canUnlock(TechnologyNode@ node, Empire& emp) const override {
return emp.getAttribute(attribute.integer) >= value.decimal;
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
double count = 0;
if(emp !is null)
count = emp.getAttribute(attribute.integer);
Color col;
if(count >= value.decimal)
col = colors::Green;
else
col = colors::Red;
string req = format(text.str, standardize(count,true), standardize(value.decimal,true));
req = format(locale::RESEARCH_REQ, req, toString(col));
desc += "\n\n"+req;
}
};
class SecretRequiresTrait : TechnologyHook {
Document doc("Can only be a secret project if you have a particular trait.");
Argument trait(AT_Trait, doc="Trait to need.");
bool canBeSecret(TechnologyNode@ node, Empire& emp) const override {
return emp.hasTrait(trait.integer);
}
};
class SecretRequiresNotTrait : TechnologyHook {
Document doc("Can only be a secret project if you do not have a particular trait.");
Argument trait(AT_Trait, doc="Trait to forbid.");
bool canBeSecret(TechnologyNode@ node, Empire& emp) const override {
return !emp.hasTrait(trait.integer);
}
};
class AffectsTaggedSubsystems : TechnologyHook {
Document doc("Show a list of subsystems affected by this technology filtered to have a particular subsystem tag.");
Argument tag(AT_Custom, doc="Tag to check for.");
SubsystemTag tagId;
bool instantiate() override {
if(!TechnologyHook::instantiate())
return false;
tagId = getSubsystemTag(tag.str);
return true;
}
void addToDescription(TechnologyNode@ node, Empire@ emp, string& desc) const override {
string systems;
array<string> displayed;
for(uint i = 0, cnt = getSubsystemDefCount(); i < cnt; ++i) {
auto@ sys = getSubsystemDef(i);
if(!sys.hasTag(tagId))
continue;
if(sys.hasTag(ST_DontList) && (emp is null || !emp.isUnlocked(sys)))
continue;
if(displayed.find(sys.name) != -1)
continue;
if(systems.length != 0)
systems += ", ";
systems += sys.name;
displayed.insertLast(sys.name);
}
if(systems.length != 0)
desc += "\n\n"+format(locale::RESEARCH_AFFECTS, systems);
}
};
class AddPointCostAttribute : TechnologyHook {
Document doc("Increase the point cost of this node by the value of an empire attribute.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument multiply(AT_Decimal, "1", doc="Multiply the attribute value by this much before adding to the point cost.");
void modPointCost(const TechnologyNode@ node, Empire& emp, double& pointCost) const override {
pointCost += emp.getAttribute(attribute.integer) * multiply.decimal;
}
};
class AddTimeCostAttribute : TechnologyHook {
Document doc("Increase the time cost of this node by the value of an empire attribute.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument multiply(AT_Decimal, "1", doc="Multiply the attribute value by this much before adding to the time cost.");
void modTimeCost(const TechnologyNode@ node, Empire& emp, double& timeCost) const override {
timeCost += emp.getAttribute(attribute.integer) * multiply.decimal;
}
};
+501
View File
@@ -0,0 +1,501 @@
import resources;
import util.formatting;
import planet_effects;
import saving;
from bonus_effects import BonusEffect;
//MorphIntoImport()
// Morphs into the first imported resource.
class MorphIntoImport : ResourceHook {
Document doc("This resource morphs into a copy of the first resource imported to its object.");
bool get_hasEffect() const override {
return true;
}
string formatEffect(Object& obj, array<const IResourceHook@>& hooks) const override {
return locale::UNOBTANIUM_EFFECT;
}
#section server
void onTick(Object& obj, Resource@ r, double time) const override {
uint availCnt = obj.availableResourceCount;
if(availCnt > 1) {
for(uint i = 0; i < availCnt; ++i) {
auto@ type = getResource(obj.availableResourceType[i]);
if(type !is null && type !is r.type && !type.artificial) {
obj.removeResource(r.id);
obj.addResource(type.id);
break;
}
}
}
}
#section all
};
//PopResearch(<Per Billion>)
// Produces <Per Billion> tiles worth of research per billion population.
class PopResearch : ResourceHook {
Document doc("Increases reseearch income by a pressure-equivalent amount based on the amount of population present.");
Argument per_billion(AT_Decimal, doc="Amount of research to add for each population.");
bool get_hasEffect() const override {
return true;
}
string formatEffect(Object& obj, array<const IResourceHook@>& hooks) const override {
return format(locale::EFFECT_POPRESEARCH, toString(1.0 / arguments[0].decimal,0));
}
#section server
void onTick(Object& obj, Resource@ r, double time) const override {
Planet@ pl = cast<Planet>(obj);
if(pl is null)
return;
int prev = 0;
r.data[hookIndex].retrieve(prev);
int amt = int(pl.Population * arguments[0].decimal);
if(amt != prev) {
obj.modResource(TR_Research, amt - prev);
r.data[hookIndex].store(amt);
}
}
void load(Resource@ r, SaveFile& file) const override {
int amt = 0;
file >> amt;
r.data[hookIndex].store(amt);
}
void save(Resource@ r, SaveFile& file) const override {
int amt = 0;
r.data[hookIndex].retrieve(amt);
file << amt;
}
void onAdd(Object& obj, Resource@ r) const override {
int amt = 0;
r.data[hookIndex].store(amt);
}
void onRemove(Object& obj, Resource@ r) const override {
int prev = 0;
r.data[hookIndex].retrieve(prev);
if(prev != 0) {
obj.modResource(TR_Research, -prev);
r.data[hookIndex].store(0);
}
}
#section all
};
//AsteroidGraphics()
// Add some floating asteroid graphics around the planet.
class AsteroidGraphics : ResourceHook {
Document doc("Add some floating asteroid graphics around the planet.");
#section server
void applyGraphics(Object& obj, Node& node) const {
if(obj.isPlanet) {
PlanetNode@ plNode = cast<PlanetNode>(node);
if(plNode !is null)
plNode.giveAsteroids();
}
}
#section all
};
//AddPermanentFTLStorage(<Amount>)
// Adds <Amount> FTL storage permanently.
class AddPermanentFTLStorage : ResourceHook {
Document doc("Add permanent FTL storage capacity, even if the resource is later lost.");
Argument amount(AT_Integer, doc="Amount of FTL storage capacity to add.");
#section server
void onAdd(Object& obj, Resource@ r) const override {
if(obj.owner !is null && obj.owner.valid)
obj.owner.modFTLCapacity(+arguments[0].integer);
}
void onOwnerChange(Object& obj, Resource@ r, Empire@ prevOwner, Empire@ newOwner) const override {
if(newOwner !is null && newOwner.valid)
newOwner.modFTLCapacity(+arguments[0].integer);
}
#section all
};
//VanishWhenConstructing()
// Custom vanish mode for vanishing when the consuming object is constructing something.
class VanishWhenConstructing : ResourceHook {
Document doc("Used for resources with Vanish Mode: Custom. Only tick down the resource while the planet is actively using labor.");
#section server
bool shouldVanish(Object& obj, Resource@ native) const override {
Object@ target = native.exportedTo;
if(target is null)
@target = native.origin;
if(target is null || !target.hasConstruction)
return false;
return target.isUsingLabor;
}
#section all
};
//VanishUnlessFTLFull()
// Custom vanish mode that doesn't vanish if the ftl storage is full.
class VanishUnlessFTLFull : ResourceHook {
Document doc("Used for resources with Vanish Mode: Custom. Only tick down the resource while the empire's FTL storage is not full.");
#section server
bool shouldVanish(Object& obj, Resource@ native) const override {
Empire@ owner = obj.owner;
if(owner is null || !owner.valid)
return false;
if(owner.FTLStored >= owner.FTLCapacity - 0.0001)
return false;
return true;
}
#section all
};
//ResourceBonding(<Amount> = <Planet Resource>, ....)
// Bonds this resource into creating other resources
final class BondData {
uint amount = 2;
string resourceName;
const ResourceType@ type;
int opCmp(const BondData& other) const {
if(amount < other.amount)
return -1;
if(amount > other.amount)
return 1;
return 0;
}
};
class ResourceBonding : ResourceHook {
array<BondData> list;
Document doc("Generate new resources by bonding with copies of the current resource. Arguments must be added manually.");
bool parse(const string& name, array<string>& args) {
list.length = args.length;
for(uint i = 0, cnt = args.length; i < cnt; ++i) {
int pos = args[i].findFirst("=");
if(pos == -1) {
error("Invalid resource bond argument: "+escape(args[i]));
return false;
}
list[i].amount = max(2, toUInt(args[i].substr(0, pos)));
list[i].resourceName = args[i].substr(pos+1).trimmed();
}
list.sortAsc();
return true;
}
#section server
void initialize(ResourceType@ type, uint index) override {
ResourceHook::initialize(type, index);
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
@list[i].type = getResource(list[i].resourceName);
if(list[i].type is null)
error("Error: ResourceBonding(): could not find resource "+list[i].resourceName);
}
}
void onGenerate(Object& obj, Resource@ r) const {
int64 id = -1;
r.data[hookIndex].store(id);
}
void onDestroy(Object& obj, Resource@ r) const {
int64 id = -1;
r.data[hookIndex].retrieve(id);
if(id != -1) {
obj.removeResource(id);
id = -1;
r.data[hookIndex].store(id);
}
}
void setResource(Object& obj, Resource@ r, int64& id, any@ data, const ResourceType@ type) {
if(type is null) {
if(id == -1)
return;
}
else if(type.id == obj.nativeResourceByID[id])
return;
Object@ target;
if(id != -1) {
@target = obj.getNativeResourceDestinationByID(obj.owner, id);
obj.removeResource(id);
}
else {
@target = r.exportedTo;
}
if(type !is null) {
id = obj.addResource(type.id);
if(target !is null) {
obj.exportResourceByID(id, target);
if(r.exportedTo !is null)
obj.exportResourceByID(r.id, null);
}
}
else {
id = -1;
if(target !is null)
obj.exportResourceByID(r.id, target);
}
data.store(id);
}
void nativeTick(Object& obj, Resource@ r, double time) const override {
int64 id = -1;
r.data[hookIndex].retrieve(id);
Object@ curExp;
if(id != -1)
@curExp = obj.getNativeResourceDestinationByID(obj.owner, id);
uint count = obj.getAvailableResourceAmount(r.type.id);
if(r.exportedTo !is null && r.exportedTo is curExp && r.usable)
count += 1;
if(count > 1) {
//Should only work for the first native water
for(uint i = 0, cnt = obj.nativeResourceCount; i < cnt; ++i) {
if(obj.nativeResourceType[i] == r.type.id) {
if(obj.nativeResourceId[i] != r.id)
count = 0;
break;
}
}
}
const ResourceType@ res;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
if(count >= list[i].amount)
@res = list[i].type;
else
break;
}
setResource(obj, r, id, r.data[hookIndex], res);
}
void load(Resource@ r, SaveFile& file) const override {
if(file < SV_0007) {
int64 id = 0;
file >> id;
}
}
void nativeSave(Resource@ r, SaveFile& file) const override {
int64 id = 0;
r.data[hookIndex].retrieve(id);
file << id;
}
void nativeLoad(Resource@ r, SaveFile& file) const override {
if(file >= SV_0007) {
int64 id = 0;
file >> id;
r.data[hookIndex].store(id);
}
}
#section all
};
//LockOnExport(Destroy Invalid = True)
// Locks the resource whenever it is first exported.
class LockOnExport : ResourceHook {
Document doc("When the resource is first exported, it is locked and can no longer change its destination.");
Argument destroy_invalid(AT_Boolean, "True", doc="If set, the resource is destroyed when the locked destination is no longer valid.");
#section server
void nativeTick(Object& obj, Resource@ native, double time) const {
if(native.exportedTo !is null && !native.locked)
obj.setResourceLocked(native.id, true);
if(arguments[0].boolean) {
Object@ dest = obj.getNativeResourceDestinationByID(obj.owner, native.id);
if(dest !is null && (!dest.valid || (dest.owner !is obj.owner && dest.owner.valid)))
obj.removeResource(native.id);
}
}
#section all
};
//OnTradeDeliver(<Hook>())
// Triggers a bonus effect when delivering the resource with a civilian trade ship.
class OnTradeDeliver : ResourceHook {
BonusEffect@ hook;
Document doc("The inner hook is triggered when a civilian ship carrying this resource delivers its cargo.");
Argument hookID(AT_Hook, "bonus_effects::BonusEffect");
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::"));
if(hook is null) {
error("OnTradeDeliver(): could not find inner hook: "+escape(arguments[0].str));
return false;
}
return ResourceHook::instantiate();
}
#section server
void onTradeDeliver(Civilian& civ, Object@ origin, Object@ target) const override {
if(target is null || !target.isRegion)
hook.activate(target, civ.owner);
}
#section all
};
//OnTradeDeliver(<Hook>())
// Triggers a bonus effect when delivering the resource with a civilian trade ship.
class OnTradeDestroy : ResourceHook {
BonusEffect@ hook;
Document doc("The inner hook is triggered when a civilian ship carrying this resource is destroyed.");
Argument hookID(AT_Hook, "bonus_effects::BonusEffect");
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::"));
if(hook is null) {
error("OnTradeDeliver(): could not find inner hook: "+escape(arguments[0].str));
return false;
}
return ResourceHook::instantiate();
}
#section server
void onTradeDestroy(Civilian& civ, Object@ origin, Object@ target, Object@ destroyer) const override {
hook.activate(target, civ.owner);
}
#section all
};
class RegenSurface : ResourceHook {
Document doc("When the planet this resource is on is generated, create a new surface with a particular size and biome count.");
Argument width(AT_Integer, doc="Surface grid width.");
Argument height(AT_Integer, doc="Surface grid width.");
Argument biome_count(AT_Integer, "3", doc="Amount of biomes on the planet.");
Argument force_biome(AT_PlanetBiome, EMPTY_DEFAULT, doc="Force a particular biome as the planet's base biome.");
#section server
void onGenerate(Object& obj, Resource@ native) const {
obj.regenSurface(width.integer, height.integer, biome_count.integer);
if(force_biome.str.length != 0) {
auto@ type = getBiome(force_biome.str);
if(type !is null)
obj.replaceFirstBiomeWith(type.id);
}
}
#section all
};
class ForcePlanetType : ResourceHook {
Document doc("Force the planet this is on to be a particular type.");
Argument planet_type(AT_Custom, doc="Planet type identifier.");
#section server
void onGenerate(Object& obj, Resource@ native) const {
if(!obj.isPlanet)
return;
Planet@ pl = cast<Planet>(obj);
const PlanetType@ planetType = getPlanetType(planet_type.str);
if(planetType is null)
return;
pl.PlanetType = planetType.id;
PlanetNode@ plNode = cast<PlanetNode>(pl.getNode());
if(plNode !is null)
plNode.planetType = planetType.id;
}
#section all
};
class OnNative : ResourceHook {
GenericEffect@ hook;
Document doc("Run this hook on the resource's native planet, regardless of whether or to where it's being exported.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
@hook = cast<GenericEffect>(parseHook(hookID.str, "planet_effects::"));
if(hook is null) {
error("OnNative(): could not find inner hook: "+escape(hookID.str));
return false;
}
return ResourceHook::instantiate();
}
#section server
void onGenerate(Object& obj, Resource@ native) const override {
if(hook !is null)
hook.enable(obj, native.data[hookIndex]);
}
void nativeTick(Object& obj, Resource@ native, double time) const override {
if(hook !is null)
hook.tick(obj, native.data[hookIndex], time);
}
void onDestroy(Object& obj, Resource@ native) const override {
if(hook !is null)
hook.disable(obj, native.data[hookIndex]);
}
void nativeSave(Resource@ native, SaveFile& file) const override {
if(hook !is null)
hook.save(native.data[hookIndex], file);
}
void nativeLoad(Resource@ native, SaveFile& file) const override {
if(hook !is null)
hook.load(native.data[hookIndex], file);
}
#section all
};
class OnExportMoveLocalCargo : ResourceHook {
Document doc("All cargo of a particular type on this object is moved to wherever this resource is exported.");
Argument cargo_type(AT_Cargo, doc="Type of cargo to move.");
#section server
void nativeTick(Object& obj, Resource@ native, double time) const override {
Object@ targ = native.exportedTo;
if(targ !is null && obj.getCargoStored(cargo_type.integer) > 0
&& targ.hasCargo && targ.cargoCapacity > targ.cargoStored) {
obj.transferCargoTo(cargo_type.integer, targ);
}
}
#section all
};
class NativeLevelChain : GenericEffect {
Document doc("Change the native resource planet's level chain and requirements.");
Argument chain(AT_Custom, doc="Chain to change to.");
uint chainId = 0;
bool instantiate() override {
chainId = getLevelChainID(chain.str);
if(chainId == uint(-1)) {
chainId = 0;
error("Cannot find planet level chain: "+chain.str);
return false;
}
return GenericEffect::instantiate();
}
#section server
void onGenerate(Object& obj, Resource@ r) const {
obj.setLevelChain(chainId);
}
#section all
};
File diff suppressed because it is too large Load Diff
+288
View File
@@ -0,0 +1,288 @@
enum SaveIdentifier {
SI_InfluenceCard = SAVE_IDENTIFIER_START,
SI_InfluenceVote,
SI_Biome,
SI_Orbital,
SI_Pickup,
SI_Resource,
SI_Building,
SI_PlanetType,
SI_ResearchField,
SI_ResearchProject,
SI_RegionEffect,
SI_AbilityType,
SI_PlanetDesignation,
SI_AnomalyType,
SI_InfluenceEffect,
SI_Trait,
SI_Status,
SI_Artifact,
SI_Global,
SI_InfluenceClause,
SI_Technology,
SI_UnlockTag,
SI_SystemFlag,
SI_CreepCamp,
SI_EmpAttribute,
SI_ConstructionType,
SI_CargoType,
SI_RandomEvent,
SI_RandomEventOption,
SI_PlanetLevelChain,
SI_AttitudeType,
SI_ObjectStat,
};
enum SaveVersion {
SV_0001,
SV_0002,
SV_0003,
SV_0004,
SV_0005,
SV_0006,
SV_0007,
SV_0008,
SV_0009,
SV_0010,
SV_0011,
SV_0012,
SV_0013,
SV_0014,
SV_0015,
SV_0016,
SV_0017,
SV_0018,
SV_0019,
SV_0020,
SV_0021,
SV_0022,
SV_0023,
SV_0024,
SV_0025,
SV_0026,
SV_0027,
SV_0028,
SV_0029,
SV_0030,
SV_0031,
SV_0032,
SV_0033,
SV_0034,
SV_0035,
SV_0036,
SV_0037,
SV_0038,
SV_0039,
SV_0040,
SV_0041,
SV_0042,
SV_0043,
SV_0044,
SV_0045,
SV_0046,
SV_0047,
SV_0048,
SV_0049,
SV_0050,
SV_0051,
SV_0052,
SV_0053,
SV_0054,
SV_0055,
SV_0056,
SV_0057,
SV_0058,
SV_0059,
SV_0060,
SV_0061,
SV_0062,
SV_0063,
SV_0064,
SV_0065,
SV_0066,
SV_0067,
SV_0068,
SV_0069,
SV_0070,
SV_0071,
SV_0072,
SV_0073,
SV_0074,
SV_0075,
SV_0076,
SV_0077,
SV_0078,
SV_0079,
SV_0080,
SV_0081,
SV_0082,
SV_0083,
SV_0084,
SV_0085,
SV_0086,
SV_0087,
SV_0088,
SV_0089,
SV_0090,
SV_0091,
SV_0092,
SV_0093,
SV_0094,
SV_0095,
SV_0096,
SV_0097,
SV_0098,
SV_0099,
SV_0100,
SV_0101,
SV_0102,
SV_0103,
SV_0104,
SV_0105,
SV_0106,
SV_0107,
SV_0108,
SV_0109,
SV_0110,
SV_0111,
SV_0112,
SV_0113,
SV_0114,
SV_0115,
SV_0116,
SV_0117,
SV_0118,
SV_0119,
SV_0120,
SV_0121,
SV_0122,
SV_0123,
SV_0124,
SV_0125,
SV_0126,
SV_0127,
SV_0128,
SV_0129,
SV_0130,
SV_0131,
SV_0132,
SV_0133,
SV_0134,
SV_LOWEST_COMPATIBLE = SV_0134,
SV_0135,
SV_0136,
SV_0137,
SV_0138,
SV_0139,
SV_0140,
SV_0141,
SV_0142,
SV_0143,
SV_0144,
SV_0145,
SV_0146,
SV_0147,
SV_0148,
SV_0149,
SV_0150,
SV_0151,
SV_0152,
SV_0153,
SV_0154,
SV_0155,
SV_0156,
SV_0157,
SV_0158,
SV_0159,
SV_0160,
SV_0161,
SV_0162,
SV_0163,
SV_NEXT,
SV_CURRENT = SV_NEXT - 1,
};
array<uint> COMPATIBILITY_MODS = {
SV_0032, /* -- r3444 --> */ SV_0074,
SV_0074, /* -- r4257 --> */ SV_0115,
SV_0115, /* -- r4676 --> */ SV_0133,
};
bool isSaveCompatible(uint version) {
if(version == uint(-1))
return false;
if(version >= SV_LOWEST_COMPATIBLE)
return true;
for(uint i = 0, cnt = COMPATIBILITY_MODS.length; i+1 < cnt; i += 2) {
if(version >= COMPATIBILITY_MODS[i] && version <= COMPATIBILITY_MODS[i+1])
return true;
}
return false;
}
void saveIdentifiers(SaveFile& file) {
file.scriptVersion = SV_CURRENT;
if(!isLoadedSave)
file.startVersion = SV_CURRENT;
else
file.startVersion = START_VERSION;
}
const uint64 OBJ_STAT_MASK = 0x03 << 56;
void saveObjectStates(Object& obj, SaveFile& file) {
file << obj.region;
uint statCount = obj.getStatCount();
file << statCount;
for(uint i = 0; i < statCount; ++i) {
uint64 statId = obj.getStatIdByIndex(i);
int64 statValue = obj.getStatValueByIndex(i);
int leftKey = int((statId & 0xFFFFFFFF00000000) >> 32);
int rightKey = int(statId & 0x00000000FFFFFFFF);
file << leftKey;
file << statValue;
if(statId & OBJ_STAT_MASK != 0)
file.writeIdentifier(SI_ObjectStat, rightKey);
else
file << rightKey;
}
}
void loadObjectStates(Object& obj, SaveFile& file) {
file >> obj.region;
if(file >= SV_0163)
{
uint statCount = 0;
file >> statCount;
for(uint i = 0; i < statCount; ++i) {
uint64 key = 0;
int leftKey = 0;
file >> leftKey;
key |= uint64(leftKey)<<32;
int64 value = 0;
file >> value;
if(key & OBJ_STAT_MASK != 0) {
int id = file.readIdentifier(SI_ObjectStat);
key |= id;
}
else {
int id = 0;
file >> id;
key |= id;
}
obj.modStatInt(key, OSM_Set, value);
}
}
}
File diff suppressed because it is too large Load Diff
+460
View File
@@ -0,0 +1,460 @@
#priority init 2000
import hooks;
import saving;
import planet_types;
import resources;
export StatusType;
export Status;
export StatusInstance;
export getStatusType, getStatusTypeCount;
export getStatusID;
export getRandomCondition;
export StatusVisibility;
enum StatusVisibility {
StV_Everybody,
StV_Owner,
StV_Origin,
StV_OwnerAndOrigin,
StV_Global,
StV_Nobody,
};
tidy final class StatusType {
uint id;
string ident;
string name;
string description;
Sprite icon;
Color color;
StatusVisibility visibility = StV_Everybody;
bool unique = false;
bool collapses = false;
array<IStatusHook@> hooks;
string def_conditionType;
const PlanetType@ conditionType;
uint conditionTier = 0;
double conditionFrequency = 0.0;
bool shouldApply(Empire@ emp, Region@ region, Object@ obj) const {
if(!obj.hasStatuses)
return false;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i) {
if(!hooks[i].shouldApply(emp, region, obj))
return false;
}
return true;
}
};
interface IStatusHook {
void onCreate(Object& obj, Status@ status, any@ data);
void onDestroy(Object& obj, Status@ status, any@ data);
void onObjectDestroy(Object& obj, Status@ status, any@ data);
bool onTick(Object& obj, Status@ status, any@ data, double time);
void onAddStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data);
void onRemoveStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data);
bool onOwnerChange(Object& obj, Status@ status, any@ data, Empire@ prevOwner, Empire@ newOwner);
bool onRegionChange(Object& obj, Status@ status, any@ data, Region@ prevRegion, Region@ newRegion);
void save(Status@ status, any@ data, SaveFile& file);
void load(Status@ status, any@ data, SaveFile& file);
bool shouldApply(Empire@ emp, Region@ region, Object@ obj) const;
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color) const;
};
class StatusHook : Hook, IStatusHook {
void onCreate(Object& obj, Status@ status, any@ data) {}
void onDestroy(Object& obj, Status@ status, any@ data) {}
void onObjectDestroy(Object& obj, Status@ status, any@ data) {}
bool onTick(Object& obj, Status@ status, any@ data, double time) { return true; }
void onAddStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data) {}
void onRemoveStack(Object& obj, Status@ status, StatusInstance@ instance, any@ data) {}
bool onOwnerChange(Object& obj, Status@ status, any@ data, Empire@ prevOwner, Empire@ newOwner) { return true; }
bool onRegionChange(Object& obj, Status@ status, any@ data, Region@ prevRegion, Region@ newRegion) { return true; }
void save(Status@ status, any@ data, SaveFile& file) {}
void load(Status@ status, any@ data, SaveFile& file) {}
bool shouldApply(Empire@ emp, Region@ region, Object@ obj) const { return true; }
bool getVariable(Object@ obj, Sprite& sprt, string& name, string& value, Color& color) const { return false; }
};
tidy final class Status : Serializable, Savable {
const StatusType@ type;
int stacks = 0;
any[] data;
Empire@ originEmpire;
Object@ originObject;
Status() {
}
Status(const StatusType@ type) {
set(type);
}
string getTooltip(Object@ valueObject = null) const {
string tt;
string name = type.name;
if(!type.unique && stacks > 1)
name += format(" (x $1)", toString(stacks));
tt = format("[font=Medium][color=$3]$1[/color][/font]\n$2",
name, type.description, toString(type.color));
string vname, vvalue;
Sprite vicon;
Color color;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(type.hooks[i].getVariable(valueObject, vicon, vname, vvalue, color)) {
tt += format("[nl/]\n[img=$1;22][b][color=$4]$2[/color][/b] [offset=120]$3[/offset][/img]",
getSpriteDesc(vicon), vname, vvalue, toString(color));
color = colors::White;
}
}
return tt;
}
bool isVisibleTo(Object& obj, Empire@ emp) const {
if(emp is null || !emp.valid)
return type.visibility == StV_Everybody;
switch(type.visibility) {
case StV_Everybody:
case StV_Global:
return true;
case StV_Owner:
return emp is obj.owner;
case StV_Origin:
return emp is originEmpire;
case StV_OwnerAndOrigin:
return emp is originEmpire || emp is obj.owner;
case StV_Nobody:
return false;
}
return false;
}
void set(const StatusType@ type) {
@this.type = type;
stacks = 0;
data.length = type.hooks.length;
}
void write(Message& msg) {
msg.writeSmall(type.id);
msg.writeSmall(stacks);
msg << originEmpire;
msg << originObject;
}
void read(Message& msg) {
@type = getStatusType(msg.readSmall());
stacks = msg.readSmall();
data.length = type.hooks.length;
msg >> originEmpire;
msg >> originObject;
}
void save(SaveFile& file) {
file.writeIdentifier(SI_Status, type.id);
file << stacks;
file << originEmpire;
file << originObject;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].save(this, data[i], file);
}
void load(SaveFile& file) {
@type = getStatusType(file.readIdentifier(SI_Status));
file >> stacks;
if(file >= SV_0083) {
file >> originEmpire;
file >> originObject;
}
data.length = type.hooks.length;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].load(this, data[i], file);
}
void create(Object& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onCreate(obj, this, data[i]);
}
void destroy(Object& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onDestroy(obj, this, data[i]);
}
void objectDestroy(Object& obj) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onObjectDestroy(obj, this, data[i]);
}
StatusInstance@ instance(Object& obj) {
StatusInstance inst;
@inst.status = this;
stacks += 1;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onAddStack(obj, this, inst, data[i]);
return inst;
}
void remove(Object& obj, StatusInstance@ inst) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i)
type.hooks[i].onRemoveStack(obj, this, inst, data[i]);
stacks -= 1;
}
bool tick(Object& obj, double time) {
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].onTick(obj, this, data[i], time))
return false;
}
return true;
}
bool ownerChange(Object& obj, Empire@ prevOwner, Empire@ newOwner) {
bool keep = true;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].onOwnerChange(obj, this, data[i], prevOwner, newOwner))
keep = false;
}
return keep;
}
bool regionChange(Object& obj, Region@ prevRegion, Region@ newRegion) {
bool keep = true;
for(uint i = 0, cnt = type.hooks.length; i < cnt; ++i) {
if(!type.hooks[i].onRegionChange(obj, this, data[i], prevRegion, newRegion))
keep = false;
}
return keep;
}
};
tidy final class StatusInstance : Savable {
Status@ status;
int id = -1;
double timer = -1.0;
Region@ boundRegion;
Empire@ boundEmpire;
void remove(Object& obj) {
status.remove(obj, this);
}
bool tick(Object& obj, double time) {
if(timer >= 0) {
timer -= time;
if(timer <= 0) {
status.remove(obj, this);
return false;
}
}
return true;
}
void save(SaveFile& file) {
file << id;
file << timer;
file << boundRegion;
file << boundEmpire;
}
void load(SaveFile& file) {
file >> id;
file >> timer;
file >> boundRegion;
file >> boundEmpire;
}
};
array<StatusType@> statusTypes;
dictionary statusIdents;
int getStatusID(const string& ident) {
auto@ type = getStatusType(ident);
if(type is null)
return -1;
return int(type.id);
}
string getStatusIdent(int id) {
auto@ type = getStatusType(id);
if(type is null)
return "";
return type.ident;
}
const StatusType@ getStatusType(uint id) {
if(id >= statusTypes.length)
return null;
return statusTypes[id];
}
const StatusType@ getStatusType(const string& ident) {
StatusType@ def;
if(statusIdents.get(ident, @def))
return def;
return null;
}
uint getStatusTypeCount() {
return statusTypes.length;
}
const StatusType@ getRandomCondition(Planet& planet) {
double roll = randomd();
double freq = 0.0;
const StatusType@ result;
for(uint i = 0, cnt = statusTypes.length; i < cnt; ++i) {
auto@ status = statusTypes[i];
if(status.conditionFrequency <= 0)
continue;
if(status.conditionType !is null) {
if(planet.PlanetType != status.conditionType.id)
continue;
}
if(status.conditionTier != 0) {
auto@ type = getResource(planet.primaryResourceType);
if(type is null || type.level < status.conditionTier)
continue;
}
if(!status.shouldApply(planet.owner, planet.region, planet))
continue;
freq += status.conditionFrequency;
double chance = status.conditionFrequency / freq;
if(roll < chance) {
@result = status;
roll /= chance;
}
else {
roll = (roll - chance) / (1.0 - chance);
}
}
return result;
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = statusTypes.length; i < cnt; ++i) {
auto type = statusTypes[i];
file.addIdentifier(SI_Status, type.id, type.ident);
}
}
void addStatus(StatusType@ type) {
type.id = statusTypes.length;
statusTypes.insertLast(type);
statusIdents.set(type.ident, @type);
}
void parseLine(string& line, StatusType@ type, ReadFile@ file) {
auto@ hook = cast<IStatusHook>(parseHook(line, "status_effects::", instantiate=false, file=file));
if(hook !is null)
type.hooks.insertLast(hook);
}
void loadStatus(const string& filename) {
ReadFile file(filename, true);
string key, value;
StatusType@ status;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
string line = file.line;
parseLine(line, status, file);
}
else if(key.equals_nocase("Status")) {
if(status !is null)
addStatus(status);
@status = StatusType();
status.ident = value;
}
else if(status is null) {
file.error("Missing status ID' line");
}
else if(key.equals_nocase("Name")) {
status.name = localize(value);
}
else if(key.equals_nocase("Description")) {
status.description = localize(value);
}
else if(key.equals_nocase("Icon")) {
status.icon = getSprite(value);
}
else if(key.equals_nocase("Color")) {
status.color = toColor(value);
}
else if(key.equals_nocase("Condition Frequency")) {
status.conditionFrequency = toDouble(value);
}
else if(key.equals_nocase("Condition Tier")) {
status.conditionTier = toUInt(value);
}
else if(key.equals_nocase("Condition Type")) {
status.def_conditionType = value;
}
else if(key.equals_nocase("Unique")) {
status.unique = toBool(value);
if(status.unique)
status.collapses = true;
}
else if(key.equals_nocase("Collapses")) {
status.collapses = toBool(value);
}
else if(key.equals_nocase("Visible To")) {
if(value.equals_nocase("everybody"))
status.visibility = StV_Everybody;
else if(value.equals_nocase("owner"))
status.visibility = StV_Owner;
else if(value.equals_nocase("origin empire"))
status.visibility = StV_Origin;
else if(value.equals_nocase("owner and origin empire"))
status.visibility = StV_OwnerAndOrigin;
else if(value.equals_nocase("nobody"))
status.visibility = StV_Nobody;
else if(value.equals_nocase("global"))
status.visibility = StV_Global;
else
file.error("Unknown status visibility: "+value);
}
else {
string line = file.line;
parseLine(line, status, file);
}
}
if(status !is null)
addStatus(status);
}
void preInit() {
FileList list("data/statuses", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadStatus(list.path[i]);
}
void init() {
auto@ list = statusTypes;
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ type = list[i];
for(uint n = 0, ncnt = type.hooks.length; n < ncnt; ++n)
if(!cast<Hook>(type.hooks[n]).instantiate())
error("Could not instantiate hook: "+addrstr(type.hooks[n])+" in "+type.ident);
if(type.def_conditionType.length != 0) {
@type.conditionType = getPlanetType(type.def_conditionType);
if(type.conditionType is null)
error("Error in Status "+type.ident+": could not find planet type "+type.def_conditionType);
}
}
}
+150
View File
@@ -0,0 +1,150 @@
import generic_effects;
import hooks;
class SubsystemEffect : SubsystemHook, Hook, RegionChangeable, LeaderChangeable {
#section server
void start(SubsystemEvent& event) const {}
void tick(SubsystemEvent& event, double time) const {}
void suspend(SubsystemEvent& event) const {}
void resume(SubsystemEvent& event) const {}
void destroy(SubsystemEvent& event) const {}
void end(SubsystemEvent& event) const {}
void change(SubsystemEvent& event) const {}
void ownerChange(SubsystemEvent& event, Empire@ prevOwner, Empire@ newOwner) const {}
DamageEventStatus damage(SubsystemEvent& event, DamageEvent& damage, const vec2u& position) const {
return DE_Continue;
}
DamageEventStatus globalDamage(SubsystemEvent& event, DamageEvent& damage, const vec2u& position, vec2d& endPoint) const {
return DE_Continue;
}
void preRetrofit(SubsystemEvent& event) const {}
void postRetrofit(SubsystemEvent& event) const {}
void save(SubsystemEvent& event, SaveFile& file) const {}
void load(SubsystemEvent& event, SaveFile& file) const {}
#section all
void regionChange(SubsystemEvent& event, Region@ prevRegion, Region@ newRegion) const {}
void leaderChange(SubsystemEvent& event, Object@ prevLeader, Object@ newLeader) const {}
};
class AddSupplyToFleet : SubsystemEffect {
Document doc("Add a bonus amount of supply storage to the fleet.");
Argument amount(AT_Decimal, doc="Amount of supply capacity to add.");
Argument leakpctpersec(AT_Decimal, doc="Drain rate per second when fully damaged.");
#section server
void tick(SubsystemEvent& event, double time) const override {
if(event.workingPercent <= 1.0 && leakpctpersec.decimal > 0) {
Ship@ ship = cast<Ship>(event.obj);
Ship@ leader = cast<Ship>(ship.Leader);
if(leader !is null)
leader.consumeSupply(ship.MaxSupply * leakpctpersec.decimal * (1.0 - sqr(event.workingPercent)) * time);
}
}
void leaderChange(SubsystemEvent& event, Object@ prevLeader, Object@ newLeader) const override {
if(prevLeader !is null && prevLeader.isShip)
cast<Ship>(prevLeader).modSupplyBonus(-amount.decimal);
if(newLeader !is null && newLeader.isShip)
cast<Ship>(newLeader).modSupplyBonus(+amount.decimal);
}
#section all
};
class AddPermanentStatus : SubsystemEffect {
Document doc("Add a status that doesn't go away during a retrofit.");
Argument status(AT_Status, doc="Status to add.");
#section server
void start(SubsystemEvent& event) const {
if(event.obj.hasStatuses && !event.obj.hasStatusEffect(status.integer))
event.obj.addStatus(status.integer);
}
#section all
};
class SolarData {
double timer = 0.0;
double prevBoost = 0.0;
};
class SolarEfficiency : SubsystemEffect {
Document doc("Modify the ship's efficiency based on how much light it is getting.");
Argument loss(AT_Decimal, doc="Amount of efficiency lost when in deep space.");
Argument min_boost(AT_Decimal, doc="Minimum boost when on a cold star or far away from a star.");
Argument max_boost(AT_Decimal, doc="Maximum boost when on a hot star or close to a star.");
Argument power_factor(AT_Boolean, "False", doc="Only apply boosts according to how much of the ship's power is solar power.");
Argument step(AT_Decimal, "0.05", doc="Only apply changes in steps of this size.");
Argument temperature_max(AT_Decimal, "15000", doc="Solar temperature (modified by distance) that triggers the maximum boost.");
#section server
void tick(SubsystemEvent& event, double time) const override {
SolarData@ dat;
event.data.retrieve(@dat);
if(dat is null) {
@dat = SolarData();
event.data.store(@dat);
}
dat.timer -= time;
if(dat.timer <= 0) {
Object@ obj = event.obj;
Region@ reg = obj.region;
dat.timer += 1.0;
if(obj.velocity.lengthSQ <= 1.0 && !obj.inCombat)
dat.timer += 10.0;
Ship@ ship = cast<Ship>(obj);
double powerFactor = event.workingPercent;
if(ship !is null) {
const Design@ dsg = ship.blueprint.design;
if(dsg !is null)
powerFactor *= dsg.total(SV_SolarPower) / dsg.total(SV_Power);
}
double newBoost = 0.0;
if(reg is null) {
newBoost = -loss.decimal * powerFactor;
}
else {
double solarFactor = reg.starTemperature * (1.0 - (obj.position.distanceToSQ(reg.position) / sqr(reg.radius)));
newBoost = min_boost.decimal + clamp(solarFactor / temperature_max.decimal, 0.0, max_boost.decimal);
newBoost *= powerFactor;
}
newBoost = round(newBoost / step.decimal) * step.decimal;
if(abs(dat.prevBoost - newBoost) >= step.decimal * 0.5) {
obj.modFleetEffectiveness(newBoost - dat.prevBoost);
dat.prevBoost = newBoost;
}
}
}
void save(SubsystemEvent& event, SaveFile& file) const {
SolarData@ dat;
event.data.retrieve(@dat);
if(dat is null) {
double t = 0.0;
file << t << t;
}
else {
file << dat.timer;
file << dat.prevBoost;
}
}
void load(SubsystemEvent& event, SaveFile& file) const {
SolarData dat;
event.data.store(@dat);
file >> dat.timer;
file >> dat.prevBoost;
}
#section all
};
+29
View File
@@ -0,0 +1,29 @@
import saving;
array<string> systemFlags;
dictionary flagIdents;
uint getSystemFlagCount() {
return systemFlags.length;
}
int getSystemFlag(const string& ident, bool create = true) {
int id = -1;
if(!flagIdents.get(ident, id) && create) {
id = int(systemFlags.length);
systemFlags.insertLast(ident);
flagIdents.set(ident, id);
}
return id;
}
string getSystemFlagIdent(int id) {
if(id < 0 || uint(id) >= systemFlags.length)
return "";
return systemFlags[id];
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = systemFlags.length; i < cnt; ++i)
file.addIdentifier(SI_SystemFlag, int(i), systemFlags[i]);
}
File diff suppressed because it is too large Load Diff
+194
View File
@@ -0,0 +1,194 @@
import icons;
enum TileResources {
TR_Money,
TR_Influence,
TR_Energy,
TR_Defense,
TR_Labor,
TR_Research,
TR_COUNT,
TR_NULL = TR_COUNT,
TR_INVALID = TR_COUNT
};
enum AffinityMask {
A_NULL = 0,
A_Money = 1,
A_Influence = 2,
A_Energy = 4,
A_Defense = 8,
A_Labor = 16,
A_Research = 32,
A_ALL = 63,
};
TileResources getTileResource(string ident) {
if(ident == "Money")
return TR_Money;
if(ident == "Influence")
return TR_Influence;
if(ident == "Energy")
return TR_Energy;
if(ident == "Defense")
return TR_Defense;
if(ident == "Labor")
return TR_Labor;
if(ident == "Research")
return TR_Research;
return TR_INVALID;
}
string getTileResourceIdent(uint r) {
switch(r) {
case TR_Money: return "Money";
case TR_Influence: return "Influence";
case TR_Energy: return "Energy";
case TR_Defense: return "Defense";
case TR_Labor: return "Labor";
case TR_Research: return "Research";
}
return "-";
}
string getTileResourceSpriteSpec(uint r) {
return getSpriteDesc(getTileResourceSprite(r));
}
const Sprite& getTileResourceSprite(uint r) {
switch(r) {
case TR_Money: return icons::Money;
case TR_Influence: return icons::Influence;
case TR_Energy: return icons::Energy;
case TR_Defense: return icons::Defense;
case TR_Labor: return icons::Labor;
case TR_Research: return icons::Research;
}
return icons::Empty;
}
Color getTileResourceColor(uint r) {
switch(r) {
case TR_Money: return Color(0xd1cb6aff);
case TR_Influence: return Color(0x0087c7ff);
case TR_Energy: return Color(0x42b4bdff);
case TR_Defense: return Color(0xaf7926ff);
case TR_Labor: return Color(0xb1b4b6ff);
case TR_Research: return Color(0x8c4ec9ff);
}
return Color();
}
string getTileResourceName(uint r) {
switch(r) {
case TR_Money: return locale::RESOURCE_MONEY;
case TR_Influence: return locale::RESOURCE_INFLUENCE;
case TR_Energy: return locale::RESOURCE_ENERGY;
case TR_Defense: return locale::RESOURCE_DEFENSE;
case TR_Labor: return locale::RESOURCE_LABOR;
case TR_Research: return locale::RESOURCE_RESEARCH;
}
return "-";
}
Sprite getAffinitySprite(uint a) {
if(a == A_ALL) {
return Sprite(spritesheet::AffinityIcons, 11);
}
else if(a & A_Money != 0) {
if(a & A_Energy != 0)
return Sprite(spritesheet::AffinityIcons, 8);
if(a & A_Influence != 0)
return Sprite(spritesheet::AffinityIcons, 10);
return Sprite(spritesheet::AffinityIcons, 0);
}
else if(a & A_Influence != 0) {
if(a & A_Research != 0)
return Sprite(spritesheet::AffinityIcons, 9);
return Sprite(spritesheet::AffinityIcons, 1);
}
else if(a & A_Energy != 0) {
if(a & A_Labor != 0)
return Sprite(spritesheet::AffinityIcons, 7);
else if(a & A_Defense != 0)
return Sprite(spritesheet::AffinityIcons, 12);
return Sprite(spritesheet::AffinityIcons, 2);
}
else if(a & A_Defense != 0) {
if(a & A_Research != 0)
return Sprite(spritesheet::AffinityIcons, 6);
return Sprite(spritesheet::AffinityIcons, 3);
}
else if(a & A_Labor != 0) {
return Sprite(spritesheet::AffinityIcons, 4);
}
else if(a & A_Research != 0) {
return Sprite(spritesheet::AffinityIcons, 5);
}
return Sprite();
}
uint getPureAffinity(uint a) {
if(a == A_Money)
return TR_Money;
if(a == A_Influence)
return TR_Influence;
if(a == A_Energy)
return TR_Energy;
if(a == A_Defense)
return TR_Defense;
if(a == A_Labor)
return TR_Labor;
if(a == A_Research)
return TR_Research;
return TR_NULL;
}
void splitAffinity(uint a, array<uint>& list) {
if(a & A_Money != 0)
list[TR_Money] += 1;
if(a & A_Influence != 0)
list[TR_Influence] += 1;
if(a & A_Energy != 0)
list[TR_Energy] += 1;
if(a & A_Labor != 0)
list[TR_Labor] += 1;
if(a & A_Research != 0)
list[TR_Research] += 1;
if(a & A_Defense != 0)
list[TR_Defense] += 1;
}
uint getAffinityFromDesc(const string& str) {
if(str.trimmed() == "ALL")
return A_ALL;
array<string>@ types = str.split("+");
uint aff = A_NULL;
for(uint i = 0, cnt = types.length; i < cnt; ++i) {
uint res = getTileResource(types[i].trimmed());
if(res != TR_NULL)
aff |= 1 << res;
}
return aff;
}
bool affinityHas(uint affinity, uint resource) {
return affinity & (1<<resource) != 0;
}
string formatTileResources(const double[]@ resources, int size = 20) {
string output = "";
string sizeStr = toString(size, 0);
for(uint i = 0, cnt = min(resources.length, TR_COUNT); i < cnt; ++i) {
uint amt = resources[i];
if(amt != 0) {
string fmt = format("[img=$1;$2/]", getTileResourceSpriteSpec(TileResources(i)), sizeStr);
for(uint j = 0; j < amt; ++j)
output += fmt;
}
}
return output;
}
+709
View File
@@ -0,0 +1,709 @@
import traits;
import influence;
from traits import TraitEffect;
from bonus_effects import BonusEffect;
from planet_effects import GenericEffect;
from map_effects import MapHook;
import bonus_effects;
import research;
import hooks;
import statuses;
import empire_effects;
import util.design_export;
#section server
import object_creation;
from empire import Creeps;
import systems;
import regions.regions;
#section all
class HWData {
Empire@ prevOwner;
Region@ prevRegion;
any data;
};
tidy final class OnHomeworld : TraitEffect {
GenericEffect@ hook;
BonusEffect@ bonus;
Document doc("Apply the specified continuous effect on the homeworld.");
Argument hookID("Hook", AT_Hook, "planet_effects::GenericEffect");
bool instantiate() override {
@hook = cast<GenericEffect>(parseHook(arguments[0].str, "planet_effects::", required=false));
if(hook is null) {
@bonus = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::"));
if(bonus is null)
return false;
}
return TraitEffect::instantiate();
}
void init(Empire& emp, any@ data) const override {
if(hook !is null) {
HWData dat;
data.store(@dat);
hook.enable(emp.Homeworld, dat.data);
@dat.prevOwner = emp.Homeworld.owner;
@dat.prevRegion = emp.Homeworld.region;
}
else if(bonus !is null) {
bonus.activate(emp.Homeworld, emp);
}
}
void tick(Empire& emp, any@ data, double time) const override {
if(hook is null)
return;
HWData@ dat;
data.retrieve(@dat);
Object@ hw = emp.Homeworld;
if(hw is null)
return;
Empire@ owner = hw.owner;
if(owner !is dat.prevOwner) {
hook.ownerChange(hw, dat.data, dat.prevOwner, owner);
@dat.prevOwner = owner;
}
Region@ region = hw.region;
if(region !is dat.prevRegion) {
hook.regionChange(hw, dat.data, dat.prevRegion, region);
@dat.prevRegion = region;
}
hook.tick(hw, dat.data, time);
}
void save(any@ data, SaveFile& file) const override {
if(hook is null)
return;
HWData@ dat;
data.retrieve(@dat);
file << dat.prevOwner;
file << dat.prevRegion;
hook.save(dat.data, file);
}
void load(any@ data, SaveFile& file) const override {
if(hook is null)
return;
HWData dat;
data.store(@dat);
file >> dat.prevOwner;
file >> dat.prevRegion;
hook.load(dat.data, file);
}
};
tidy final class TriggerHomeworld : TraitEffect {
BonusEffect@ bonus;
Document doc("Apply the specified one-time trigger effect on the homeworld.");
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect");
Argument run_post(AT_Boolean, "False", doc="Whether to run the trigger as a post init event.");
bool instantiate() override {
@bonus = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::"));
if(bonus is null)
return false;
return TraitEffect::instantiate();
}
void init(Empire& emp, any@ data) const override {
if(!run_post.boolean) {
if(emp.Homeworld !is null && emp.Homeworld.valid)
bonus.activate(emp.Homeworld, emp);
else if(emp.HomeObj !is null)
bonus.activate(emp.HomeObj, emp);
}
}
void postInit(Empire& emp, any@ data) const override {
if(run_post.boolean) {
if(emp.Homeworld !is null && emp.Homeworld.valid)
bonus.activate(emp.Homeworld, emp);
else if(emp.HomeObj !is null)
bonus.activate(emp.HomeObj, emp);
}
}
};
tidy final class InHomeSystem : TraitEffect {
MapHook@ hook;
Document doc("Apply the specified map generation effect on the home system.");
Argument hookID("Hook", AT_Hook, "map_effects::IMapHook");
bool instantiate() override {
@hook = cast<MapHook>(parseHook(arguments[0].str, "map_effects::"));
if(hook is null)
return false;
return TraitEffect::instantiate();
}
#section server
void init(Empire& emp, any@ data) const override {
Region@ region = emp.HomeSystem;
if(region is null && emp.Homeworld !is null)
@region = getRegion(emp.Homeworld.position);
if(region is null && emp.HomeObj !is null)
@region = getRegion(emp.HomeObj.position);
if(region is null)
return;
SystemDesc@ sys = getSystem(region);
if(sys is null)
return;
Object@ current;
hook.trigger(null, sys, current);
}
#section all
};
tidy final class TriggerHomeSystem : TraitEffect {
BonusEffect@ bonus;
Document doc("Apply the specified one-time trigger effect on the home system.");
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect");
Argument run_post(AT_Boolean, "False", doc="Whether to run the trigger as a post init event.");
bool instantiate() override {
@bonus = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::"));
if(bonus is null)
return false;
return TraitEffect::instantiate();
}
#section server
void init(Empire& emp, any@ data) const override {
if(!run_post.boolean) {
Region@ region = emp.HomeSystem;
if(region is null && emp.Homeworld !is null)
@region = getRegion(emp.Homeworld.position);
if(region is null && emp.HomeObj !is null)
@region = getRegion(emp.HomeObj.position);
if(region !is null)
bonus.activate(region, emp);
}
}
void postInit(Empire& emp, any@ data) const override {
if(run_post.boolean) {
Region@ region = emp.HomeSystem;
if(region is null && emp.Homeworld !is null)
@region = getRegion(emp.Homeworld.position);
if(region is null && emp.HomeObj !is null)
@region = getRegion(emp.HomeObj.position);
if(region !is null)
bonus.activate(region, emp);
}
}
#section all
};
tidy final class InRandomAdjacentSystem : TraitEffect {
MapHook@ hook;
Document doc("Apply the specified map generation effect on a random system adjacent to the home system.");
Argument hookID("Hook", AT_Hook, "map_effects::IMapHook");
bool instantiate() override {
@hook = cast<MapHook>(parseHook(arguments[0].str, "map_effects::"));
if(hook is null)
return false;
return TraitEffect::instantiate();
}
#section server
void init(Empire& emp, any@ data) const override {
Region@ region = emp.HomeSystem;
if(region is null && emp.Homeworld !is null)
@region = getRegion(emp.Homeworld.position);
if(region is null && emp.HomeObj !is null)
@region = getRegion(emp.HomeObj.position);
if(region is null)
return;
SystemDesc@ sys = getSystem(region);
if(sys is null)
return;
if(sys.adjacent.length == 0)
return;
SystemDesc@ adj = getSystem(sys.adjacent[randomi(0, sys.adjacent.length-1)]);
if(adj is null)
return;
Object@ current;
hook.trigger(null, adj, current);
}
#section all
};
tidy final class InAllAdjacentSystems : TraitEffect {
MapHook@ hook;
Document doc("Apply the specified map generation effect on all systems adjacent to the home system.");
Argument hookID("Hook", AT_Hook, "map_effects::IMapHook");
bool instantiate() override {
@hook = cast<MapHook>(parseHook(arguments[0].str, "map_effects::"));
if(hook is null)
return false;
return TraitEffect::instantiate();
}
#section server
void init(Empire& emp, any@ data) const override {
Region@ region = emp.HomeSystem;
if(region is null && emp.Homeworld !is null)
@region = getRegion(emp.Homeworld.position);
if(region is null && emp.HomeObj !is null)
@region = getRegion(emp.HomeObj.position);
if(region is null)
return;
SystemDesc@ sys = getSystem(region);
if(sys is null)
return;
for(uint i = 0, cnt = sys.adjacent.length; i < cnt; ++i) {
auto@ other = getSystem(sys.adjacent[i]);
if(other is null)
continue;
Object@ current;
hook.trigger(null, other, current);
}
}
#section all
};
class RemoveAllCards : TraitEffect {
Document doc("Remove all influence cards the empire starts with.");
#section server
void postInit(Empire& emp, any@ data) const override {
array<InfluenceCard> cards;
cards.syncFrom(emp.getInfluenceCards());
for(uint i = 0, cnt = cards.length; i < cnt; ++i)
emp.takeCardUse(cards[i].id, uint(-1));
}
#section all
};
class LoadDesigns : TraitEffect {
Document doc("Load default designs from a particular directory into the empire.");
Argument directory(AT_Custom, doc="Relative path to the directory to add designs from.");
Argument limit_shipset(AT_Boolean, "True", doc="Whether to only load designs that have a saved hull that matches the current shipset.");
Argument retry_without_limit(AT_Boolean, "True", doc="Whether to override the shipset limit and load all designs if no designs were found.");
#section server
DesignSet designs;
bool instantiate() override {
designs.readDirectory("data/designs/"+directory.str);
designs.limitShipset = limit_shipset.boolean;
designs.softLimitRetry = retry_without_limit.boolean;
return TraitEffect::instantiate();
}
void init(Empire& emp, any@ data) const override {
designs.createFor(emp);
}
#section all
};
class PlanetReqData {
double timer;
set_int set;
array<Planet@> list;
array<int> ids;
};
class AddStatusPlanetsReqLevel : TraitEffect {
Document doc("Add a status effect to all planets of a particular level or higher.");
Argument level(AT_Integer, doc="Minimum level of planets that get the status.");
Argument status(AT_Status, doc="Type of status to add to planets.");
#section server
void init(Empire& emp, any@ data) const override {
PlanetReqData list;
data.store(@list);
}
void tick(Empire& emp, any@ data, double time) const override {
PlanetReqData@ list;
data.retrieve(@list);
if(list is null)
return;
list.timer -= time;
if(list.timer >= 0)
return;
uint minLevel = arguments[0].integer;
list.timer = 5.0;
//Check old
for(int i = list.list.length - 1; i >= 0; --i) {
Planet@ pl = list.list[i];
if(pl.level < minLevel || pl.owner !is emp) {
pl.removeStatus(list.ids[i]);
list.list.removeAt(uint(i));
list.ids.removeAt(uint(i));
list.set.erase(pl.id);
}
}
//Check new
DataList@ objs = emp.getPlanets();
Object@ obj;
while(receive(objs, obj)) {
Planet@ pl = cast<Planet>(obj);
if(!list.set.contains(pl.id) && pl.level >= minLevel) {
int id = pl.addStatus(-1.0, arguments[1].integer);
list.list.insertLast(pl);
list.ids.insertLast(id);
list.set.insert(pl.id);
}
}
}
void save(any@ data, SaveFile& file) const override {
PlanetReqData@ list;
data.retrieve(@list);
if(list is null) {
file.write0();
return;
}
file.write1();
file << list.timer;
file << list.list.length;
for(uint i = 0, cnt = list.list.length; i < cnt; ++i) {
file << list.list[i];
file << list.ids[i];
}
}
void load(any@ data, SaveFile& file) const override {
if(file >= SV_0043 && file.readBit()) {
PlanetReqData list;
data.store(@list);
file >> list.timer;
uint cnt = 0;
file >> cnt;
list.list.length = cnt;
list.ids.length = cnt;
for(uint i = 0; i < cnt; ++i) {
file >> list.list[i];
file >> list.ids[i];
list.set.insert(list.list[i].id);
}
}
}
#section all
};
class SetColonizerInfo : TraitEffect {
Document doc("Change the properties of what this race's colonizers look like.");
Argument name(AT_Locale, "#COLONY_SHIP", doc="Name of a colonizer.");
Argument model(AT_Custom, EMPTY_DEFAULT, doc="Model to use for the colonizer.");
Argument material(AT_Custom, EMPTY_DEFAULT, doc="Material to use for the colonizer.");
void init(Empire& emp, any@ data) const override {
emp.ColonizerName = name.str;
if(model.str.length != 0) {
emp.ColonizerModel = model.str;
emp.ColonizerMaterial = material.str;
}
}
};
tidy final class IfHaveTrait : TraitEffect {
Document doc("Only apply the inner hook if the empire also has another trait. Cannot be used for continuous effects, only ones applied once at game start.");
Argument trait(AT_Trait, doc="Trait to check for.");
Argument hookID("Hook", AT_Hook, "trait_effects::TraitEffect");
Argument elseID("Else", AT_Hook, "", "trait_effects::TraitEffect");
ITraitEffect@ hook;
ITraitEffect@ elseHook;
bool instantiate() override {
@hook = cast<ITraitEffect>(parseHook(hookID.str, "trait_effects::"));
if(elseID.str.length != 0)
@elseHook = cast<ITraitEffect>(parseHook(elseID.str, "trait_effects::"));
return TraitEffect::instantiate();
}
void preInit(Empire& emp, any@ data) const {
if(emp.hasTrait(trait.integer)) {
if(hook !is null)
hook.preInit(emp, data);
}
else {
if(elseHook !is null)
elseHook.preInit(emp, data);
}
}
void init(Empire& emp, any@ data) const {
if(emp.hasTrait(trait.integer)) {
if(hook !is null)
hook.init(emp, data);
}
else {
if(elseHook !is null)
elseHook.init(emp, data);
}
}
void postInit(Empire& emp, any@ data) const {
if(emp.hasTrait(trait.integer)) {
if(hook !is null)
hook.postInit(emp, data);
}
else {
if(elseHook !is null)
elseHook.postInit(emp, data);
}
}
};
tidy final class IfNotHaveTrait : TraitEffect {
Document doc("Only apply the inner hook if the empire does not have another trait. Cannot be used for continuous effects, only ones applied once at game start.");
Argument trait(AT_Trait, doc="Trait to check for.");
Argument hookID("Hook", AT_Hook, "trait_effects::TraitEffect");
Argument elseID("Else", AT_Hook, "", "trait_effects::TraitEffect");
ITraitEffect@ hook;
ITraitEffect@ elseHook;
bool instantiate() override {
@hook = cast<ITraitEffect>(parseHook(hookID.str, "trait_effects::"));
if(elseID.str.length != 0)
@elseHook = cast<ITraitEffect>(parseHook(elseID.str, "trait_effects::"));
return TraitEffect::instantiate();
}
void preInit(Empire& emp, any@ data) const {
if(!emp.hasTrait(trait.integer)) {
if(hook !is null)
hook.preInit(emp, data);
}
else {
if(elseHook !is null)
elseHook.preInit(emp, data);
}
}
void init(Empire& emp, any@ data) const {
if(!emp.hasTrait(trait.integer)) {
if(hook !is null)
hook.init(emp, data);
}
else {
if(elseHook !is null)
elseHook.init(emp, data);
}
}
void postInit(Empire& emp, any@ data) const {
if(!emp.hasTrait(trait.integer)) {
if(hook !is null)
hook.postInit(emp, data);
}
else {
if(elseHook !is null)
elseHook.postInit(emp, data);
}
}
};
class AddRandomTrait : TraitEffect {
Document doc("Add a random trait with a particular unique tag to the empire.");
Argument unique_type(AT_Custom, doc="'Unique' tag to select a trait from.");
Argument ignore_trait(AT_Trait, EMPTY_DEFAULT, doc="A trait to ignore in the randomization.");
Argument only_available(AT_Boolean, "True", doc="Whether to only choose from traits that are normally available to be chosen.");
#section server
void preInit(Empire& emp, any@ data) const {
const Trait@ ourType;
const Trait@ type;
double total = 0;
const ITraitEffect@ cmp = this;
for(uint i = 0, cnt = getTraitCount(); i < cnt; ++i) {
auto@ other = getTrait(i);
for(uint n = 0, ncnt = other.hooks.length; n < ncnt; ++n) {
const ITraitEffect@ oth = other.hooks[n];
if(oth is cmp) {
@ourType = other;
break;
}
}
if(only_available.boolean && !other.available)
continue;
if(other is ourType)
continue;
if(other.cost != 0)
continue;
if(other.id == uint(ignore_trait.integer))
continue;
if(other.unique == unique_type.str) {
total += 1;
if(randomd() < 1.0 / total)
@type = other;
}
}
if(type !is null)
emp.addTrait(type.id, doPreInit=true);
}
#section all
};
tidy final class RepeatLargestFlagshipBuiltSize : TraitEffect {
Document doc("Repeat a trigger every time a flagship larger than the previously biggest flagship is built, repeats depending on size.");
Argument hookID("Hook", AT_Hook, "bonus_effects::EmpireTrigger");
EmpireTrigger@ hook;
Argument repeat_per(AT_Decimal, "10", doc="Repeat once for every time the largest ever design goes up by this amount.");
Argument start_from(AT_Decimal, "100", doc="Don't count size increments below this total size (starting ships).");
#section server
bool instantiate() override {
@hook = cast<EmpireTrigger>(parseHook(hookID.str, "bonus_effects::"));
return TraitEffect::instantiate();
}
void init(Empire& emp, any@ data) const override {
double maxSize = 0;
data.store(maxSize);
}
void tick(Empire& emp, any@ data, double time) const override {
double previous = 0;
data.retrieve(previous);
uint ind = randomi(0, emp.fleetCount-1);
Ship@ fleet = cast<Ship>(emp.fleets[ind]);
if(fleet !is null && !fleet.isStation) {
const Design@ dsg = fleet.blueprint.design;
if(dsg !is null && dsg.owner is emp) {
double flSize = floor(dsg.size / repeat_per.decimal) * repeat_per.decimal;
if(flSize > previous) {
int repeats = floor(flSize / repeat_per.decimal);
repeats -= floor(max(previous, start_from.decimal) / repeat_per.decimal);
if(repeats > 0) {
for(uint i = 0; i < uint(repeats); ++i)
hook.activate(null, emp);
}
data.store(flSize);
}
}
}
}
void save(any@ data, SaveFile& file) const override {
double val = 0;
data.retrieve(val);
file << val;
}
void load(any@ data, SaveFile& file) const override {
double val = 0;
file >> val;
data.store(val);
}
#section all
};
class ClearFirstBudget : TraitEffect {
Document doc("Make sure the first budget of the game for this empire is 0.");
#section server
void tick(Empire& emp, any@ data, double time) const override {
if(gameTime < 2.0)
emp.consumeBudget(emp.RemainingBudget, false);
}
#section all
};
class PeaceWithRemnants : TraitEffect {
Document doc("This empire will not be attacked by remnants.");
#section server
void init(Empire& emp, any@ data) const override {
Creeps.setHostile(emp, false);
emp.setHostile(Creeps, false);
}
#section all
};
class VisData {
set_int visionSystems;
array<int> list;
uint index = 0;
}
class GrantVisionTradeRange : TraitEffect {
Document doc("You automatically get vision over all systems within your trade range, even if you have no objects there.");
#section server
void init(Empire& emp, any@ data) const override {
VisData info;
data.store(@info);
}
void tick(Empire& emp, any@ data, double time) const override {
VisData@ info;
data.retrieve(@info);
for(uint n = 0; n < 50; ++n) {
info.index = (info.index+1) % systemCount;
auto@ sys = getSystem(info.index);
bool has = info.visionSystems.contains(info.index);
bool should = hasTradeAdjacent(emp, sys.object);
if(has != should) {
if(should) {
info.visionSystems.insert(info.index);
info.list.insertLast(info.index);
sys.object.grantVision(emp);
}
else {
info.visionSystems.erase(info.index);
info.list.remove(info.index);
sys.object.revokeVision(emp);
}
}
}
}
void save(any@ data, SaveFile& file) const override {
VisData@ info;
data.retrieve(@info);
uint cnt = info.list.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file << info.list[i];
}
void load(any@ data, SaveFile& file) const override {
VisData info;
data.store(@info);
uint cnt = 0;
file >> cnt;
info.list.length = cnt;
for(uint i = 0; i < cnt; ++i) {
file >> info.list[i];
info.visionSystems.insert(info.list[i]);
}
}
#section all
};
+351
View File
@@ -0,0 +1,351 @@
#priority init 5500
#section game
import saving;
import hooks;
#section menu
class Hook {};
#section all
export Trait;
export getTrait, getTraitCount;
export TraitCategory;
export getTraitCategory, getTraitCategoryCount;
tidy final class Trait {
uint id;
const TraitCategory@ category;
string ident;
string name;
string description;
string unique;
Sprite icon;
Color color;
int order = 0;
int cost = 0;
int gives = 0;
bool defaultTrait = false;
bool available = true;
bool aiSupport = true;
string dlc;
array<ITraitEffect@> hooks;
array<string> hookDefs;
array<const Trait@> conflicts;
array<string> conflictDefs;
void preInit(Empire& emp, array<any>& data) const {
data.length = hooks.length;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].preInit(emp, data[i]);
}
void init(Empire& emp, array<any>& data) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].init(emp, data[i]);
}
void postInit(Empire& emp, array<any>& data) const {
data.length = hooks.length;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].postInit(emp, data[i]);
}
void tick(Empire& emp, array<any>& data, double time) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].tick(emp, data[i], time);
}
void save(array<any>& data, SaveFile& file) const {
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].save(data[i], file);
}
void load(array<any>& data, SaveFile& file) const {
data.length = hooks.length;
for(uint i = 0, cnt = hooks.length; i < cnt; ++i)
hooks[i].load(data[i], file);
}
void addConflict(const Trait@ other) {
if(conflicts.find(other) != -1)
return;
conflicts.insertLast(other);
}
bool get_hasDLC() const {
if(dlc.length == 0)
return true;
return hasDLC(dlc);
}
bool hasConflicts(const array<const Trait@>& list) const {
for(uint i = 0, cnt = list.length; i < cnt; ++i) {
auto@ other = list[i];
if(other is this)
continue;
if(conflicts.find(other) != -1)
return true;
if(unique.length != 0 && unique == other.unique)
return true;
}
return false;
}
int opCmp(const Trait@ other) const {
if(order < other.order)
return -1;
if(order > other.order)
return 1;
return 0;
}
bool opEquals(const Trait@ other) const {
return other.id == id;
}
};
interface ITraitEffect {
void preInit(Empire& emp, any@ data) const;
void init(Empire& emp, any@ data) const;
void postInit(Empire& emp, any@ data) const;
void tick(Empire& emp, any@ data, double time) const;
void save(any@ data, SaveFile& file) const;
void load(any@ data, SaveFile& file) const;
};
class TraitEffect : Hook, ITraitEffect {
void preInit(Empire& emp, any@ data) const {}
void init(Empire& emp, any@ data) const {}
void postInit(Empire& emp, any@ data) const {}
void tick(Empire& emp, any@ data, double time) const {}
void save(any@ data, SaveFile& file) const {}
void load(any@ data, SaveFile& file) const {}
};
array<Trait@> traits;
dictionary idents;
const Trait@ getTrait(uint id) {
if(id >= traits.length)
return null;
return traits[id];
}
const Trait@ getTrait(const string& ident) {
Trait@ def;
if(idents.get(ident, @def))
return def;
return null;
}
int getTraitID(const string& ident) {
auto@ type = getTrait(ident);
if(type is null)
return -1;
return int(type.id);
}
string getTraitIdent(int id) {
auto@ type = getTrait(id);
if(type is null)
return "";
return type.ident;
}
uint getTraitCount() {
return traits.length;
}
void addTrait(Trait@ type) {
type.id = traits.length;
traits.insertLast(type);
idents.set(type.ident, @type);
}
tidy final class TraitCategory {
uint id;
string ident;
string name;
TraitCategory(const string& ident) {
this.ident = ident;
name = localize("#TRAIT_CAT_"+ident);
if(name[0] == '#')
name = ident;
}
};
array<TraitCategory@> categories;
dictionary catIdents;
const TraitCategory@ getTraitCategory(uint id) {
if(id >= categories.length)
return null;
return categories[id];
}
const TraitCategory@ getTraitCategory(const string& ident, bool create = false) {
TraitCategory@ def;
if(catIdents.get(ident, @def))
return def;
if(create)
return addTraitCategory(TraitCategory(ident));
return null;
}
uint getTraitCategoryCount() {
return categories.length;
}
TraitCategory@ addTraitCategory(TraitCategory@ type) {
type.id = categories.length;
categories.insertLast(type);
catIdents.set(type.ident, @type);
return type;
}
void saveIdentifiers(SaveFile& file) {
#section game
for(uint i = 0, cnt = traits.length; i < cnt; ++i) {
auto type = traits[i];
file.addIdentifier(SI_Trait, type.id, type.ident);
}
#section all
}
void parseLine(string& line, Trait@ trait, ReadFile@ file) {
#section game
//Hook line
trait.hookDefs.insertLast(line);
#section all
}
void loadTraits(const string& filename) {
ReadFile file(filename, true);
string key, value;
Trait@ trait;
uint index = 0;
while(file++) {
key = file.key;
value = file.value;
if(file.fullLine) {
string line = file.line;
parseLine(line, trait, file);
}
else if(key.equals_nocase("Trait")) {
if(trait !is null)
addTrait(trait);
@trait = Trait();
trait.ident = value;
}
else if(trait is null) {
file.error("Missing trait ID' line");
}
else if(key.equals_nocase("Name")) {
trait.name = localize(value);
}
else if(key.equals_nocase("Description")) {
trait.description = localize(value);
}
else if(key.equals_nocase("Costs Points")) {
trait.cost = toInt(value);
}
else if(key.equals_nocase("Gives Points")) {
trait.gives = toInt(value);
}
else if(key.equals_nocase("Category")) {
@trait.category = getTraitCategory(value, create=true);
}
else if(key.equals_nocase("Icon")) {
trait.icon = getSprite(value);
}
else if(key.equals_nocase("Color")) {
trait.color = toColor(value);
}
else if(key.equals_nocase("Order")) {
trait.order = toInt(value);
}
else if(key.equals_nocase("Unique")) {
trait.unique = value;
}
else if(key.equals_nocase("Default")) {
trait.defaultTrait = toBool(value);
}
else if(key.equals_nocase("Available")) {
trait.available = toBool(value);
}
else if(key.equals_nocase("Conflict")) {
trait.conflictDefs.insertLast(value);
}
else if(key.equals_nocase("DLC")) {
trait.dlc = value;
}
else if(key.equals_nocase("AI Support")) {
trait.aiSupport = toBool(value);
}
else {
string line = file.line;
parseLine(line, trait, file);
}
}
if(trait !is null)
addTrait(trait);
}
export initTraits;
bool initialized = false;
void initTraits() {
if(initialized)
return;
initialized = true;
FileList list("data/traits", "*.txt", true);
for(uint i = 0, cnt = list.length; i < cnt; ++i)
loadTraits(list.path[i]);
}
void preInit() {
initTraits();
#section game
for(uint i = 0, cnt = traits.length; i < cnt; ++i) {
auto@ trait = traits[i];
for(uint n = 0, ncnt = trait.hookDefs.length; n < ncnt; ++n) {
auto@ hook = cast<ITraitEffect>(parseHook(trait.hookDefs[n], "trait_effects::", instantiate=false));
if(hook !is null)
trait.hooks.insertLast(hook);
}
}
#section all
}
void init() {
for(uint i = 0, cnt = traits.length; i < cnt; ++i) {
auto@ trait = traits[i];
#section game
for(uint n = 0, ncnt = trait.hooks.length; n < ncnt; ++n) {
if(!cast<Hook>(trait.hooks[n]).instantiate())
error("Could not instantiate hook "+addrstr(trait.hooks[n])+" on trait "+trait.ident);
}
#section all
for(uint n = 0, ncnt = trait.conflictDefs.length; n < ncnt; ++n) {
Trait@ other;
if(!idents.get(trait.conflictDefs[n], @other)) {
error("Could not find conflict trait "+trait.conflictDefs[n]+" in trait "+trait.ident);
continue;
}
trait.addConflict(other);
other.addConflict(trait);
}
}
}
+54
View File
@@ -0,0 +1,54 @@
#priority init 10000
import saving;
const array<string> dlcs = {"Heralds"};
#section client
int getUnlockTag(const string& ident, bool create = true) {
return getUnlockTag_client(ident);
}
string getUnlockTagIdent(int id) {
return getUnlockTagIdent_client(id);
}
#section server-side
array<string> unlockTags;
dictionary unlockIdents;
void preInit() {
for(uint i = 0, cnt = dlcs.length; i < cnt; ++i)
getUnlockTag(dlcs[i]+"DLC", create=true);
}
uint getUnlockTagCount() {
return unlockTags.length;
}
int getUnlockTag(const string& ident, bool create = true) {
int id = -1;
if(!unlockIdents.get(ident, id) && create) {
id = int(unlockTags.length);
unlockTags.insertLast(ident);
unlockIdents.set(ident, id);
}
return id;
}
int getUnlockTag_client(string ident) {
int id = -1;
if(unlockIdents.get(ident, id))
return id;
return -1;
}
string getUnlockTagIdent(int id) {
if(id < 0 || uint(id) >= unlockTags.length)
return "";
return unlockTags[id];
}
void saveIdentifiers(SaveFile& file) {
for(uint i = 0, cnt = unlockTags.length; i < cnt; ++i)
file.addIdentifier(SI_UnlockTag, int(i), unlockTags[i]);
}
+9
View File
@@ -0,0 +1,9 @@
#section menu
void preInit() {
MP_VERSION = 81;
}
#section all
const bool STEAM_EQUIV_BUILD = IS_STEAM_BUILD;
const string GAME_VERSION = "v2.0.3";
const string SCRIPT_VERSION = "DEV";
+598
View File
@@ -0,0 +1,598 @@
import hooks;
import influence;
from bonus_effects import BonusEffect;
import hook_globals;
import systems;
import saving;
#section server
from influence import InfluenceStore;
from influence_global import createInfluenceEffect, getSenateLeader;
#section all
//ClaimPlanet(<Event>, <Target>)
// Claim <Target> planet if <Event> happens.
// <Event> should be one of 'pass' or 'fail'.
class ClaimPlanet : InfluenceVoteEffect {
Document doc("Claims a target planet when the vote passes or fails.");
Argument event("Event", AT_PassFail, doc="Either 'pass' or 'fail' to choose when the result occurs.");
Argument targ("Target", TT_Object);
#section server
void onStart(InfluenceVote@ vote) const override {
Object@ obj = targ.fromTarget(vote.targets).obj;
obj.setContestion(true);
}
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const override {
Object@ obj = targ.fromTarget(vote.targets).obj;
if(passed == event.boolean)
obj.takeoverPlanet(vote.startedBy, 0.5);
obj.setContestion(false);
}
#section all
};
//CreateEffect(<Event>, <Effect>, <Target>, <Duration> = 0)
// Create a new influence effect if <Event> happens.
// <Event> should be one of 'pass' or 'fail'.
// If duration is set to 0, the default from the effect is used.
class CreateEffect : InfluenceVoteEffect {
Document doc("Starts a new influence effect when the vote passes or fails.");
Argument event("Event", AT_PassFail, doc="Either 'pass' or 'fail' to choose when the result occurs.");
Argument effect("Effect", AT_InfluenceEffect, doc="ID of the influence effect to create.");
Argument targ("Target", TT_Any, EMPTY_DEFAULT);
Argument duration("Duration", AT_Decimal, "0", doc="Duration in seconds for the effect to last.");
Argument give_to_contributor(AT_Boolean, "False", doc="If set, the effect is given to the highest contributor of the vote, instead of the empire that started it.");
const InfluenceEffectType@ effectType;
void init(InfluenceVoteType@ type) override {
@effectType = getInfluenceEffectType(effect.str);
if(effectType is null)
error("Error: CreateEffect() could not find effect "+effect.str);
}
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
if(passed != event.boolean)
return;
Targets effTargs = effectType.targets;
if(targ.integer != -1 && effTargs.targets.length != 0)
effTargs.targets[0] = targ.fromTarget(vote.targets);
Empire@ owner = vote.startedBy;
if(give_to_contributor.boolean) {
Empire@ contrib = vote.highestContribPoints;
if(contrib !is null && vote.getVoteFrom(contrib) != 0)
@owner = contrib;
}
createInfluenceEffect(owner, effectType, effTargs, duration.decimal);
}
#section all
};
//Trigger(<Object>, <Hook>(...), <Event> = Pass)
// Run <Hook> as a single-time effect hook on <Planet>.
tidy final class Trigger : InfluenceVoteEffect {
Document doc("Triggers another hook when the vote passes or fails.");
Argument targ("Object", TT_Object);
Argument hookID("Hook", AT_Hook, "bonus_effects::EmpireTrigger", doc="Hook to trigger.");
Argument event("Event", AT_PassFail, "Pass", doc="Either 'pass' or 'fail' to choose when the result occurs.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(arguments[1].str, "bonus_effects::"));
if(hook is null) {
error("BonusEffect(): could not find inner hook: "+escape(arguments[1].str));
return false;
}
return InfluenceVoteEffect::instantiate();
}
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
if(passed != arguments[2].boolean)
return;
auto@ objTarg = arguments[0].fromTarget(vote.targets);
if(objTarg is null || objTarg.obj is null)
return;
hook.activate(objTarg.obj, vote.startedBy);
}
#section all
};
tidy final class TriggerHighestContributor : InfluenceVoteEffect {
Document doc("Trigger an effect on the empire that contributed the most to this vote.");
Argument hookID("Hook", AT_Hook, "bonus_effects::EmpireTrigger", doc="Hook to trigger.");
Argument event("Event", AT_PassFail, "Pass", doc="Either 'pass' or 'fail' to choose when the result occurs.");
Argument randomize(AT_Boolean, "False", doc="Whether to pick a random one if multiple empires apply.");
Argument multiple(AT_Boolean, "True", doc="Whether to apply to all empires if multiple empires apply.");
Argument require_positive(AT_Boolean, "True", doc="Whether to require at least 1 support to trigger, or allow triggering on 0 as well.");
Argument use_points(AT_Boolean, "True", doc="Whether to judge contributions by integrated contribution points over time. If set to false, only the final support value of each empire is used.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::"));
if(hook is null) {
error("BonusEffect(): could not find inner hook: "+escape(hookID.str));
return false;
}
return InfluenceVoteEffect::instantiate();
}
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
if(passed != event.boolean)
return;
double highest = -INFINITY;
if(require_positive.boolean)
highest = 0.01;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
if(!getEmpire(i).major)
continue;
double val = 0;
if(use_points.boolean)
val = vote.contribPoints[i];
else
val = vote.empireVotes[i];
if(val > highest)
highest = val;
}
array<Empire@> choices;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
if(!getEmpire(i).major)
continue;
double val = 0;
if(use_points.boolean)
val = vote.contribPoints[i];
else
val = vote.empireVotes[i];
if(val >= highest - 0.0001)
choices.insertLast(getEmpire(i));
}
if(choices.length == 0) {
return;
}
else if(choices.length == 1) {
hook.activate(null, choices[0]);
}
else {
if(randomize.boolean) {
Empire@ targ = choices[randomi(0, choices.length-1)];
hook.activate(null, choices[0]);
}
else if(multiple.boolean) {
for(uint i = 0, cnt = choices.length; i < cnt; ++i)
hook.activate(null, choices[i]);
}
}
}
#section all
};
tidy final class TriggerLowestContributor : InfluenceVoteEffect {
Document doc("Trigger an effect on the empire that contributed the least to this vote.");
Argument hookID("Hook", AT_Hook, "bonus_effects::EmpireTrigger", doc="Hook to trigger.");
Argument event("Event", AT_PassFail, "Pass", doc="Either 'pass' or 'fail' to choose when the result occurs.");
Argument randomize(AT_Boolean, "False", doc="Whether to pick a random one if multiple empires apply.");
Argument multiple(AT_Boolean, "True", doc="Whether to apply to all empires if multiple empires apply.");
Argument require_negative(AT_Boolean, "False", doc="Whether to only trigger for empires that actually opposed, instead of just being the lowest support.");
Argument use_points(AT_Boolean, "True", doc="Whether to judge contributions by integrated contribution points over time. If set to false, only the final support value of each empire is used.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::"));
if(hook is null) {
error("BonusEffect(): could not find inner hook: "+escape(hookID.str));
return false;
}
return InfluenceVoteEffect::instantiate();
}
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
if(passed != event.boolean)
return;
double lowest = INFINITY;
if(require_negative.boolean)
lowest = -0.01;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
if(!getEmpire(i).major)
continue;
double val = 0;
if(use_points.boolean)
val = vote.contribPoints[i];
else
val = vote.empireVotes[i];
if(val < lowest)
lowest = val;
}
array<Empire@> choices;
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
if(!getEmpire(i).major)
continue;
double val = 0;
if(use_points.boolean)
val = vote.contribPoints[i];
else
val = vote.empireVotes[i];
if(val <= lowest + 0.0001)
choices.insertLast(getEmpire(i));
}
if(choices.length == 0) {
return;
}
else if(choices.length == 1) {
hook.activate(null, choices[0]);
}
else {
if(randomize.boolean) {
Empire@ targ = choices[randomi(0, choices.length-1)];
hook.activate(null, choices[0]);
}
else if(multiple.boolean) {
for(uint i = 0, cnt = choices.length; i < cnt; ++i)
hook.activate(null, choices[i]);
}
}
}
#section all
};
tidy final class OnOwner : InfluenceVoteEffect {
Document doc("Triggers an empire hook when the vote passes or fails.");
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to trigger.");
Argument event("Event", AT_PassFail, "Pass", doc="Either 'pass' or 'fail' to choose when the result occurs.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(hookID.str, "bonus_effects::"));
if(hook is null) {
error("BonusEffect(): could not find inner hook: "+escape(hookID.str));
return false;
}
return InfluenceVoteEffect::instantiate();
}
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
if(passed != event.boolean)
return;
hook.activate(null, vote.startedBy);
}
#section all
};
//CancelOnWar(<Target>)
// Cancel the vote when the owner becomes at war with the target.
class CancelOnWar : InfluenceVoteEffect {
Document doc("Ends the vote when the vote starter is at war with the target.");
Argument targ("Target", TT_Empire);
#section server
bool onTick(InfluenceVote@ vote, double time) const override {
Empire@ to = arguments[0].fromTarget(vote.targets).emp;
if(vote.startedBy !is null && vote.startedBy.isHostile(to))
vote.end(false, true);
return false;
}
#section all
};
class CancelIfNotLeader : InfluenceVoteEffect {
Document doc("Cancel the vote if the owner is not the senate leader.");
#section server
bool onTick(InfluenceVote@ vote, double time) const override {
if(vote.startedBy !is getSenateLeader())
vote.end(false, true);
return false;
}
#section all
};
class CancelIfAttributeLT : InfluenceVoteEffect {
Document doc("Cancel the vote if the owner's attribute is too low.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
Argument value(AT_Decimal, "1", doc="Value to test against.");
#section server
bool onTick(InfluenceVote@ vote, double time) const override {
Empire@ owner = vote.startedBy;
if(owner is null || !owner.valid)
return false;
if(owner.getAttribute(attribute.integer) < value.decimal)
vote.end(false, true);
return false;
}
#section all
};
//CancelOnDestroyed(<Target>)
// Cancel the vote when the target is no longer valid.
class CancelOnDestroyed : InfluenceVoteEffect {
Document doc("Ends the vote when the target object is no longer valid (destroyed).");
Argument targ("Target", TT_Object);
#section server
bool onTick(InfluenceVote@ vote, double time) const override {
Object@ obj = arguments[0].fromTarget(vote.targets).obj;
if(obj is null || !obj.valid)
vote.end(false, true);
return false;
}
#section all
};
//CancelOnLost(<Target>)
// Cancel the vote when the target is no longer ours.
class CancelOnLost : InfluenceVoteEffect {
Document doc("Ends the vote when the target object is no longer owned by this empire.");
Argument targ("Target", TT_Object);
#section server
bool onTick(InfluenceVote@ vote, double time) const override {
Object@ obj = arguments[0].fromTarget(vote.targets).obj;
if(obj is null || !obj.valid || obj.owner !is vote.startedBy)
vote.end(false, true);
return false;
}
#section all
};
//ClaimSystem(<Event>, <Target>)
// Claim all planets in <Target> system if <Event> happens.
// <Event> should be one of 'pass' or 'fail'.
class ClaimSystem : InfluenceVoteEffect {
Document doc("Claims a target system when the vote passes or fails.");
Argument event("Event", AT_PassFail, doc="Either 'pass' or 'fail' to choose when the result occurs.");
Argument targ("Target", TT_Object);
#section server
void onStart(InfluenceVote@ vote) const {
array<Object@> contested;
vote.data[hookIndex].store(@contested);
Object@ obj = arguments[1].fromTarget(vote.targets).obj;
Region@ reg = cast<Region>(obj);
if(reg is null)
@reg = obj.region;
if(reg is null)
return;
for(uint i = 0, cnt = reg.planetCount; i < cnt; ++i) {
Planet@ pl = reg.planets[i];
if(pl !is null && pl.owner !is null && pl.owner !is vote.startedBy && pl.owner.valid) {
pl.setContestion(true);
contested.insertLast(pl);
}
}
}
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
array<Object@>@ contested;
vote.data[hookIndex].retrieve(@contested);
if(contested !is null) {
for(uint i = 0, cnt = contested.length; i < cnt; ++i)
contested[i].setContestion(false);
}
if(passed == arguments[0].boolean) {
Object@ obj = arguments[1].fromTarget(vote.targets).obj;
for(uint i = 0, cnt = obj.planetCount; i < cnt; ++i) {
Planet@ pl = obj.planets[i];
if(pl !is null && pl.owner !is null && pl.owner !is vote.startedBy && pl.owner.valid) {
pl.takeoverPlanet(vote.startedBy, 0.5);
}
}
}
}
void save(InfluenceVote@ vote, SaveFile& file) const override {
array<Object@>@ contested;
vote.data[hookIndex].retrieve(@contested);
uint cnt = 0;
if(contested !is null)
cnt = contested.length;
file << cnt;
for(uint i = 0; i < cnt; ++i)
file << contested[i];
}
void load(InfluenceVote@ vote, SaveFile& file) const override {
array<Object@> contested;
vote.data[hookIndex].store(@contested);
if(file >= SV_0159) {
uint cnt = 0;
file >> cnt;
for(uint i = 0; i < cnt; ++i) {
Object@ obj;
file >> obj;
if(obj !is null)
contested.insertLast(obj);
}
}
}
#section all
};
//FlagContested(<Target>)
// Mark <Target> as contested for the duration of the vote.
class FlagContested : InfluenceVoteEffect {
Document doc("Marks an object as contested while the vote is in progress.");
Argument targ("Target", TT_Object);
#section server
void onStart(InfluenceVote@ vote) const {
Object@ obj = arguments[0].fromTarget(vote.targets).obj;
if(obj.isPlanet)
obj.setContestion(true);
else if(obj.isOrbital)
cast<Orbital>(obj).setContested(true);
}
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
Object@ obj = arguments[0].fromTarget(vote.targets).obj;
if(obj.isPlanet)
obj.setContestion(false);
else if(obj.isOrbital)
cast<Orbital>(obj).setContested(false);
}
#section all
};
//ModGlobal(<Event>, <Global>, <Amount>)
// Modify a global value when an event happens.
class ModGlobal : InfluenceVoteEffect {
Document doc("Adds a value to a global when the vote passes or fails.");
Argument event("Event", AT_PassFail, doc="Either 'pass' or 'fail' to choose when the result occurs.");
Argument global("Global", AT_Global, doc="Which global value to modify.");
Argument amount("Amount", AT_Decimal, doc="Amount to modify it by.");
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const override {
if(passed == arguments[0].boolean) {
auto@ glob = getGlobal(arguments[1].integer);
glob.add(arguments[2].decimal);
}
}
#section all
};
//TriggerAllPlanets(<Hook>(...), <Event> = Pass)
// Run <Hook> as a single-time effect hook on all planets in the galaxy.
tidy final class TriggerAllPlanets : InfluenceVoteEffect {
Document doc("Runs another hook on all planets when the vote passes or fails.");
Argument hookID("Hook", AT_Hook, "bonus_effects::BonusEffect", doc="Hook to trigger.");
Argument event("Event", AT_PassFail, "Pass", doc="Either 'pass' or 'fail' to choose when the result occurs.");
BonusEffect@ hook;
bool instantiate() override {
@hook = cast<BonusEffect>(parseHook(arguments[0].str, "bonus_effects::"));
if(hook is null) {
error("BonusEffect(): could not find inner hook: "+escape(arguments[0].str));
return false;
}
return InfluenceVoteEffect::instantiate();
}
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const {
if(passed != arguments[1].boolean)
return;
for(uint i = 0, cnt = systemCount; i < cnt; ++i) {
auto@ sys = getSystem(i);
for(uint n = 0, ncnt = sys.object.planetCount; n < ncnt; ++n) {
Object@ obj = sys.object.planets[n];
hook.activate(obj, vote.startedBy);
}
}
}
#section all
};
class AddStartWeight : InfluenceVoteEffect {
Document doc("Add an amount of weight to the vote when it is started.");
Argument weight(AT_Integer, doc="Amount of weight to add.");
#section server
void onStart(InfluenceVote@ vote) const {
if(weight.integer > 0)
vote.totalFor += weight.integer;
else
vote.totalAgainst -= weight.integer;
}
#section all
};
class MultiplyPositiveSpeed : InfluenceVoteEffect {
Document doc("The vote proceeds in the positive at a multiplied rate.");
Argument amount(AT_Decimal, doc="Speed multiplier for the vote.");
void onStart(InfluenceVote@ vote) const override {
vote.positiveSpeed *= amount.decimal;
}
};
class MultiplyNegativeSpeed : InfluenceVoteEffect {
Document doc("The vote proceeds in the negative at a multiplied rate.");
Argument amount(AT_Decimal, doc="Speed multiplier for the vote.");
void onStart(InfluenceVote@ vote) const override {
vote.negativeSpeed *= amount.decimal;
}
};
class AddPositiveCostPenalty : InfluenceVoteEffect {
Document doc("Increase the cost of positive cards played in this vote.");
Argument amount(AT_Integer, doc="Amount extra to add to play costs.");
void onStart(InfluenceVote@ vote) const override {
vote.positiveCostPenalty += amount.integer;
}
};
class AddNegativeCostPenalty : InfluenceVoteEffect {
Document doc("Increase the cost of negative cards played in this vote.");
Argument amount(AT_Integer, doc="Amount extra to add to play costs.");
void onStart(InfluenceVote@ vote) const override {
vote.negativeCostPenalty += amount.integer;
}
};
class FailReturnCardIfAttributeSet : InfluenceVoteEffect {
Document doc("If the vote fails and the given empire attribute is not zero, return the card to the owner.");
Argument attribute(AT_EmpAttribute, doc="Attribute to check.");
#section server
void onEnd(InfluenceVote@ vote, bool passed, bool withdrawn) const override {
if(!passed && !withdrawn && vote.startedBy.getAttribute(attribute.integer) > 0) {
if(vote.events.length == 0)
return;
auto@ evt = vote.events[0];
if(evt.type != IVET_Start || evt.cardEvent is null)
return;
auto@ startCard = evt.cardEvent.card;
auto@ newCard = startCard.type.create(uses=1, quality=startCard.quality);
cast<InfluenceStore>(vote.startedBy.InfluenceManager).addCard(vote.startedBy, newCard);
}
}
#section all
};
class EmpireStartWeightAttribute : InfluenceVoteEffect {
Document doc("Add weight to each empire at the start based on a particular attribute.");
Argument attribute(AT_EmpAttribute, doc="Attribute to use.");
#section server
void onStart(InfluenceVote@ vote) const override {
for(uint i = 0, cnt = getEmpireCount(); i < cnt; ++i) {
Empire@ emp = getEmpire(i);
if(!emp.major)
continue;
int support = floor(emp.getAttribute(attribute.integer));
if(support == 0)
continue;
if(vote.isPresent(emp))
vote.vote(emp, support);
}
}
#section all
};