Index: ps/trunk/binaries/data/mods/public/simulation/components/Builder.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/Builder.js (revision 24009) +++ ps/trunk/binaries/data/mods/public/simulation/components/Builder.js (revision 24010) @@ -1,101 +1,101 @@ function Builder() {} Builder.prototype.Schema = "Allows the unit to construct and repair buildings." + "" + "1.0" + "" + "\n structures/{civ}_barracks\n structures/{native}_civil_centre\n structures/pers_apadana\n " + "" + "" + "" + "" + "" + "" + "" + "tokens" + "" + "" + ""; Builder.prototype.Init = function() { }; Builder.prototype.Serialize = null; // we have no dynamic state to save Builder.prototype.GetEntitiesList = function() { let string = this.template.Entities._string; if (!string) return []; let cmpPlayer = QueryOwnerInterface(this.entity); if (!cmpPlayer) return []; string = ApplyValueModificationsToEntity("Builder/Entities/_string", string, this.entity); let cmpIdentity = Engine.QueryInterface(this.entity, IID_Identity); if (cmpIdentity) string = string.replace(/\{native\}/g, cmpIdentity.GetCiv()); let entities = string.replace(/\{civ\}/g, cmpPlayer.GetCiv()).split(/\s+/); let disabledTemplates = cmpPlayer.GetDisabledTemplates(); let cmpTemplateManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager); return entities.filter(ent => !disabledTemplates[ent] && cmpTemplateManager.TemplateExists(ent)); }; Builder.prototype.GetRange = function() { let max = 2; let cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); if (cmpObstruction) - max += cmpObstruction.GetUnitRadius(); + max += cmpObstruction.GetSize(); return { "max": max, "min": 0 }; }; Builder.prototype.GetRate = function() { return ApplyValueModificationsToEntity("Builder/Rate", +this.template.Rate, this.entity); }; /** * Build/repair the target entity. This should only be called after a successful range check. * It should be called at a rate of once per second. */ Builder.prototype.PerformBuilding = function(target) { let rate = this.GetRate(); let cmpFoundation = Engine.QueryInterface(target, IID_Foundation); if (cmpFoundation) { cmpFoundation.Build(this.entity, rate); return; } let cmpRepairable = Engine.QueryInterface(target, IID_Repairable); if (cmpRepairable) { cmpRepairable.Repair(this.entity, rate); return; } }; Builder.prototype.OnValueModification = function(msg) { if (msg.component != "Builder" || !msg.valueNames.some(name => name.endsWith('_string'))) return; // Token changes may require selection updates. let cmpPlayer = QueryOwnerInterface(this.entity, IID_Player); if (cmpPlayer) Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface).SetSelectionDirty(cmpPlayer.GetPlayerID()); }; Engine.RegisterComponentType(IID_Builder, "Builder", Builder); Index: ps/trunk/binaries/data/mods/public/simulation/components/GarrisonHolder.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/GarrisonHolder.js (revision 24009) +++ ps/trunk/binaries/data/mods/public/simulation/components/GarrisonHolder.js (revision 24010) @@ -1,672 +1,672 @@ function GarrisonHolder() {} GarrisonHolder.prototype.Schema = "" + "" + "" + "" + "" + "tokens" + "" + "" + "" + "" + "" + "tokens" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; /** * Initialize GarrisonHolder Component * Garrisoning when loading a map is set in the script of the map, by setting initGarrison * which should contain the array of garrisoned entities. */ GarrisonHolder.prototype.Init = function() { // Garrisoned Units this.entities = []; this.timer = undefined; this.allowGarrisoning = new Map(); }; /** * @param {number} entity - The entity to verify. * @return {boolean} - Whether the given entity is garrisoned in this GarrisonHolder. */ GarrisonHolder.prototype.IsGarrisoned = function(entity) { return this.entities.indexOf(entity) != -1; }; /** * @return {Object} max and min range at which entities can garrison the holder. */ GarrisonHolder.prototype.GetLoadingRange = function() { return { "max": +this.template.LoadingRange, "min": 0 }; }; GarrisonHolder.prototype.CanPickup = function(ent) { if (!this.template.Pickup || this.IsFull()) return false; let cmpOwner = Engine.QueryInterface(this.entity, IID_Ownership); return !!cmpOwner && IsOwnedByPlayer(cmpOwner.GetOwner(), ent); }; GarrisonHolder.prototype.GetEntities = function() { return this.entities; }; /** * @return {Array} unit classes which can be garrisoned inside this * particular entity. Obtained from the entity's template. */ GarrisonHolder.prototype.GetAllowedClasses = function() { return this.template.List._string; }; GarrisonHolder.prototype.GetCapacity = function() { return ApplyValueModificationsToEntity("GarrisonHolder/Max", +this.template.Max, this.entity); }; GarrisonHolder.prototype.IsFull = function() { return this.GetGarrisonedEntitiesCount() >= this.GetCapacity(); }; GarrisonHolder.prototype.GetHealRate = function() { return ApplyValueModificationsToEntity("GarrisonHolder/BuffHeal", +this.template.BuffHeal, this.entity); }; /** * Set this entity to allow or disallow garrisoning in the entity. * Every component calling this function should do it with its own ID, and as long as one * component doesn't allow this entity to garrison, it can't be garrisoned * When this entity already contains garrisoned soldiers, * these will not be able to ungarrison until the flag is set to true again. * * This more useful for modern-day features. For example you can't garrison or ungarrison * a driving vehicle or plane. * @param {boolean} allow - Whether the entity should be garrisonable. */ GarrisonHolder.prototype.AllowGarrisoning = function(allow, callerID) { this.allowGarrisoning.set(callerID, allow); }; GarrisonHolder.prototype.IsGarrisoningAllowed = function() { return Array.from(this.allowGarrisoning.values()).every(allow => allow); }; GarrisonHolder.prototype.GetGarrisonedEntitiesCount = function() { let count = this.entities.length; for (let ent of this.entities) { let cmpGarrisonHolder = Engine.QueryInterface(ent, IID_GarrisonHolder); if (cmpGarrisonHolder) count += cmpGarrisonHolder.GetGarrisonedEntitiesCount(); } return count; }; GarrisonHolder.prototype.IsAllowedToGarrison = function(entity) { if (!this.IsGarrisoningAllowed()) return false; if (!IsOwnedByMutualAllyOfEntity(entity, this.entity)) return false; let extraCount = 0; let cmpGarrisonHolder = Engine.QueryInterface(entity, IID_GarrisonHolder); if (cmpGarrisonHolder) extraCount += cmpGarrisonHolder.GetGarrisonedEntitiesCount(); if (this.GetGarrisonedEntitiesCount() + extraCount >= this.GetCapacity()) return false; let cmpIdentity = Engine.QueryInterface(entity, IID_Identity); if (!cmpIdentity) return false; let entityClasses = cmpIdentity.GetClassesList(); return MatchesClassList(entityClasses, this.template.List._string) && !!Engine.QueryInterface(entity, IID_Garrisonable); }; /** * @param {number} entity - The entityID to garrison. * @param {boolean} renamed - Whether the entity was renamed. * * @return {boolean} - Whether the entity was garrisoned. */ GarrisonHolder.prototype.Garrison = function(entity, renamed = false) { if (!this.IsAllowedToGarrison(entity)) return false; if (!this.HasEnoughHealth()) return false; if (!this.timer && this.GetHealRate() > 0) { let cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); this.timer = cmpTimer.SetTimeout(this.entity, IID_GarrisonHolder, "HealTimeout", 1000, {}); } this.entities.push(entity); this.UpdateGarrisonFlag(); let cmpProductionQueue = Engine.QueryInterface(entity, IID_ProductionQueue); if (cmpProductionQueue) cmpProductionQueue.PauseProduction(); let cmpAura = Engine.QueryInterface(entity, IID_Auras); if (cmpAura && cmpAura.HasGarrisonAura()) cmpAura.ApplyGarrisonAura(this.entity); let cmpPosition = Engine.QueryInterface(entity, IID_Position); if (cmpPosition) cmpPosition.MoveOutOfWorld(); Engine.PostMessage(this.entity, MT_GarrisonedUnitsChanged, { "added": [entity], "removed": [], "renamed": renamed }); return true; }; /** * Simply eject the unit from the garrisoning entity without moving it * @param {number} entity - Id of the entity to be ejected. * @param {boolean} forced - Whether eject is forced (i.e. if building is destroyed). * @param {boolean} renamed - Whether eject was due to entity renaming. * * @return {boolean} Whether the entity was ejected. */ GarrisonHolder.prototype.Eject = function(entity, forced, renamed = false) { let entityIndex = this.entities.indexOf(entity); // Error: invalid entity ID, usually it's already been ejected if (entityIndex == -1) return false; // Find spawning location let cmpFootprint = Engine.QueryInterface(this.entity, IID_Footprint); let cmpHealth = Engine.QueryInterface(this.entity, IID_Health); let cmpIdentity = Engine.QueryInterface(this.entity, IID_Identity); // If the garrisonHolder is a sinking ship, restrict the location to the intersection of both passabilities // TODO: should use passability classes to be more generic let pos; if ((!cmpHealth || cmpHealth.GetHitpoints() == 0) && cmpIdentity && cmpIdentity.HasClass("Ship")) pos = cmpFootprint.PickSpawnPointBothPass(entity); else pos = cmpFootprint.PickSpawnPoint(entity); if (pos.y < 0) { // Error: couldn't find space satisfying the unit's passability criteria if (!forced) return false; // If ejection is forced, we need to continue, so use center of the building let cmpPosition = Engine.QueryInterface(this.entity, IID_Position); pos = cmpPosition.GetPosition(); } this.entities.splice(entityIndex, 1); let cmpEntUnitAI = Engine.QueryInterface(entity, IID_UnitAI); if (cmpEntUnitAI) cmpEntUnitAI.Ungarrison(); let cmpEntProductionQueue = Engine.QueryInterface(entity, IID_ProductionQueue); if (cmpEntProductionQueue) cmpEntProductionQueue.UnpauseProduction(); let cmpEntAura = Engine.QueryInterface(entity, IID_Auras); if (cmpEntAura && cmpEntAura.HasGarrisonAura()) cmpEntAura.RemoveGarrisonAura(this.entity); let cmpEntPosition = Engine.QueryInterface(entity, IID_Position); if (cmpEntPosition) { cmpEntPosition.JumpTo(pos.x, pos.z); cmpEntPosition.SetHeightOffset(0); let cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (cmpPosition) cmpEntPosition.SetYRotation(cmpPosition.GetPosition().horizAngleTo(pos)); } Engine.PostMessage(this.entity, MT_GarrisonedUnitsChanged, { "added": [], "removed": [entity], "renamed": renamed }); return true; }; /** * Ejects units and orders them to move to the rally point. If an ejection * with a given obstruction radius has failed, we won't try anymore to eject * entities with a bigger obstruction as that is compelled to also fail. * @param {Array} entities - An array containing the ids of the entities to eject. * @param {boolean} forced - Whether eject is forced (ie: if building is destroyed). * @return {boolean} Whether the entities were ejected. */ GarrisonHolder.prototype.PerformEject = function(entities, forced) { if (!this.IsGarrisoningAllowed() && !forced) return false; let ejectedEntities = []; let success = true; let failedRadius; let radius; let cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership); for (let entity of entities) { if (failedRadius !== undefined) { let cmpObstruction = Engine.QueryInterface(entity, IID_Obstruction); - radius = cmpObstruction ? cmpObstruction.GetUnitRadius() : 0; + radius = cmpObstruction ? cmpObstruction.GetSize() : 0; if (radius >= failedRadius) continue; } if (this.Eject(entity, forced)) { let cmpEntOwnership = Engine.QueryInterface(entity, IID_Ownership); if (cmpOwnership && cmpEntOwnership && cmpOwnership.GetOwner() == cmpEntOwnership.GetOwner()) ejectedEntities.push(entity); } else { success = false; if (failedRadius !== undefined) failedRadius = Math.min(failedRadius, radius); else { let cmpObstruction = Engine.QueryInterface(entity, IID_Obstruction); - failedRadius = cmpObstruction ? cmpObstruction.GetUnitRadius() : 0; + failedRadius = cmpObstruction ? cmpObstruction.GetSize() : 0; } } } this.OrderWalkToRallyPoint(ejectedEntities); this.UpdateGarrisonFlag(); return success; }; /** * Order entities to walk to the rally point. * @param {Array} entities - An array containing all the ids of the entities. */ GarrisonHolder.prototype.OrderWalkToRallyPoint = function(entities) { let cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership); let cmpRallyPoint = Engine.QueryInterface(this.entity, IID_RallyPoint); if (!cmpRallyPoint || !cmpRallyPoint.GetPositions()[0]) return; let commands = GetRallyPointCommands(cmpRallyPoint, entities); // Ignore the rally point if it is autogarrison if (commands[0].type == "garrison" && commands[0].target == this.entity) return; for (let command of commands) ProcessCommand(cmpOwnership.GetOwner(), command); }; /** * Unload unit from the garrisoning entity and order them * to move to the rally point. * @return {boolean} Whether the command was successful. */ GarrisonHolder.prototype.Unload = function(entity, forced) { return this.PerformEject([entity], forced); }; /** * Unload one or all units that match a template and owner from * the garrisoning entity and order them to move to the rally point. * @param {string} template - Type of units that should be ejected. * @param {number} owner - Id of the player whose units should be ejected. * @param {boolean} all - Whether all units should be ejected. * @param {boolean} forced - Whether unload is forced. * @return {boolean} Whether the unloading was successful. */ GarrisonHolder.prototype.UnloadTemplate = function(template, owner, all, forced) { let entities = []; let cmpTemplateManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager); for (let entity of this.entities) { let cmpIdentity = Engine.QueryInterface(entity, IID_Identity); // Units with multiple ranks are grouped together. let name = cmpIdentity.GetSelectionGroupName() || cmpTemplateManager.GetCurrentTemplateName(entity); if (name != template || owner != Engine.QueryInterface(entity, IID_Ownership).GetOwner()) continue; entities.push(entity); // If 'all' is false, only ungarrison the first matched unit. if (!all) break; } return this.PerformEject(entities, forced); }; /** * Unload all units, that belong to certain player * and order all own units to move to the rally point. * @param {boolean} forced - Whether unload is forced. * @param {number} owner - Id of the player whose units should be ejected. * @return {boolean} Whether the unloading was successful. */ GarrisonHolder.prototype.UnloadAllByOwner = function(owner, forced) { let entities = this.entities.filter(ent => { let cmpOwnership = Engine.QueryInterface(ent, IID_Ownership); return cmpOwnership && cmpOwnership.GetOwner() == owner; }); return this.PerformEject(entities, forced); }; /** * Unload all units from the entity and order them to move to the rally point. * @param {boolean} forced - Whether unload is forced. * @return {boolean} Whether the unloading was successful. */ GarrisonHolder.prototype.UnloadAll = function(forced) { return this.PerformEject(this.entities.slice(), forced); }; /** * Used to check if the garrisoning entity's health has fallen below * a certain limit after which all garrisoned units are unloaded. */ GarrisonHolder.prototype.OnHealthChanged = function(msg) { if (!this.HasEnoughHealth() && this.entities.length) this.EjectOrKill(this.entities.slice()); }; GarrisonHolder.prototype.HasEnoughHealth = function() { // 0 is a valid value so explicitly check for undefined. if (this.template.EjectHealth === undefined) return true; let cmpHealth = Engine.QueryInterface(this.entity, IID_Health); return !cmpHealth || cmpHealth.GetHitpoints() > Math.floor(+this.template.EjectHealth * cmpHealth.GetMaxHitpoints()); }; /** * Called every second. Heals garrisoned units. */ GarrisonHolder.prototype.HealTimeout = function(data) { let cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); if (!this.entities.length) { cmpTimer.CancelTimer(this.timer); this.timer = undefined; return; } for (let entity of this.entities) { let cmpHealth = Engine.QueryInterface(entity, IID_Health); if (cmpHealth && !cmpHealth.IsUnhealable()) cmpHealth.Increase(this.GetHealRate()); } this.timer = cmpTimer.SetTimeout(this.entity, IID_GarrisonHolder, "HealTimeout", 1000, {}); }; /** * Updates the garrison flag depending whether something is garrisoned in the entity. */ GarrisonHolder.prototype.UpdateGarrisonFlag = function() { let cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); if (!cmpVisual) return; cmpVisual.SetVariant("garrison", this.entities.length ? "garrisoned" : "ungarrisoned"); }; /** * Cancel timer when destroyed. */ GarrisonHolder.prototype.OnDestroy = function() { if (this.timer) { let cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); cmpTimer.CancelTimer(this.timer); } }; /** * If a garrisoned entity is captured, or about to be killed (so its owner changes to '-1'), * remove it from the building so we only ever contain valid entities. */ GarrisonHolder.prototype.OnGlobalOwnershipChanged = function(msg) { // The ownership change may be on the garrisonholder if (this.entity == msg.entity) { let entities = this.entities.filter(ent => msg.to == INVALID_PLAYER || !IsOwnedByMutualAllyOfEntity(this.entity, ent)); if (entities.length) this.EjectOrKill(entities); return; } // or on some of its garrisoned units let entityIndex = this.entities.indexOf(msg.entity); if (entityIndex != -1) { // If the entity is dead, remove it directly instead of ejecting the corpse let cmpHealth = Engine.QueryInterface(msg.entity, IID_Health); if (cmpHealth && cmpHealth.GetHitpoints() == 0) { this.entities.splice(entityIndex, 1); Engine.PostMessage(this.entity, MT_GarrisonedUnitsChanged, { "added": [], "removed": [msg.entity] }); this.UpdateGarrisonFlag(); } else if (msg.to == INVALID_PLAYER || !IsOwnedByMutualAllyOfEntity(this.entity, msg.entity)) this.EjectOrKill([msg.entity]); } }; /** * Update list of garrisoned entities if one gets renamed (e.g. by promotion). */ GarrisonHolder.prototype.OnGlobalEntityRenamed = function(msg) { let entityIndex = this.entities.indexOf(msg.entity); if (entityIndex != -1) { this.Eject(msg.entity, true, true); this.Garrison(msg.newentity, true); // TurretHolder is not subscribed to GarrisonChanged, so we must inform it explicitly. // Otherwise a renaming entity may re-occupy another turret instead of its previous one, // since the message does not know what turret point whas used, which is not wanted. // Also ensure the TurretHolder receives the message after we process it. // If it processes it before us we garrison a turret and subsequently // are hidden by GarrisonHolder again. // This could be fixed by not requiring a turret to be 'garrisoned'. let cmpTurretHolder = Engine.QueryInterface(this.entity, IID_TurretHolder); if (cmpTurretHolder) cmpTurretHolder.SwapEntities(msg.entity, msg.newentity); } if (!this.initGarrison) return; // Update the pre-game garrison because of SkirmishReplacement if (msg.entity == this.entity) { let cmpGarrisonHolder = Engine.QueryInterface(msg.newentity, IID_GarrisonHolder); if (cmpGarrisonHolder) cmpGarrisonHolder.initGarrison = this.initGarrison; } else { entityIndex = this.initGarrison.indexOf(msg.entity); if (entityIndex != -1) this.initGarrison[entityIndex] = msg.newentity; } }; /** * Eject all foreign garrisoned entities which are no more allied. */ GarrisonHolder.prototype.OnDiplomacyChanged = function() { this.EjectOrKill(this.entities.filter(ent => !IsOwnedByMutualAllyOfEntity(this.entity, ent))); }; /** * Eject or kill a garrisoned unit which can no more be garrisoned * (garrisonholder's health too small or ownership changed). */ GarrisonHolder.prototype.EjectOrKill = function(entities) { let cmpPosition = Engine.QueryInterface(this.entity, IID_Position); // Eject the units which can be ejected (if not in world, it generally means this holder // is inside a holder which kills its entities, so do not eject) if (cmpPosition && cmpPosition.IsInWorld()) { let ejectables = entities.filter(ent => this.IsEjectable(ent)); if (ejectables.length) this.PerformEject(ejectables, false); } // And destroy all remaining entities let killedEntities = []; for (let entity of entities) { let entityIndex = this.entities.indexOf(entity); if (entityIndex == -1) continue; let cmpHealth = Engine.QueryInterface(entity, IID_Health); if (cmpHealth) cmpHealth.Kill(); this.entities.splice(entityIndex, 1); killedEntities.push(entity); } if (killedEntities.length) { Engine.PostMessage(this.entity, MT_GarrisonedUnitsChanged, { "added": [], "removed": killedEntities }); this.UpdateGarrisonFlag(); } }; /** * Whether an entity is ejectable. * @param {number} entity - The entity-ID to be tested. * @return {boolean} - Whether the entity is ejectable. */ GarrisonHolder.prototype.IsEjectable = function(entity) { if (!this.entities.find(ent => ent == entity)) return false; let ejectableClasses = this.template.EjectClassesOnDestroy._string; let entityClasses = Engine.QueryInterface(entity, IID_Identity).GetClassesList(); return MatchesClassList(entityClasses, ejectableClasses); }; /** * Sets the intitGarrison to the specified entities. Used by the mapreader. * * @param {number[]} entities - The entity IDs to garrison on init. */ GarrisonHolder.prototype.SetInitGarrison = function(entities) { this.initGarrison = clone(entities); }; /** * Initialise the garrisoned units. */ GarrisonHolder.prototype.OnGlobalInitGame = function(msg) { if (!this.initGarrison) return; for (let ent of this.initGarrison) { let cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI); if (cmpUnitAI && cmpUnitAI.CanGarrison(this.entity) && this.Garrison(ent)) cmpUnitAI.Autogarrison(this.entity); } this.initGarrison = undefined; }; GarrisonHolder.prototype.OnValueModification = function(msg) { if (msg.component != "GarrisonHolder" || msg.valueNames.indexOf("GarrisonHolder/BuffHeal") == -1) return; if (this.timer && this.GetHealRate() == 0) { let cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); cmpTimer.CancelTimer(this.timer); this.timer = undefined; } else if (!this.timer && this.GetHealRate() > 0) { let cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); this.timer = cmpTimer.SetTimeout(this.entity, IID_GarrisonHolder, "HealTimeout", 1000, {}); } }; Engine.RegisterComponentType(IID_GarrisonHolder, "GarrisonHolder", GarrisonHolder); Index: ps/trunk/binaries/data/mods/public/simulation/components/Trader.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/Trader.js (revision 24009) +++ ps/trunk/binaries/data/mods/public/simulation/components/Trader.js (revision 24010) @@ -1,311 +1,311 @@ // See helpers/TraderGain.js for the CalculateTaderGain() function which works out how many // resources a trader gets function Trader() {} Trader.prototype.Schema = "Lets the unit generate resouces while moving between markets (or docks in case of water trading)." + "" + "0.75" + "0.2" + "" + "" + "" + "" + "" + "" + "" + "" + ""; Trader.prototype.Init = function() { this.markets = []; this.index = -1; this.goods = { "type": null, "amount": null, "origin": null }; }; Trader.prototype.CalculateGain = function(currentMarket, nextMarket) { let gain = CalculateTraderGain(currentMarket, nextMarket, this.template, this.entity); if (!gain) // One of our markets must have been destroyed return null; // For garrisonable unit increase gain for each garrisoned trader // Calculate this here to save passing unnecessary stuff into the CalculateTraderGain function let garrisonGainMultiplier = this.GetGarrisonGainMultiplier(); if (garrisonGainMultiplier === undefined) return gain; let cmpGarrisonHolder = Engine.QueryInterface(this.entity, IID_GarrisonHolder); if (!cmpGarrisonHolder) return gain; let garrisonMultiplier = 1; let garrisonedTradersCount = 0; for (let entity of cmpGarrisonHolder.GetEntities()) { let cmpGarrisonedUnitTrader = Engine.QueryInterface(entity, IID_Trader); if (cmpGarrisonedUnitTrader) ++garrisonedTradersCount; } garrisonMultiplier *= 1 + garrisonGainMultiplier * garrisonedTradersCount; if (gain.traderGain) gain.traderGain = Math.round(garrisonMultiplier * gain.traderGain); if (gain.market1Gain) gain.market1Gain = Math.round(garrisonMultiplier * gain.market1Gain); if (gain.market2Gain) gain.market2Gain = Math.round(garrisonMultiplier * gain.market2Gain); return gain; }; /** * Remove market from trade route iff only first market is set. * @param {number} id of market to be removed. * @return {boolean} true iff removal was successful. */ Trader.prototype.RemoveTargetMarket = function(target) { if (this.markets.length != 1 || this.markets[0] != target) return false; let cmpTargetMarket = QueryMiragedInterface(target, IID_Market); if (!cmpTargetMarket) return false; cmpTargetMarket.RemoveTrader(this.entity); this.index = -1; this.markets = []; return true; } // Set target as target market. // Return true if at least one of markets was changed. Trader.prototype.SetTargetMarket = function(target, source) { let cmpTargetMarket = QueryMiragedInterface(target, IID_Market); if (!cmpTargetMarket) return false; if (source) { // Establish a trade route with both markets in one go. let cmpSourceMarket = QueryMiragedInterface(source, IID_Market); if (!cmpSourceMarket) return false; this.markets = [source]; } if (this.markets.length >= 2) { // If we already have both markets - drop them // and use the target as first market for (let market of this.markets) { let cmpMarket = QueryMiragedInterface(market, IID_Market); if (cmpMarket) cmpMarket.RemoveTrader(this.entity); } this.index = 0; this.markets = [target]; cmpTargetMarket.AddTrader(this.entity); } else if (this.markets.length == 1) { // If we have only one market and target is different from it, // set the target as second one if (target == this.markets[0]) return false; this.index = 0; this.markets.push(target); cmpTargetMarket.AddTrader(this.entity); this.goods.amount = this.CalculateGain(this.markets[0], this.markets[1]); } else { // Else we don't have target markets at all, // set the target as first market this.index = 0; this.markets = [target]; cmpTargetMarket.AddTrader(this.entity); } // Drop carried goods if markets were changed this.goods.amount = null; return true; }; Trader.prototype.GetFirstMarket = function() { return this.markets[0] || null; }; Trader.prototype.GetSecondMarket = function() { return this.markets[1] || null; }; Trader.prototype.GetTraderGainMultiplier = function() { return ApplyValueModificationsToEntity("Trader/GainMultiplier", +this.template.GainMultiplier, this.entity); }; Trader.prototype.GetGarrisonGainMultiplier = function() { if (this.template.GarrisonGainMultiplier === undefined) return undefined; return ApplyValueModificationsToEntity("Trader/GarrisonGainMultiplier", +this.template.GarrisonGainMultiplier, this.entity); }; Trader.prototype.HasBothMarkets = function() { return this.markets.length >= 2; }; Trader.prototype.CanTrade = function(target) { let cmpTraderIdentity = Engine.QueryInterface(this.entity, IID_Identity); let cmpTargetMarket = QueryMiragedInterface(target, IID_Market); if (!cmpTargetMarket) return false; let cmpTargetFoundation = Engine.QueryInterface(target, IID_Foundation); if (cmpTargetFoundation) return false; if (!(cmpTraderIdentity.HasClass("Organic") && cmpTargetMarket.HasType("land")) && !(cmpTraderIdentity.HasClass("Ship") && cmpTargetMarket.HasType("naval"))) return false; let cmpTraderPlayer = QueryOwnerInterface(this.entity, IID_Player); let cmpTargetPlayer = QueryOwnerInterface(target, IID_Player); return !cmpTraderPlayer.IsEnemy(cmpTargetPlayer.GetPlayerID()); }; Trader.prototype.AddResources = function(ent, gain) { let cmpPlayer = QueryOwnerInterface(ent); if (cmpPlayer) cmpPlayer.AddResource(this.goods.type, gain); let cmpStatisticsTracker = QueryOwnerInterface(ent, IID_StatisticsTracker); if (cmpStatisticsTracker) cmpStatisticsTracker.IncreaseTradeIncomeCounter(gain); }; Trader.prototype.GenerateResources = function(currentMarket, nextMarket) { this.AddResources(this.entity, this.goods.amount.traderGain); if (this.goods.amount.market1Gain) this.AddResources(currentMarket, this.goods.amount.market1Gain); if (this.goods.amount.market2Gain) this.AddResources(nextMarket, this.goods.amount.market2Gain); }; Trader.prototype.PerformTrade = function(currentMarket) { let previousMarket = this.markets[this.index]; if (previousMarket != currentMarket) // Inconsistent markets { this.goods.amount = null; return INVALID_ENTITY; } this.index = ++this.index % this.markets.length; let nextMarket = this.markets[this.index]; if (this.goods.amount && this.goods.amount.traderGain) this.GenerateResources(previousMarket, nextMarket); let cmpPlayer = QueryOwnerInterface(this.entity); if (!cmpPlayer) return INVALID_ENTITY; this.goods.type = cmpPlayer.GetNextTradingGoods(); this.goods.amount = this.CalculateGain(currentMarket, nextMarket); this.goods.origin = currentMarket; return nextMarket; }; Trader.prototype.GetGoods = function() { return this.goods; }; /** * Returns true if the trader has the given market (can be either a market or a mirage) */ Trader.prototype.HasMarket = function(market) { return this.markets.indexOf(market) != -1; }; /** * Remove a market when this trader can no longer trade with it */ Trader.prototype.RemoveMarket = function(market) { let index = this.markets.indexOf(market); if (index == -1) return; this.markets.splice(index, 1); let cmpUnitAI = Engine.QueryInterface(this.entity, IID_UnitAI); if (cmpUnitAI) cmpUnitAI.MarketRemoved(market); }; /** * Switch between a market and its mirage according to visibility */ Trader.prototype.SwitchMarket = function(oldMarket, newMarket) { let index = this.markets.indexOf(oldMarket); if (index == -1) return; this.markets[index] = newMarket; let cmpUnitAI = Engine.QueryInterface(this.entity, IID_UnitAI); if (cmpUnitAI) cmpUnitAI.SwitchMarketOrder(oldMarket, newMarket); }; Trader.prototype.StopTrading = function() { for (let market of this.markets) { let cmpMarket = QueryMiragedInterface(market, IID_Market); if (cmpMarket) cmpMarket.RemoveTrader(this.entity); } this.index = -1; this.markets = []; this.goods.amount = null; this.markets = []; }; // Get range in which deals with market are available, // i.e. trader should be in no more than MaxDistance from market // to be able to trade with it. Trader.prototype.GetRange = function() { let cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); let max = 1; if (cmpObstruction) - max += cmpObstruction.GetUnitRadius()*1.5; + max += cmpObstruction.GetSize() * 1.5; return { "min": 0, "max": max }; }; Trader.prototype.OnGarrisonedUnitsChanged = function() { if (this.HasBothMarkets()) this.goods.amount = this.CalculateGain(this.markets[0], this.markets[1]); }; Engine.RegisterComponentType(IID_Trader, "Trader", Trader); Index: ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Builder.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Builder.js (revision 24009) +++ ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Builder.js (revision 24010) @@ -1,83 +1,83 @@ Engine.LoadHelperScript("Player.js"); Engine.LoadComponentScript("interfaces/Builder.js"); Engine.LoadComponentScript("Builder.js"); const builderId = 6; const playerId = 1; const playerEntityID = 2; AddMock(SYSTEM_ENTITY, IID_TemplateManager, { "TemplateExists": () => true }); Engine.RegisterGlobal("ApplyValueModificationsToEntity", (prop, oVal, ent) => oVal); let cmpBuilder = ConstructComponent(builderId, "Builder", { "Rate": 1.0, "Entities": { "_string": "structures/{civ}_barracks structures/{civ}_civil_centre structures/{native}_house" } }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetEntitiesList(), []); AddMock(SYSTEM_ENTITY, IID_PlayerManager, { "GetPlayerByID": id => playerEntityID }); AddMock(playerEntityID, IID_Player, { "GetCiv": () => "iber", "GetDisabledTemplates": () => ({}), "GetPlayerID": () => playerId }); AddMock(builderId, IID_Ownership, { "GetOwner": () => playerId }); AddMock(builderId, IID_Identity, { "GetCiv": () => "iber" }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetEntitiesList(), ["structures/iber_barracks", "structures/iber_civil_centre", "structures/iber_house"]); AddMock(SYSTEM_ENTITY, IID_TemplateManager, { "TemplateExists": name => name == "structures/iber_civil_centre" }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetEntitiesList(), ["structures/iber_civil_centre"]); AddMock(SYSTEM_ENTITY, IID_TemplateManager, { "TemplateExists": () => true }); AddMock(playerEntityID, IID_Player, { "GetCiv": () => "iber", "GetDisabledTemplates": () => ({ "structures/athen_barracks": true }), "GetPlayerID": () => playerId }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetEntitiesList(), ["structures/iber_barracks", "structures/iber_civil_centre", "structures/iber_house"]); AddMock(playerEntityID, IID_Player, { "GetCiv": () => "iber", "GetDisabledTemplates": () => ({ "structures/iber_barracks": true }), "GetPlayerID": () => playerId }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetEntitiesList(), ["structures/iber_civil_centre", "structures/iber_house"]); AddMock(playerEntityID, IID_Player, { "GetCiv": () => "athen", "GetDisabledTemplates": () => ({ "structures/athen_barracks": true }), "GetPlayerID": () => playerId }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetEntitiesList(), ["structures/athen_civil_centre", "structures/iber_house"]); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetRange(), { "max": 2, "min": 0 }); AddMock(builderId, IID_Obstruction, { - "GetUnitRadius": () => 1.0 + "GetSize": () => 1 }); TS_ASSERT_UNEVAL_EQUALS(cmpBuilder.GetRange(), { "max": 3, "min": 0 }); Index: ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Damage.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Damage.js (revision 24009) +++ ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Damage.js (revision 24010) @@ -1,635 +1,691 @@ Engine.LoadHelperScript("Attacking.js"); Engine.LoadHelperScript("Player.js"); Engine.LoadHelperScript("ValueModification.js"); Engine.LoadComponentScript("interfaces/DelayedDamage.js"); Engine.LoadComponentScript("interfaces/Health.js"); Engine.LoadComponentScript("interfaces/Loot.js"); Engine.LoadComponentScript("interfaces/Promotion.js"); Engine.LoadComponentScript("interfaces/ModifiersManager.js"); Engine.LoadComponentScript("interfaces/Resistance.js"); Engine.LoadComponentScript("interfaces/Timer.js"); Engine.LoadComponentScript("Attack.js"); Engine.LoadComponentScript("DelayedDamage.js"); Engine.LoadComponentScript("Timer.js"); function Test_Generic() { ResetState(); let cmpTimer = ConstructComponent(SYSTEM_ENTITY, "Timer"); cmpTimer.OnUpdate({ "turnLength": 1 }); let attacker = 11; let atkPlayerEntity = 1; let attackerOwner = 6; let cmpAttack = ConstructComponent(attacker, "Attack", { "Ranged": { "Damage": { "Crush": 5, }, "MaxRange": 50, "MinRange": 0, "Delay": 0, "Projectile": { "Speed": 75.0, "Spread": 0.5, "Gravity": 9.81, "FriendlyFire": "false", "LaunchPoint": { "@y": 3 } } } }); let damage = 5; let target = 21; let targetOwner = 7; let targetPos = new Vector3D(3, 0, 3); let type = "Melee"; let damageTaken = false; cmpAttack.GetAttackStrengths = attackType => ({ "Hack": 0, "Pierce": 0, "Crush": damage }); let data = { "type": "Melee", "attackData": { "Damage": { "Hack": 0, "Pierce": 0, "Crush": damage }, }, "target": target, "attacker": attacker, "attackerOwner": attackerOwner, "position": targetPos, "projectileId": 9, "direction": new Vector3D(1, 0, 0) }; AddMock(atkPlayerEntity, IID_Player, { "GetEnemies": () => [targetOwner] }); AddMock(SYSTEM_ENTITY, IID_PlayerManager, { "GetPlayerByID": id => atkPlayerEntity, "GetAllPlayers": () => [0, 1, 2, 3, 4] }); AddMock(SYSTEM_ENTITY, IID_ProjectileManager, { "RemoveProjectile": () => {}, "LaunchProjectileAtPoint": (ent, pos, speed, gravity) => {}, }); AddMock(target, IID_Position, { "GetPosition": () => targetPos, "GetPreviousPosition": () => targetPos, "GetPosition2D": () => Vector2D.From(targetPos), "IsInWorld": () => true, }); AddMock(target, IID_Health, { "TakeDamage": (amount, __, ___) => { damageTaken = true; return { "healthChange": -amount }; }, }); AddMock(SYSTEM_ENTITY, IID_DelayedDamage, { "MissileHit": () => { damageTaken = true; }, }); Engine.PostMessage = function(ent, iid, message) { TS_ASSERT_UNEVAL_EQUALS({ "type": type, "target": target, "attacker": attacker, "attackerOwner": attackerOwner, "damage": damage, "capture": 0, "statusEffects": [], "fromStatusEffect": false }, message); }; AddMock(target, IID_Footprint, { "GetShape": () => ({ "type": "circle", "radius": 20 }), }); AddMock(attacker, IID_Ownership, { "GetOwner": () => attackerOwner, }); AddMock(attacker, IID_Position, { "GetPosition": () => new Vector3D(2, 0, 3), "GetRotation": () => new Vector3D(1, 2, 3), "IsInWorld": () => true, }); function TestDamage() { cmpTimer.OnUpdate({ "turnLength": 1 }); TS_ASSERT(damageTaken); damageTaken = false; } Attacking.HandleAttackEffects(target, data.type, data.attackData, data.attacker, data.attackerOwner); TestDamage(); data.type = "Ranged"; type = data.type; Attacking.HandleAttackEffects(target, data.type, data.attackData, data.attacker, data.attackerOwner); TestDamage(); // Check for damage still being dealt if the attacker dies cmpAttack.PerformAttack("Ranged", target); Engine.DestroyEntity(attacker); TestDamage(); atkPlayerEntity = 1; AddMock(atkPlayerEntity, IID_Player, { "GetEnemies": () => [2, 3] }); TS_ASSERT_UNEVAL_EQUALS(Attacking.GetPlayersToDamage(atkPlayerEntity, true), [0, 1, 2, 3, 4]); TS_ASSERT_UNEVAL_EQUALS(Attacking.GetPlayersToDamage(atkPlayerEntity, false), [2, 3]); } Test_Generic(); function TestLinearSplashDamage() { ResetState(); Engine.PostMessage = (ent, iid, message) => {}; const attacker = 50; const attackerOwner = 1; const origin = new Vector2D(0, 0); let data = { "type": "Ranged", "attackData": { "Damage": { "Hack": 100, "Pierce": 0, "Crush": 0 } }, "attacker": attacker, "attackerOwner": attackerOwner, "origin": origin, "radius": 10, "shape": "Linear", "direction": new Vector3D(1, 747, 0), "friendlyFire": false, }; let fallOff = function(x, y) { return (1 - x * x / (data.radius * data.radius)) * (1 - 25 * y * y / (data.radius * data.radius)); }; let hitEnts = new Set(); AddMock(attackerOwner, IID_Player, { "GetEnemies": () => [2] }); AddMock(SYSTEM_ENTITY, IID_PlayerManager, { "GetPlayerByID": id => attackerOwner, "GetAllPlayers": () => [0, 1, 2] }); AddMock(SYSTEM_ENTITY, IID_RangeManager, { "ExecuteQueryAroundPos": () => [60, 61, 62], }); + AddMock(SYSTEM_ENTITY, IID_ObstructionManager, { + "DistanceToPoint": (ent) => ({ + "60": Math.sqrt(9.25), + "61": 0, + "62": Math.sqrt(29) + }[ent]) + }); + AddMock(60, IID_Position, { - "GetPosition2D": () => new Vector2D(2.2, -0.4), + "GetPosition2D": () => new Vector2D(3, -0.5), }); AddMock(61, IID_Position, { "GetPosition2D": () => new Vector2D(0, 0), }); AddMock(62, IID_Position, { "GetPosition2D": () => new Vector2D(5, 2), }); AddMock(60, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(60); - TS_ASSERT_EQUALS(amount, 100 * fallOff(2.2, -0.4)); + TS_ASSERT_EQUALS(amount, 100 * fallOff(3, -0.5)); return { "healthChange": -amount }; } }); AddMock(61, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(61); TS_ASSERT_EQUALS(amount, 100 * fallOff(0, 0)); return { "healthChange": -amount }; } }); AddMock(62, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(62); - TS_ASSERT_EQUALS(amount, 0); + // Minor numerical precision issues make this necessary + TS_ASSERT(amount < 0.00001); return { "healthChange": -amount }; } }); Attacking.CauseDamageOverArea(data); TS_ASSERT(hitEnts.has(60)); TS_ASSERT(hitEnts.has(61)); TS_ASSERT(hitEnts.has(62)); hitEnts.clear(); data.direction = new Vector3D(0.6, 747, 0.8); AddMock(60, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(60); TS_ASSERT_EQUALS(amount, 100 * fallOff(1, 2)); return { "healthChange": -amount }; } }); Attacking.CauseDamageOverArea(data); TS_ASSERT(hitEnts.has(60)); TS_ASSERT(hitEnts.has(61)); TS_ASSERT(hitEnts.has(62)); hitEnts.clear(); } TestLinearSplashDamage(); function TestCircularSplashDamage() { ResetState(); Engine.PostMessage = (ent, iid, message) => {}; const radius = 10; let attackerOwner = 1; let fallOff = function(r) { return 1 - r * r / (radius * radius); }; AddMock(attackerOwner, IID_Player, { "GetEnemies": () => [2] }); AddMock(SYSTEM_ENTITY, IID_PlayerManager, { "GetPlayerByID": id => attackerOwner, "GetAllPlayers": () => [0, 1, 2] }); AddMock(SYSTEM_ENTITY, IID_RangeManager, { - "ExecuteQueryAroundPos": () => [60, 61, 62, 64], + "ExecuteQueryAroundPos": () => [60, 61, 62, 64, 65], + }); + + AddMock(SYSTEM_ENTITY, IID_ObstructionManager, { + "DistanceToPoint": (ent, x, z) => ({ + "60": 0, + "61": 5, + "62": 1, + "63": Math.sqrt(85), + "64": 10, + "65": 2 + }[ent]) }); AddMock(60, IID_Position, { "GetPosition2D": () => new Vector2D(3, 4), }); AddMock(61, IID_Position, { "GetPosition2D": () => new Vector2D(0, 0), }); AddMock(62, IID_Position, { "GetPosition2D": () => new Vector2D(3.6, 3.2), }); AddMock(63, IID_Position, { "GetPosition2D": () => new Vector2D(10, -10), }); - // Target on the frontier of the shape + // Target on the frontier of the shape (see distance above). AddMock(64, IID_Position, { "GetPosition2D": () => new Vector2D(9, -4), }); + // Big target far away (see distance above). + AddMock(65, IID_Position, { + "GetPosition2D": () => new Vector2D(23, 4), + }); + AddMock(60, IID_Health, { "TakeDamage": (amount, __, ___) => { TS_ASSERT_EQUALS(amount, 100 * fallOff(0)); return { "healthChange": -amount }; } }); AddMock(61, IID_Health, { "TakeDamage": (amount, __, ___) => { TS_ASSERT_EQUALS(amount, 100 * fallOff(5)); return { "healthChange": -amount }; } }); AddMock(62, IID_Health, { "TakeDamage": (amount, __, ___) => { TS_ASSERT_EQUALS(amount, 100 * fallOff(1)); return { "healthChange": -amount }; } }); AddMock(63, IID_Health, { "TakeDamage": (amount, __, ___) => { TS_ASSERT(false); } }); - let cmphealth = AddMock(64, IID_Health, { + let cmphealth64 = AddMock(64, IID_Health, { "TakeDamage": (amount, __, ___) => { TS_ASSERT_EQUALS(amount, 0); return { "healthChange": -amount }; } }); - let spy = new Spy(cmphealth, "TakeDamage"); + let spy64 = new Spy(cmphealth64, "TakeDamage"); + + let cmpHealth65 = AddMock(65, IID_Health, { + "TakeDamage": (amount, __, ___) => { + TS_ASSERT_EQUALS(amount, 100 * fallOff(2)); + return { "healthChange": -amount }; + } + }); + let spy65 = new Spy(cmpHealth65, "TakeDamage"); Attacking.CauseDamageOverArea({ "type": "Ranged", "attackData": { "Damage": { "Hack": 100, "Pierce": 0, "Crush": 0 } }, "attacker": 50, "attackerOwner": attackerOwner, "origin": new Vector2D(3, 4), "radius": radius, "shape": "Circular", "friendlyFire": false, }); - TS_ASSERT_EQUALS(spy._called, 1); + TS_ASSERT_EQUALS(spy64._called, 1); + TS_ASSERT_EQUALS(spy65._called, 1); } TestCircularSplashDamage(); function Test_MissileHit() { ResetState(); Engine.PostMessage = (ent, iid, message) => {}; let cmpDelayedDamage = ConstructComponent(SYSTEM_ENTITY, "DelayedDamage"); let target = 60; let targetOwner = 1; let targetPos = new Vector3D(3, 10, 0); let hitEnts = new Set(); AddMock(SYSTEM_ENTITY, IID_Timer, { "GetLatestTurnLength": () => 500 }); const radius = 10; let data = { "type": "Ranged", "attackData": { "Damage": { "Hack": 0, "Pierce": 100, "Crush": 0 } }, "target": 60, "attacker": 70, "attackerOwner": 1, "position": targetPos, "direction": new Vector3D(1, 0, 0), "projectileId": 9, "friendlyFire": "false", }; AddMock(SYSTEM_ENTITY, IID_PlayerManager, { "GetPlayerByID": id => id == 1 ? 10 : 11, "GetAllPlayers": () => [0, 1] }); AddMock(SYSTEM_ENTITY, IID_ProjectileManager, { "RemoveProjectile": () => {}, "LaunchProjectileAtPoint": (ent, pos, speed, gravity) => {}, }); AddMock(60, IID_Position, { "GetPosition": () => targetPos, "GetPreviousPosition": () => targetPos, "GetPosition2D": () => Vector2D.From(targetPos), "IsInWorld": () => true, }); AddMock(60, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(60); TS_ASSERT_EQUALS(amount, 100); return { "healthChange": -amount }; } }); AddMock(60, IID_Footprint, { "GetShape": () => ({ "type": "circle", "radius": 20 }), }); AddMock(70, IID_Ownership, { "GetOwner": () => 1, }); AddMock(70, IID_Position, { "GetPosition": () => new Vector3D(0, 0, 0), "GetRotation": () => new Vector3D(0, 0, 0), "IsInWorld": () => true, }); AddMock(10, IID_Player, { "GetEnemies": () => [2] }); cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(60)); hitEnts.clear(); // Target is a mirage: hit the parent. AddMock(60, IID_Mirage, { "GetParent": () => 61 }); + AddMock(SYSTEM_ENTITY, IID_ObstructionManager, { + "DistanceToPoint": (ent) => 0 + }); + AddMock(61, IID_Position, { "GetPosition": () => targetPos, "GetPreviousPosition": () => targetPos, "GetPosition2D": () => Vector2D.from3D(targetPos), "IsInWorld": () => true }); AddMock(61, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(61); TS_ASSERT_EQUALS(amount, 100); return { "healthChange": -amount }; } }); AddMock(61, IID_Footprint, { "GetShape": () => ({ "type": "circle", "radius": 20 }) }); cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); hitEnts.clear(); // Make sure we don't corrupt other tests. DeleteMock(60, IID_Mirage); cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(60)); hitEnts.clear(); // The main target is not hit but another one is hit. AddMock(60, IID_Position, { "GetPosition": () => new Vector3D(900, 10, 0), "GetPreviousPosition": () => new Vector3D(900, 10, 0), "GetPosition2D": () => new Vector2D(900, 0), "IsInWorld": () => true }); AddMock(60, IID_Health, { "TakeDamage": (amount, __, ___) => { TS_ASSERT_EQUALS(false); return { "healthChange": -amount }; } }); AddMock(SYSTEM_ENTITY, IID_RangeManager, { "ExecuteQueryAroundPos": () => [61] }); cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); hitEnts.clear(); // Add a splash damage. data.splash = {}; data.splash.friendlyFire = false; data.splash.radius = 10; data.splash.shape = "Circular"; data.splash.attackData = { "Damage": { "Hack": 0, "Pierce": 0, "Crush": 200 } }; AddMock(SYSTEM_ENTITY, IID_RangeManager, { "ExecuteQueryAroundPos": () => [61, 62] }); + AddMock(SYSTEM_ENTITY, IID_ObstructionManager, { + "DistanceToPoint": (ent) => ({ + "61": 0, + "62": 5 + }[ent]) + }); + let dealtDamage = 0; AddMock(61, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(61); dealtDamage += amount; return { "healthChange": -amount }; } }); AddMock(62, IID_Position, { "GetPosition": () => new Vector3D(8, 10, 0), "GetPreviousPosition": () => new Vector3D(8, 10, 0), "GetPosition2D": () => new Vector2D(8, 0), "IsInWorld": () => true, }); AddMock(62, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(62); TS_ASSERT_EQUALS(amount, 200 * 0.75); return { "healthChange": -amount }; } }); AddMock(62, IID_Footprint, { "GetShape": () => ({ "type": "circle", "radius": 20 }), }); cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 100 + 200); dealtDamage = 0; TS_ASSERT(hitEnts.has(62)); hitEnts.clear(); // Add some hard counters bonus. Engine.DestroyEntity(62); AddMock(SYSTEM_ENTITY, IID_RangeManager, { "ExecuteQueryAroundPos": () => [61] }); + AddMock(SYSTEM_ENTITY, IID_ObstructionManager, { + "DistanceToPoint": (ent) => 0 + }); + let bonus= { "BonusCav": { "Classes": "Cavalry", "Multiplier": 400 } }; let splashBonus = { "BonusCav": { "Classes": "Cavalry", "Multiplier": 10000 } }; AddMock(61, IID_Identity, { "GetClassesList": () => ["Cavalry"], "GetCiv": () => "civ" }); data.attackData.Bonuses = bonus; cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 400 * 100 + 200); dealtDamage = 0; hitEnts.clear(); data.splash.attackData.Bonuses = splashBonus; cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 400 * 100 + 10000 * 200); dealtDamage = 0; hitEnts.clear(); data.attackData.Bonuses = undefined; cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 100 + 10000 * 200); dealtDamage = 0; hitEnts.clear(); data.attackData.Bonuses = null; cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 100 + 10000 * 200); dealtDamage = 0; hitEnts.clear(); data.attackData.Bonuses = {}; cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 100 + 10000 * 200); dealtDamage = 0; hitEnts.clear(); // Test splash damage with friendly fire. data.splash = {}; data.splash.friendlyFire = true; data.splash.radius = 10; data.splash.shape = "Circular"; data.splash.attackData = { "Damage": { "Pierce": 0, "Crush": 200 } }; AddMock(SYSTEM_ENTITY, IID_RangeManager, { "ExecuteQueryAroundPos": () => [61, 62] }); + AddMock(SYSTEM_ENTITY, IID_ObstructionManager, { + "DistanceToPoint": (ent) => ({ + "61": 0, + "62": 5 + }[ent]) + }); + dealtDamage = 0; AddMock(61, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(61); dealtDamage += amount; return { "healthChange": -amount }; } }); AddMock(62, IID_Position, { "GetPosition": () => new Vector3D(8, 10, 0), "GetPreviousPosition": () => new Vector3D(8, 10, 0), "GetPosition2D": () => new Vector2D(8, 0), "IsInWorld": () => true, }); AddMock(62, IID_Health, { "TakeDamage": (amount, __, ___) => { hitEnts.add(62); TS_ASSERT_EQUALS(amount, 200 * 0.75); return { "healtChange": -amount }; } }); AddMock(62, IID_Footprint, { "GetShape": () => ({ "type": "circle", "radius": 20 }), }); cmpDelayedDamage.MissileHit(data, 0); TS_ASSERT(hitEnts.has(61)); TS_ASSERT_EQUALS(dealtDamage, 100 + 200); dealtDamage = 0; TS_ASSERT(hitEnts.has(62)); hitEnts.clear(); } Test_MissileHit(); Index: ps/trunk/binaries/data/mods/public/simulation/helpers/Attacking.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/helpers/Attacking.js (revision 24009) +++ ps/trunk/binaries/data/mods/public/simulation/helpers/Attacking.js (revision 24010) @@ -1,440 +1,449 @@ /** * Provides attack and damage-related helpers under the Attacking umbrella (to avoid name ambiguity with the component). */ function Attacking() {} const DirectEffectsSchema = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; const StatusEffectsSchema = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + DirectEffectsSchema + "" + "" + "" + "" + "" + ModificationsSchema + "" + "" + "" + "Ignore" + "Extend" + "Replace" + "Stack" + "" + "" + "" + "" + "" + ""; /** * Builds a RelaxRNG schema of possible attack effects. * See globalscripts/AttackEffects.js for possible elements. * Attacks may also have a "Bonuses" element. * * @return {string} - RelaxNG schema string. */ Attacking.prototype.BuildAttackEffectsSchema = function() { return "" + "" + "" + DirectEffectsSchema + StatusEffectsSchema + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; }; /** * Returns a template-like object of attack effects. */ Attacking.prototype.GetAttackEffectsData = function(valueModifRoot, template, entity) { let ret = {}; if (template.Damage) { ret.Damage = {}; let applyMods = damageType => ApplyValueModificationsToEntity(valueModifRoot + "/Damage/" + damageType, +(template.Damage[damageType] || 0), entity); for (let damageType in template.Damage) ret.Damage[damageType] = applyMods(damageType); } if (template.Capture) ret.Capture = ApplyValueModificationsToEntity(valueModifRoot + "/Capture", +(template.Capture || 0), entity); if (template.ApplyStatus) ret.ApplyStatus = this.GetStatusEffectsData(valueModifRoot, template.ApplyStatus, entity); if (template.Bonuses) ret.Bonuses = template.Bonuses; return ret; }; Attacking.prototype.GetStatusEffectsData = function(valueModifRoot, template, entity) { let result = {}; for (let effect in template) { let statusTemplate = template[effect]; result[effect] = { "StatusName": statusTemplate.StatusName, "ApplierTooltip": statusTemplate.ApplierTooltip, "ReceiverTooltip": statusTemplate.ReceiverTooltip, "Duration": ApplyValueModificationsToEntity(valueModifRoot + "/ApplyStatus/" + effect + "/Duration", +(statusTemplate.Duration || 0), entity), "Interval": ApplyValueModificationsToEntity(valueModifRoot + "/ApplyStatus/" + effect + "/Interval", +(statusTemplate.Interval || 0), entity), "Stackability": statusTemplate.Stackability }; Object.assign(result[effect], this.GetAttackEffectsData(valueModifRoot + "/ApplyStatus" + effect, statusTemplate, entity)); if (statusTemplate.Modifiers) result[effect].Modifiers = this.GetStatusEffectsModifications(valueModifRoot, statusTemplate.Modifiers, entity, effect); } return result; }; Attacking.prototype.GetStatusEffectsModifications = function(valueModifRoot, template, entity, effect) { let modifiers = {}; for (let modifier in template) { let modifierTemplate = template[modifier]; modifiers[modifier] = { "Paths": modifierTemplate.Paths, "Affects": modifierTemplate.Affects }; if (modifierTemplate.Add !== undefined) modifiers[modifier].Add = ApplyValueModificationsToEntity(valueModifRoot + "/ApplyStatus/" + effect + "/Modifiers/" + modifier + "/Add", +modifierTemplate.Add, entity); if (modifierTemplate.Multiply !== undefined) modifiers[modifier].Multiply = ApplyValueModificationsToEntity(valueModifRoot + "/ApplyStatus/" + effect + "/Modifiers/" + modifier + "/Multiply", +modifierTemplate.Multiply, entity); if (modifierTemplate.Replace !== undefined) modifiers[modifier].Replace = modifierTemplate.Replace; } return modifiers; }; /** * Calculate the total effect taking bonus and resistance into account. * * @param {number} target - The target of the attack. * @param {Object} effectData - The effects calculate the effect for. * @param {string} effectType - The type of effect to apply (e.g. Damage, Capture or ApplyStatus). * @param {number} bonusMultiplier - The factor to multiply the total effect with. * @param {Object} cmpResistance - Optionally the resistance component of the target. * * @return {number} - The total value of the effect. */ Attacking.prototype.GetTotalAttackEffects = function(target, effectData, effectType, bonusMultiplier, cmpResistance) { let total = 0; if (!cmpResistance) cmpResistance = Engine.QueryInterface(target, IID_Resistance); let resistanceStrengths = cmpResistance ? cmpResistance.GetEffectiveResistanceAgainst(effectType) : {}; if (effectType == "Damage") for (let type in effectData.Damage) total += effectData.Damage[type] * Math.pow(0.9, resistanceStrengths.Damage ? resistanceStrengths.Damage[type] || 0 : 0); else if (effectType == "Capture") { total = effectData.Capture * Math.pow(0.9, resistanceStrengths.Capture || 0); // If Health is lower we are more susceptible to capture attacks. let cmpHealth = Engine.QueryInterface(target, IID_Health); if (cmpHealth) total /= 0.1 + 0.9 * cmpHealth.GetHitpoints() / cmpHealth.GetMaxHitpoints(); } else if (effectType == "ApplyStatus") return effectData[effectType]; return total * bonusMultiplier; }; /** * Gives the position of the given entity, taking the lateness into account. * @param {number} ent - Entity id of the entity we are finding the location for. * @param {number} lateness - The time passed since the expected time to fire the function. * @return {Vector3D} The location of the entity. */ Attacking.prototype.InterpolatedLocation = function(ent, lateness) { let cmpTargetPosition = Engine.QueryInterface(ent, IID_Position); if (!cmpTargetPosition || !cmpTargetPosition.IsInWorld()) // TODO: handle dead target properly return undefined; let curPos = cmpTargetPosition.GetPosition(); let prevPos = cmpTargetPosition.GetPreviousPosition(); let cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); let turnLength = cmpTimer.GetLatestTurnLength(); return new Vector3D( (curPos.x * (turnLength - lateness) + prevPos.x * lateness) / turnLength, 0, (curPos.z * (turnLength - lateness) + prevPos.z * lateness) / turnLength ); }; /** * Test if a point is inside of an entity's footprint. * @param {number} ent - Id of the entity we are checking with. * @param {Vector3D} point - The point we are checking with. * @param {number} lateness - The time passed since the expected time to fire the function. * @return {boolean} True if the point is inside of the entity's footprint. */ Attacking.prototype.TestCollision = function(ent, point, lateness) { let targetPosition = this.InterpolatedLocation(ent, lateness); if (!targetPosition) return false; let cmpFootprint = Engine.QueryInterface(ent, IID_Footprint); if (!cmpFootprint) return false; let targetShape = cmpFootprint.GetShape(); if (!targetShape) return false; if (targetShape.type == "circle") return targetPosition.horizDistanceToSquared(point) < targetShape.radius * targetShape.radius; if (targetShape.type == "square") { let angle = Engine.QueryInterface(ent, IID_Position).GetRotation().y; let distance = Vector2D.from3D(Vector3D.sub(point, targetPosition)).rotate(-angle); return Math.abs(distance.x) < targetShape.width / 2 && Math.abs(distance.y) < targetShape.depth / 2; } warn("TestCollision called with an invalid footprint shape"); return false; }; /** * Get the list of players affected by the damage. * @param {number} attackerOwner - The player id of the attacker. * @param {boolean} friendlyFire - A flag indicating if allied entities are also damaged. * @return {number[]} The ids of players need to be damaged. */ Attacking.prototype.GetPlayersToDamage = function(attackerOwner, friendlyFire) { if (!friendlyFire) return QueryPlayerIDInterface(attackerOwner).GetEnemies(); return Engine.QueryInterface(SYSTEM_ENTITY, IID_PlayerManager).GetAllPlayers(); }; /** * Damages units around a given origin. * @param {Object} data - The data sent by the caller. * @param {string} data.type - The type of damage. * @param {Object} data.attackData - The attack data. * @param {number} data.attacker - The entity id of the attacker. * @param {number} data.attackerOwner - The player id of the attacker. * @param {Vector2D} data.origin - The origin of the projectile hit. * @param {number} data.radius - The radius of the splash damage. * @param {string} data.shape - The shape of the radius. * @param {Vector3D} [data.direction] - The unit vector defining the direction. Needed for linear splash damage. * @param {boolean} data.friendlyFire - A flag indicating if allied entities also ought to be damaged. */ Attacking.prototype.CauseDamageOverArea = function(data) { let nearEnts = this.EntitiesNearPoint(data.origin, data.radius, this.GetPlayersToDamage(data.attackerOwner, data.friendlyFire)); let damageMultiplier = 1; + let cmpObstructionManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_ObstructionManager); + // Cycle through all the nearby entities and damage it appropriately based on its distance from the origin. for (let ent of nearEnts) { - let entityPosition = Engine.QueryInterface(ent, IID_Position).GetPosition2D(); + // Correct somewhat for the entity's obstruction radius. + // TODO: linear falloff should arguably use something cleverer. + let distance = cmpObstructionManager.DistanceToPoint(ent, data.origin.x, data.origin.y); + if (data.shape == 'Circular') // circular effect with quadratic falloff in every direction - damageMultiplier = 1 - data.origin.distanceToSquared(entityPosition) / (data.radius * data.radius); + damageMultiplier = 1 - distance * distance / (data.radius * data.radius); else if (data.shape == 'Linear') // linear effect with quadratic falloff in two directions (only used for certain missiles) { - // Get position of entity relative to splash origin. - let relativePos = entityPosition.sub(data.origin); + // The entity has a position here since it was returned by the range manager. + let entityPosition = Engine.QueryInterface(ent, IID_Position).GetPosition2D(); + let relativePos = entityPosition.sub(data.origin).normalize().mult(distance); // Get the position relative to the missile direction. let direction = Vector2D.from3D(data.direction); let parallelPos = relativePos.dot(direction); let perpPos = relativePos.cross(direction); // The width of linear splash is one fifth of the normal splash radius. let width = data.radius / 5; // Check that the unit is within the distance splash width of the line starting at the missile's // landing point which extends in the direction of the missile for length splash radius. if (parallelPos >= 0 && Math.abs(perpPos) < width) // If in radius, quadratic falloff in both directions damageMultiplier = (1 - parallelPos * parallelPos / (data.radius * data.radius)) * (1 - perpPos * perpPos / (width * width)); else damageMultiplier = 0; } else // In case someone calls this function with an invalid shape. { warn("The " + data.shape + " splash damage shape is not implemented!"); } + // The RangeManager can return units that are too far away (due to approximations there) + // so the multiplier can end up below 0. + damageMultiplier = Math.max(0, damageMultiplier); this.HandleAttackEffects(ent, data.type + ".Splash", data.attackData, data.attacker, data.attackerOwner, damageMultiplier); } }; /** * Handle an attack peformed on an entity. * * @param {number} target - The targetted entityID. * @param {string} attackType - The type of attack that was performed (e.g. "Melee" or "Capture"). * @param {Object} effectData - The effects use. * @param {number} attacker - The entityID that attacked us. * @param {number} attackerOwner - The playerID that owned the attacker when the attack was performed. * @param {number} bonusMultiplier - The factor to multiply the total effect with, defaults to 1. * * @return {boolean} - Whether we handled the attack. */ Attacking.prototype.HandleAttackEffects = function(target, attackType, attackData, attacker, attackerOwner, bonusMultiplier = 1) { let cmpResistance = Engine.QueryInterface(target, IID_Resistance); if (cmpResistance && cmpResistance.IsInvulnerable()) return false; bonusMultiplier *= !attackData.Bonuses ? 1 : this.GetAttackBonus(attacker, target, attackType, attackData.Bonuses); let targetState = {}; for (let effectType of g_EffectTypes) { if (!attackData[effectType]) continue; let receiver = g_EffectReceiver[effectType]; let cmpReceiver = Engine.QueryInterface(target, global[receiver.IID]); if (!cmpReceiver) continue; Object.assign(targetState, cmpReceiver[receiver.method](this.GetTotalAttackEffects(target, attackData, effectType, bonusMultiplier, cmpResistance), attacker, attackerOwner)); } if (!Object.keys(targetState).length) return false; Engine.PostMessage(target, MT_Attacked, { "type": attackType, "target": target, "attacker": attacker, "attackerOwner": attackerOwner, "damage": -(targetState.healthChange || 0), "capture": targetState.captureChange || 0, "statusEffects": targetState.inflictedStatuses || [], "fromStatusEffect": !!attackData.StatusEffect, }); // We do not want an entity to get XP from active Status Effects. if (!!attackData.StatusEffect) return true; let cmpPromotion = Engine.QueryInterface(attacker, IID_Promotion); if (cmpPromotion && targetState.xp) cmpPromotion.IncreaseXp(targetState.xp); return true; }; /** * Gets entities near a give point for given players. * @param {Vector2D} origin - The point to check around. * @param {number} radius - The radius around the point to check. * @param {number[]} players - The players of which we need to check entities. * @param {number} itf - Interface IID that returned entities must implement. Defaults to none. * @return {number[]} The id's of the entities in range of the given point. */ Attacking.prototype.EntitiesNearPoint = function(origin, radius, players, itf = 0) { // If there is insufficient data return an empty array. if (!origin || !radius || !players || !players.length) return []; let cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); return cmpRangeManager.ExecuteQueryAroundPos(origin, 0, radius, players, itf); }; /** * Calculates the attack damage multiplier against a target. * @param {number} source - The source entity's id. * @param {number} target - The target entity's id. * @param {string} type - The type of attack. * @param {Object} template - The bonus' template. * @return {number} - The source entity's attack bonus against the specified target. */ Attacking.prototype.GetAttackBonus = function(source, target, type, template) { let cmpIdentity = Engine.QueryInterface(target, IID_Identity); if (!cmpIdentity) return 1; let attackBonus = 1; let targetClasses = cmpIdentity.GetClassesList(); let targetCiv = cmpIdentity.GetCiv(); // Multiply the bonuses for all matching classes. for (let key in template) { let bonus = template[key]; if (bonus.Civ && bonus.Civ !== targetCiv) continue; if (!bonus.Classes || MatchesClassList(targetClasses, bonus.Classes)) attackBonus *= ApplyValueModificationsToEntity("Attack/" + type + "/Bonuses/" + key + "/Multiplier", +bonus.Multiplier, source); } return attackBonus; }; var AttackingInstance = new Attacking(); Engine.RegisterGlobal("Attacking", AttackingInstance); Index: ps/trunk/source/simulation2/components/CCmpFootprint.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpFootprint.cpp (revision 24009) +++ ps/trunk/source/simulation2/components/CCmpFootprint.cpp (revision 24010) @@ -1,410 +1,410 @@ /* Copyright (C) 2020 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "simulation2/system/Component.h" #include "ICmpFootprint.h" #include "ps/Profile.h" #include "simulation2/components/ICmpObstruction.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpPathfinder.h" #include "simulation2/components/ICmpPosition.h" #include "simulation2/components/ICmpRallyPoint.h" #include "simulation2/components/ICmpUnitMotion.h" #include "simulation2/helpers/Geometry.h" #include "simulation2/MessageTypes.h" #include "maths/FixedVector2D.h" class CCmpFootprint : public ICmpFootprint { public: static void ClassInit(CComponentManager& UNUSED(componentManager)) { } DEFAULT_COMPONENT_ALLOCATOR(Footprint) EShape m_Shape; entity_pos_t m_Size0; // width/radius entity_pos_t m_Size1; // height/radius entity_pos_t m_Height; entity_pos_t m_MaxSpawnDistance; static std::string GetSchema() { return "Approximation of the entity's shape, for collision detection and may be used for outline rendering or to determine selectable bounding box. " "Shapes are flat horizontal squares or circles, extended vertically to a given height." "" "" "0.0" "8" "" "" "" "0.0" "8" "" "" "" "" "" "0.0" "" "" "" "" "0.0" "" "" "" "" "" "" "0.0" "" "" "" "" "" "" "" "" "" "" "" ""; } virtual void Init(const CParamNode& paramNode) { if (paramNode.GetChild("Square").IsOk()) { m_Shape = SQUARE; m_Size0 = paramNode.GetChild("Square").GetChild("@width").ToFixed(); m_Size1 = paramNode.GetChild("Square").GetChild("@depth").ToFixed(); } else if (paramNode.GetChild("Circle").IsOk()) { m_Shape = CIRCLE; m_Size0 = m_Size1 = paramNode.GetChild("Circle").GetChild("@radius").ToFixed(); } else { // Error - pick some default m_Shape = CIRCLE; m_Size0 = m_Size1 = entity_pos_t::FromInt(1); } m_Height = paramNode.GetChild("Height").ToFixed(); if (paramNode.GetChild("MaxSpawnDistance").IsOk()) m_MaxSpawnDistance = paramNode.GetChild("MaxSpawnDistance").ToFixed(); else // Pick some default m_MaxSpawnDistance = entity_pos_t::FromInt(7); } virtual void Deinit() { } virtual void Serialize(ISerializer& UNUSED(serialize)) { // No dynamic state to serialize } virtual void Deserialize(const CParamNode& paramNode, IDeserializer& UNUSED(deserialize)) { Init(paramNode); } virtual void GetShape(EShape& shape, entity_pos_t& size0, entity_pos_t& size1, entity_pos_t& height) const { shape = m_Shape; size0 = m_Size0; size1 = m_Size1; height = m_Height; } virtual CFixedVector3D PickSpawnPoint(entity_id_t spawned) const { PROFILE3("PickSpawnPoint"); // Try to find a free space around the building's footprint. // (Note that we use the footprint, not the obstruction shape - this might be a bit dodgy // because the footprint might be inside the obstruction, but it hopefully gives us a nicer // shape.) const CFixedVector3D error(fixed::FromInt(-1), fixed::FromInt(-1), fixed::FromInt(-1)); CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return error; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return error; // If no spawned obstruction, use a positive radius to avoid division by zero errors. entity_pos_t spawnedRadius = fixed::FromInt(1); ICmpObstructionManager::tag_t spawnedTag; CmpPtr cmpSpawnedObstruction(GetSimContext(), spawned); if (cmpSpawnedObstruction) { - spawnedRadius = cmpSpawnedObstruction->GetUnitRadius(); + spawnedRadius = cmpSpawnedObstruction->GetSize(); spawnedTag = cmpSpawnedObstruction->GetObstruction(); } // Get passability class from UnitMotion. CmpPtr cmpUnitMotion(GetSimContext(), spawned); if (!cmpUnitMotion) return error; pass_class_t spawnedPass = cmpUnitMotion->GetPassabilityClass(); CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return error; // Ignore collisions with the spawned entity and entities that don't block movement. SkipTagRequireFlagsObstructionFilter filter(spawnedTag, ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); CFixedVector2D initialPos = cmpPosition->GetPosition2D(); entity_angle_t initialAngle = cmpPosition->GetRotation().Y; CFixedVector2D u = CFixedVector2D(fixed::Zero(), fixed::FromInt(1)).Rotate(initialAngle); CFixedVector2D v = u.Perpendicular(); // Obstructions are squares, so multiply its radius by 2*sqrt(2) ~= 3 to determine the distance between units. entity_pos_t gap = spawnedRadius * 3; int rows = std::max(1, (m_MaxSpawnDistance / gap).ToInt_RoundToInfinity()); // The first row of units will be half a gap away from the footprint. CFixedVector2D halfSize = m_Shape == CIRCLE ? CFixedVector2D(m_Size1 + gap / 2, m_Size0 + gap / 2) : CFixedVector2D((m_Size1 + gap) / 2, (m_Size0 + gap) / 2); // Figure out how many units can fit on each halfside of the rectangle. // Since 2*pi/6 ~= 1, this is also how many units can fit on a sixth of the circle. int distX = std::max(1, (halfSize.X / gap).ToInt_RoundToNegInfinity()); int distY = std::max(1, (halfSize.Y / gap).ToInt_RoundToNegInfinity()); // Try more spawning points for large units in case some of them are partially blocked. if (rows == 1) { distX *= 2; distY *= 2; } // Store the position of the spawning point within each row that's closest to the spawning angle. std::vector offsetPoints(rows, 0); CmpPtr cmpRallyPoint(GetEntityHandle()); if (cmpRallyPoint && cmpRallyPoint->HasPositions()) { CFixedVector2D rallyPointPos = cmpRallyPoint->GetFirstPosition(); if (m_Shape == CIRCLE) { entity_angle_t offsetAngle = atan2_approx(rallyPointPos.X - initialPos.X, rallyPointPos.Y - initialPos.Y) - initialAngle; // There are 6*(distX+r) points in row r, so multiply that by angle/2pi to find the offset within the row. for (int r = 0; r < rows; ++r) offsetPoints[r] = (offsetAngle * 3 * (distX + r) / fixed::Pi()).ToInt_RoundToNearest(); } else { CFixedVector2D offsetPos = Geometry::NearestPointOnSquare(rallyPointPos - initialPos, u, v, halfSize); // Scale and convert the perimeter coordinates of the point to its offset within the row. int x = (offsetPos.Dot(u) * distX / halfSize.X).ToInt_RoundToNearest(); int y = (offsetPos.Dot(v) * distY / halfSize.Y).ToInt_RoundToNearest(); for (int r = 0; r < rows; ++r) offsetPoints[r] = Geometry::GetPerimeterDistance( distX + r, distY + r, x >= distX ? distX + r : x <= -distX ? -distX - r : x, y >= distY ? distY + r : y <= -distY ? -distY - r : y); } } for (int k = 0; k < 2 * (distX + distY + 2 * rows); k = k > 0 ? -k : 1 - k) for (int r = 0; r < rows; ++r) { CFixedVector2D pos = initialPos; if (m_Shape == CIRCLE) // Multiply the point by 2pi / 6*(distX+r) to get the angle. pos += u.Rotate(fixed::Pi() * (offsetPoints[r] + k) / (3 * (distX + r))).Multiply(halfSize.X + gap * r ); else { // Convert the point to coordinates and scale. std::pair p = Geometry::GetPerimeterCoordinates(distX + r, distY + r, offsetPoints[r] + k); pos += u.Multiply((halfSize.X + gap * r) * p.first / (distX + r)) + v.Multiply((halfSize.Y + gap * r) * p.second / (distY + r)); } if (cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, spawnedRadius, spawnedPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS) return CFixedVector3D(pos.X, fixed::Zero(), pos.Y); } return error; } virtual CFixedVector3D PickSpawnPointBothPass(entity_id_t spawned) const { PROFILE3("PickSpawnPointBothPass"); // Try to find a free space inside and around this footprint // at the intersection between the footprint passability and the unit passability. // (useful for example for destroyed ships where the spawning point should be in the intersection // of the unit and ship passabilities). // As the overlap between these passabilities regions may be narrow, we need a small step (1 meter) const CFixedVector3D error(fixed::FromInt(-1), fixed::FromInt(-1), fixed::FromInt(-1)); CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition || !cmpPosition->IsInWorld()) return error; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return error; entity_pos_t spawnedRadius; ICmpObstructionManager::tag_t spawnedTag; CmpPtr cmpSpawnedObstruction(GetSimContext(), spawned); if (cmpSpawnedObstruction) { - spawnedRadius = cmpSpawnedObstruction->GetUnitRadius(); + spawnedRadius = cmpSpawnedObstruction->GetSize(); spawnedTag = cmpSpawnedObstruction->GetObstruction(); } // else use zero radius // Get passability class from UnitMotion CmpPtr cmpUnitMotion(GetSimContext(), spawned); if (!cmpUnitMotion) return error; pass_class_t spawnedPass = cmpUnitMotion->GetPassabilityClass(); CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return error; // Get the Footprint entity passability CmpPtr cmpEntityMotion(GetEntityHandle()); if (!cmpEntityMotion) return error; pass_class_t entityPass = cmpEntityMotion->GetPassabilityClass(); CFixedVector2D initialPos = cmpPosition->GetPosition2D(); entity_angle_t initialAngle = cmpPosition->GetRotation().Y; // Max spawning distance + 1 (in meters) const i32 maxSpawningDistance = 13; if (m_Shape == CIRCLE) { // Expand outwards from foundation with a fixed step of 1 meter for (i32 dist = 0; dist <= maxSpawningDistance; ++dist) { // The spawn point should be far enough from this footprint to fit the unit, plus a little gap entity_pos_t clearance = spawnedRadius + entity_pos_t::FromInt(1+dist); entity_pos_t radius = m_Size0 + clearance; // Try equally-spaced points around the circle in alternating directions, starting from the front const i32 numPoints = 31 + 2*dist; for (i32 i = 0; i < (numPoints+1)/2; i = (i > 0 ? -i : 1-i)) // [0, +1, -1, +2, -2, ... (np-1)/2, -(np-1)/2] { entity_angle_t angle = initialAngle + (entity_angle_t::Pi()*2).Multiply(entity_angle_t::FromInt(i)/(int)numPoints); fixed s, c; sincos_approx(angle, s, c); CFixedVector3D pos (initialPos.X + s.Multiply(radius), fixed::Zero(), initialPos.Y + c.Multiply(radius)); SkipTagObstructionFilter filter(spawnedTag); // ignore collisions with the spawned entity if (cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Z, spawnedRadius, spawnedPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS && cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Z, spawnedRadius, entityPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS) return pos; // this position is okay, so return it } } } else { fixed s, c; sincos_approx(initialAngle, s, c); // Expand outwards from foundation with a fixed step of 1 meter for (i32 dist = 0; dist <= maxSpawningDistance; ++dist) { // The spawn point should be far enough from this footprint to fit the unit, plus a little gap entity_pos_t clearance = spawnedRadius + entity_pos_t::FromInt(1+dist); for (i32 edge = 0; edge < 4; ++edge) { // Compute the direction and length of the current edge CFixedVector2D dir; fixed sx, sy; switch (edge) { case 0: dir = CFixedVector2D(c, -s); sx = m_Size0; sy = m_Size1; break; case 1: dir = CFixedVector2D(-s, -c); sx = m_Size1; sy = m_Size0; break; case 2: dir = CFixedVector2D(s, c); sx = m_Size1; sy = m_Size0; break; case 3: dir = CFixedVector2D(-c, s); sx = m_Size0; sy = m_Size1; break; } sx = sx/2 + clearance; sy = sy/2 + clearance; // Try equally-spaced (1 meter) points along the edge in alternating directions, starting from the middle i32 numPoints = 1 + 2*sx.ToInt_RoundToNearest(); CFixedVector2D center = initialPos - dir.Perpendicular().Multiply(sy); for (i32 i = 0; i < (numPoints+1)/2; i = (i > 0 ? -i : 1-i)) // [0, +1, -1, +2, -2, ... (np-1)/2, -(np-1)/2] { CFixedVector2D pos (center + dir*i); SkipTagObstructionFilter filter(spawnedTag); // ignore collisions with the spawned entity if (cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, spawnedRadius, spawnedPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS && cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, spawnedRadius, entityPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS) return CFixedVector3D(pos.X, fixed::Zero(), pos.Y); // this position is okay, so return it } } } } return error; } }; REGISTER_COMPONENT_TYPE(Footprint) Index: ps/trunk/source/simulation2/components/CCmpObstruction.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 24009) +++ ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 24010) @@ -1,847 +1,839 @@ /* Copyright (C) 2020 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "simulation2/system/Component.h" #include "ICmpObstruction.h" #include "ps/CLogger.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpTerrain.h" #include "simulation2/components/ICmpUnitMotion.h" #include "simulation2/components/ICmpWaterManager.h" #include "simulation2/serialization/SerializeTemplates.h" /** * Obstruction implementation. This keeps the ICmpPathfinder's model of the world updated when the * entities move and die, with shapes derived from ICmpFootprint. */ class CCmpObstruction : public ICmpObstruction { public: static void ClassInit(CComponentManager& componentManager) { componentManager.SubscribeToMessageType(MT_PositionChanged); componentManager.SubscribeToMessageType(MT_Destroy); } DEFAULT_COMPONENT_ALLOCATOR(Obstruction) typedef ICmpObstructionManager::tag_t tag_t; typedef ICmpObstructionManager::flags_t flags_t; // Template state: EObstructionType m_Type; entity_pos_t m_Size0; // radius or width entity_pos_t m_Size1; // radius or depth flags_t m_TemplateFlags; entity_pos_t m_Clearance; typedef struct { entity_pos_t dx, dz; entity_angle_t da; entity_pos_t size0, size1; flags_t flags; } Shape; std::vector m_Shapes; // Dynamic state: /// Whether the obstruction is actively obstructing or just an inactive placeholder. bool m_Active; /// Whether the entity associated with this obstruction is currently moving. Only applicable for /// UNIT-type obstructions. bool m_Moving; /// Whether an obstruction's control group should be kept consistent and /// used to set control groups for entities that collide with it. bool m_ControlPersist; /** * Primary control group identifier. Indicates to which control group this entity's shape belongs. * Typically used in combination with obstruction test filters to have member shapes ignore each * other during obstruction tests. Defaults to the entity's ID. Must never be set to INVALID_ENTITY. */ entity_id_t m_ControlGroup; /** * Optional secondary control group identifier. Similar to m_ControlGroup; if set to a valid value, * then this field identifies an additional, secondary control group to which this entity's shape * belongs. Set to INVALID_ENTITY to not assign any secondary group. Defaults to INVALID_ENTITY. * * These are only necessary in case it is not sufficient for an entity to belong to only one control * group. Otherwise, they can be ignored. */ entity_id_t m_ControlGroup2; /// Identifier of this entity's obstruction shape, as registered in the obstruction manager. Contains /// structure, but should be treated as opaque here. tag_t m_Tag; std::vector m_ClusterTags; /// Set of flags affecting the behaviour of this entity's obstruction shape. flags_t m_Flags; static std::string GetSchema() { return "" "Causes this entity to obstruct the motion of other units." "" "" "" "" "1.5" "" "" "" "" "1.5" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "1.5" "" "" "" "" "1.5" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""; } virtual void Init(const CParamNode& paramNode) { // The minimum obstruction size is the navcell size * sqrt(2) // This is enforced in the schema as a minimum of 1.5 fixed minObstruction = (Pathfinding::NAVCELL_SIZE.Square() * 2).Sqrt(); m_TemplateFlags = 0; if (paramNode.GetChild("BlockMovement").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_MOVEMENT; if (paramNode.GetChild("BlockPathfinding").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_PATHFINDING; if (paramNode.GetChild("BlockFoundation").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_FOUNDATION; if (paramNode.GetChild("BlockConstruction").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION; if (paramNode.GetChild("DeleteUponConstruction").ToBool()) m_TemplateFlags |= ICmpObstructionManager::FLAG_DELETE_UPON_CONSTRUCTION; m_Flags = m_TemplateFlags; if (paramNode.GetChild("DisableBlockMovement").ToBool()) m_Flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); if (paramNode.GetChild("DisableBlockPathfinding").ToBool()) m_Flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); if (paramNode.GetChild("Unit").IsOk()) { m_Type = UNIT; CmpPtr cmpUnitMotion(GetEntityHandle()); if (cmpUnitMotion) m_Clearance = cmpUnitMotion->GetUnitClearance(); } else if (paramNode.GetChild("Static").IsOk()) { m_Type = STATIC; m_Size0 = paramNode.GetChild("Static").GetChild("@width").ToFixed(); m_Size1 = paramNode.GetChild("Static").GetChild("@depth").ToFixed(); ENSURE(m_Size0 > minObstruction); ENSURE(m_Size1 > minObstruction); } else { m_Type = CLUSTER; CFixedVector2D max = CFixedVector2D(fixed::FromInt(0), fixed::FromInt(0)); CFixedVector2D min = CFixedVector2D(fixed::FromInt(0), fixed::FromInt(0)); const CParamNode::ChildrenMap& clusterMap = paramNode.GetChild("Obstructions").GetChildren(); for(CParamNode::ChildrenMap::const_iterator it = clusterMap.begin(); it != clusterMap.end(); ++it) { Shape b; b.size0 = it->second.GetChild("@width").ToFixed(); b.size1 = it->second.GetChild("@depth").ToFixed(); ENSURE(b.size0 > minObstruction); ENSURE(b.size1 > minObstruction); b.dx = it->second.GetChild("@x").ToFixed(); b.dz = it->second.GetChild("@z").ToFixed(); b.da = entity_angle_t::FromInt(0); b.flags = m_Flags; m_Shapes.push_back(b); max.X = std::max(max.X, b.dx + b.size0/2); max.Y = std::max(max.Y, b.dz + b.size1/2); min.X = std::min(min.X, b.dx - b.size0/2); min.Y = std::min(min.Y, b.dz - b.size1/2); } m_Size0 = fixed::FromInt(2).Multiply(std::max(max.X, -min.X)); m_Size1 = fixed::FromInt(2).Multiply(std::max(max.Y, -min.Y)); } m_Active = paramNode.GetChild("Active").ToBool(); m_ControlPersist = paramNode.GetChild("ControlPersist").IsOk(); m_Tag = tag_t(); if (m_Type == CLUSTER) m_ClusterTags.clear(); m_Moving = false; m_ControlGroup = GetEntityId(); m_ControlGroup2 = INVALID_ENTITY; } virtual void Deinit() { } struct SerializeTag { template void operator()(S& serialize, const char* UNUSED(name), tag_t& value) { serialize.NumberU32_Unbounded("tag", value.n); } }; template void SerializeCommon(S& serialize) { serialize.Bool("active", m_Active); serialize.Bool("moving", m_Moving); serialize.NumberU32_Unbounded("control group", m_ControlGroup); serialize.NumberU32_Unbounded("control group 2", m_ControlGroup2); serialize.NumberU32_Unbounded("tag", m_Tag.n); serialize.NumberU8_Unbounded("flags", m_Flags); if (m_Type == CLUSTER) SerializeVector()(serialize, "cluster tags", m_ClusterTags); if (m_Type == UNIT) serialize.NumberFixed_Unbounded("clearance", m_Clearance); } virtual void Serialize(ISerializer& serialize) { SerializeCommon(serialize); } virtual void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) { Init(paramNode); SerializeCommon(deserialize); } virtual void HandleMessage(const CMessage& msg, bool UNUSED(global)) { switch (msg.GetType()) { case MT_PositionChanged: { if (!m_Active) break; const CMessagePositionChanged& data = static_cast (msg); if (!data.inWorld && !m_Tag.valid()) break; // nothing needs to change CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) break; // error if (data.inWorld && m_Tag.valid()) { cmpObstructionManager->MoveShape(m_Tag, data.x, data.z, data.a); if (m_Type == CLUSTER) { for (size_t i = 0; i < m_Shapes.size(); ++i) { Shape& b = m_Shapes[i]; fixed s, c; sincos_approx(data.a, s, c); cmpObstructionManager->MoveShape(m_ClusterTags[i], data.x + b.dx.Multiply(c) + b.dz.Multiply(s), data.z + b.dz.Multiply(c) - b.dx.Multiply(s), data.a + b.da); } } } else if (data.inWorld && !m_Tag.valid()) { // Need to create a new pathfinder shape: if (m_Type == STATIC) m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(), data.x, data.z, data.a, m_Size0, m_Size1, m_Flags, m_ControlGroup, m_ControlGroup2); else if (m_Type == UNIT) m_Tag = cmpObstructionManager->AddUnitShape(GetEntityId(), data.x, data.z, m_Clearance, (flags_t)(m_Flags | (m_Moving ? ICmpObstructionManager::FLAG_MOVING : 0)), m_ControlGroup); else AddClusterShapes(data.x, data.x, data.a); } else if (!data.inWorld && m_Tag.valid()) { cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if(m_Type == CLUSTER) RemoveClusterShapes(); } break; } case MT_Destroy: { if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) break; // error // Deactivate the obstruction in case PositionChanged messages are sent after this. m_Active = false; cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if(m_Type == CLUSTER) RemoveClusterShapes(); } break; } } } virtual void SetActive(bool active) { if (active && !m_Active) { m_Active = true; // Construct the obstruction shape CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return; // error if (!cmpPosition->IsInWorld()) return; // don't need an obstruction // TODO: code duplication from message handlers CFixedVector2D pos = cmpPosition->GetPosition2D(); if (m_Type == STATIC) m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(), pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, m_Flags, m_ControlGroup, m_ControlGroup2); else if (m_Type == UNIT) m_Tag = cmpObstructionManager->AddUnitShape(GetEntityId(), pos.X, pos.Y, m_Clearance, (flags_t)(m_Flags | (m_Moving ? ICmpObstructionManager::FLAG_MOVING : 0)), m_ControlGroup); else AddClusterShapes(pos.X, pos.Y, cmpPosition->GetRotation().Y); } else if (!active && m_Active) { m_Active = false; // Delete the obstruction shape // TODO: code duplication from message handlers if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error cmpObstructionManager->RemoveShape(m_Tag); m_Tag = tag_t(); if (m_Type == CLUSTER) RemoveClusterShapes(); } } // else we didn't change the active status } virtual void SetDisableBlockMovementPathfinding(bool movementDisabled, bool pathfindingDisabled, int32_t shape) { flags_t *flags = NULL; if (shape == -1) flags = &m_Flags; else if (m_Type == CLUSTER && shape < (int32_t)m_Shapes.size()) flags = &m_Shapes[shape].flags; else return; // error // Remove the blocking / pathfinding flags or // Add the blocking / pathfinding flags if the template had enabled them if (movementDisabled) *flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); else *flags |= (flags_t)(m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); if (pathfindingDisabled) *flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); else *flags |= (flags_t)(m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); // Reset the shape with the new flags (kind of inefficiently - we // should have a ICmpObstructionManager::SetFlags function or something) if (m_Active) { SetActive(false); SetActive(true); } } virtual bool GetBlockMovementFlag() const { return (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT) != 0; } virtual EObstructionType GetObstructionType() const { return m_Type; } virtual ICmpObstructionManager::tag_t GetObstruction() const { return m_Tag; } virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const { return GetObstructionSquare(out, true); } virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const { return GetObstructionSquare(out, false); } virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out, bool previousPosition) const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return false; // error CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return false; // error if (!cmpPosition->IsInWorld()) return false; // no obstruction square CFixedVector2D pos; if (previousPosition) pos = cmpPosition->GetPreviousPosition2D(); else pos = cmpPosition->GetPosition2D(); if (m_Type == UNIT) out = cmpObstructionManager->GetUnitShapeObstruction(pos.X, pos.Y, m_Clearance); else out = cmpObstructionManager->GetStaticShapeObstruction(pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1); return true; } - virtual entity_pos_t GetUnitRadius() const - { - if (m_Type == UNIT) - return m_Clearance; - else - return entity_pos_t::Zero(); - } - virtual entity_pos_t GetSize() const { if (m_Type == UNIT) return m_Clearance; else return CFixedVector2D(m_Size0 / 2, m_Size1 / 2).Length(); } virtual CFixedVector2D GetStaticSize() const { return m_Type == STATIC ? CFixedVector2D(m_Size0, m_Size1) : CFixedVector2D(); } virtual void SetUnitClearance(const entity_pos_t& clearance) { if (m_Type == UNIT) m_Clearance = clearance; } virtual bool IsControlPersistent() const { return m_ControlPersist; } virtual bool CheckShorePlacement() const { ICmpObstructionManager::ObstructionSquare s; if (!GetObstructionSquare(s)) return false; CFixedVector2D front = CFixedVector2D(s.x, s.z) + s.v.Multiply(s.hh); CFixedVector2D back = CFixedVector2D(s.x, s.z) - s.v.Multiply(s.hh); CmpPtr cmpTerrain(GetSystemEntity()); CmpPtr cmpWaterManager(GetSystemEntity()); if (!cmpTerrain || !cmpWaterManager) return false; // Keep these constants in agreement with the pathfinder. return cmpWaterManager->GetWaterLevel(front.X, front.Y) - cmpTerrain->GetGroundLevel(front.X, front.Y) > fixed::FromInt(1) && cmpWaterManager->GetWaterLevel( back.X, back.Y) - cmpTerrain->GetGroundLevel( back.X, back.Y) < fixed::FromInt(2); } virtual EFoundationCheck CheckFoundation(const std::string& className) const { return CheckFoundation(className, false); } virtual EFoundationCheck CheckFoundation(const std::string& className, bool onlyCenterPoint) const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return FOUNDATION_CHECK_FAIL_ERROR; // error if (!cmpPosition->IsInWorld()) return FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION; // no obstruction CFixedVector2D pos = cmpPosition->GetPosition2D(); CmpPtr cmpPathfinder(GetSystemEntity()); if (!cmpPathfinder) return FOUNDATION_CHECK_FAIL_ERROR; // error // required precondition to use SkipControlGroupsRequireFlagObstructionFilter if (m_ControlGroup == INVALID_ENTITY) { LOGERROR("[CmpObstruction] Cannot test for foundation obstructions; primary control group must be valid"); return FOUNDATION_CHECK_FAIL_ERROR; } // Get passability class pass_class_t passClass = cmpPathfinder->GetPassabilityClass(className); // Ignore collisions within the same control group, or with other non-foundation-blocking shapes. // Note that, since the control group for each entity defaults to the entity's ID, this is typically // equivalent to only ignoring the entity's own shape and other non-foundation-blocking shapes. SkipControlGroupsRequireFlagObstructionFilter filter(m_ControlGroup, m_ControlGroup2, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION); if (m_Type == UNIT) return cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, m_Clearance, passClass, onlyCenterPoint); else return cmpPathfinder->CheckBuildingPlacement(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, GetEntityId(), passClass, onlyCenterPoint); } virtual bool CheckDuplicateFoundation() const { CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return false; // error if (!cmpPosition->IsInWorld()) return false; // no obstruction CFixedVector2D pos = cmpPosition->GetPosition2D(); CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return false; // error // required precondition to use SkipControlGroupsRequireFlagObstructionFilter if (m_ControlGroup == INVALID_ENTITY) { LOGERROR("[CmpObstruction] Cannot test for foundation obstructions; primary control group must be valid"); return false; } // Ignore collisions with entities unless they block foundations and match both control groups. SkipTagRequireControlGroupsAndFlagObstructionFilter filter(m_Tag, m_ControlGroup, m_ControlGroup2, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION); if (m_Type == UNIT) return !cmpObstructionManager->TestUnitShape(filter, pos.X, pos.Y, m_Clearance, NULL); else return !cmpObstructionManager->TestStaticShape(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, NULL ); } virtual std::vector GetEntitiesByFlags(flags_t flags) const { std::vector ret; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return ret; // error // Ignore collisions within the same control group, or with other shapes that don't match the filter. // Note that, since the control group for each entity defaults to the entity's ID, this is typically // equivalent to only ignoring the entity's own shape and other shapes that don't match the filter. SkipControlGroupsRequireFlagObstructionFilter filter(false, m_ControlGroup, m_ControlGroup2, flags); ICmpObstructionManager::ObstructionSquare square; if (!GetObstructionSquare(square)) return ret; // error cmpObstructionManager->GetUnitsOnObstruction(square, ret, filter, false); cmpObstructionManager->GetStaticObstructionsOnObstruction(square, ret, filter); return ret; } virtual std::vector GetEntitiesBlockingMovement() const { return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); } virtual std::vector GetEntitiesBlockingConstruction() const { return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); } virtual std::vector GetEntitiesDeletedUponConstruction() const { return GetEntitiesByFlags(ICmpObstructionManager::FLAG_DELETE_UPON_CONSTRUCTION); } virtual void SetMovingFlag(bool enabled) { m_Moving = enabled; if (m_Tag.valid() && m_Type == UNIT) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (cmpObstructionManager) cmpObstructionManager->SetUnitMovingFlag(m_Tag, m_Moving); } } virtual void SetControlGroup(entity_id_t group) { m_ControlGroup = group; UpdateControlGroups(); } virtual void SetControlGroup2(entity_id_t group2) { m_ControlGroup2 = group2; UpdateControlGroups(); } virtual entity_id_t GetControlGroup() const { return m_ControlGroup; } virtual entity_id_t GetControlGroup2() const { return m_ControlGroup2; } void UpdateControlGroups() { if (m_Tag.valid()) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (cmpObstructionManager) { if (m_Type == UNIT) { cmpObstructionManager->SetUnitControlGroup(m_Tag, m_ControlGroup); } else if (m_Type == STATIC) { cmpObstructionManager->SetStaticControlGroup(m_Tag, m_ControlGroup, m_ControlGroup2); } else { cmpObstructionManager->SetStaticControlGroup(m_Tag, m_ControlGroup, m_ControlGroup2); for (size_t i = 0; i < m_ClusterTags.size(); ++i) { cmpObstructionManager->SetStaticControlGroup(m_ClusterTags[i], m_ControlGroup, m_ControlGroup2); } } } } } void ResolveFoundationCollisions() const { if (m_Type == UNIT) return; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; CmpPtr cmpPosition(GetEntityHandle()); if (!cmpPosition) return; // error if (!cmpPosition->IsInWorld()) return; // no obstruction CFixedVector2D pos = cmpPosition->GetPosition2D(); // Ignore collisions within the same control group, or with other non-foundation-blocking shapes. // Note that, since the control group for each entity defaults to the entity's ID, this is typically // equivalent to only ignoring the entity's own shape and other non-foundation-blocking shapes. SkipControlGroupsRequireFlagObstructionFilter filter(m_ControlGroup, m_ControlGroup2, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION); std::vector collisions; if (cmpObstructionManager->TestStaticShape(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, &collisions)) { std::vector persistentEnts, normalEnts; if (m_ControlPersist) persistentEnts.push_back(m_ControlGroup); else normalEnts.push_back(GetEntityId()); for (std::vector::iterator it = collisions.begin(); it != collisions.end(); ++it) { entity_id_t ent = *it; if (ent == INVALID_ENTITY) continue; CmpPtr cmpObstruction(GetSimContext(), ent); if (!cmpObstruction->IsControlPersistent()) normalEnts.push_back(ent); else persistentEnts.push_back(cmpObstruction->GetControlGroup()); } // The collision can't be resolved without usable persistent control groups. if (persistentEnts.empty()) return; // Attempt to replace colliding entities' control groups with a persistent one. for (std::vector::iterator it = normalEnts.begin(); it != normalEnts.end(); ++it) { entity_id_t ent = *it; CmpPtr cmpObstruction(GetSimContext(), ent); for (std::vector::iterator it = persistentEnts.begin(); it != persistentEnts.end(); ++it) { entity_id_t persistent = *it; entity_id_t group = cmpObstruction->GetControlGroup(); // Only clobber 'default' control groups. if (group == ent) cmpObstruction->SetControlGroup(persistent); else if (cmpObstruction->GetControlGroup2() == INVALID_ENTITY && group != persistent) cmpObstruction->SetControlGroup2(persistent); } } } } protected: inline void AddClusterShapes(entity_pos_t x, entity_pos_t z, entity_angle_t a) { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error flags_t flags = m_Flags; // Disable block movement and block pathfinding for the obstruction shape flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING); m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(), x, z, a, m_Size0, m_Size1, flags, m_ControlGroup, m_ControlGroup2); fixed s, c; sincos_approx(a, s, c); for (size_t i = 0; i < m_Shapes.size(); ++i) { Shape& b = m_Shapes[i]; tag_t tag = cmpObstructionManager->AddStaticShape(GetEntityId(), x + b.dx.Multiply(c) + b.dz.Multiply(s), z + b.dz.Multiply(c) - b.dx.Multiply(s), a + b.da, b.size0, b.size1, b.flags, m_ControlGroup, m_ControlGroup2); m_ClusterTags.push_back(tag); } } inline void RemoveClusterShapes() { CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return; // error for (size_t i = 0; i < m_ClusterTags.size(); ++i) { if (m_ClusterTags[i].valid()) { cmpObstructionManager->RemoveShape(m_ClusterTags[i]); } } m_ClusterTags.clear(); } }; REGISTER_COMPONENT_TYPE(Obstruction) Index: ps/trunk/source/simulation2/components/ICmpObstruction.cpp =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstruction.cpp (revision 24009) +++ ps/trunk/source/simulation2/components/ICmpObstruction.cpp (revision 24010) @@ -1,63 +1,63 @@ /* Copyright (C) 2020 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "ICmpObstruction.h" #include "simulation2/system/InterfaceScripted.h" #include "simulation2/system/SimContext.h" std::string ICmpObstruction::CheckFoundation_wrapper(const std::string& className, bool onlyCenterPoint) const { EFoundationCheck check = CheckFoundation(className, onlyCenterPoint); switch (check) { case FOUNDATION_CHECK_SUCCESS: return "success"; case FOUNDATION_CHECK_FAIL_ERROR: return "fail_error"; case FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION: return "fail_no_obstruction"; case FOUNDATION_CHECK_FAIL_OBSTRUCTS_FOUNDATION: return "fail_obstructs_foundation"; case FOUNDATION_CHECK_FAIL_TERRAIN_CLASS: return "fail_terrain_class"; default: debug_warn(L"Unexpected result from CheckFoundation"); return ""; } } BEGIN_INTERFACE_WRAPPER(Obstruction) -DEFINE_INTERFACE_METHOD_CONST_0("GetUnitRadius", entity_pos_t, ICmpObstruction, GetUnitRadius) +DEFINE_INTERFACE_METHOD_CONST_0("GetSize", entity_pos_t, ICmpObstruction, GetSize) DEFINE_INTERFACE_METHOD_CONST_0("CheckShorePlacement", bool, ICmpObstruction, CheckShorePlacement) DEFINE_INTERFACE_METHOD_CONST_2("CheckFoundation", std::string, ICmpObstruction, CheckFoundation_wrapper, std::string, bool) DEFINE_INTERFACE_METHOD_CONST_0("CheckDuplicateFoundation", bool, ICmpObstruction, CheckDuplicateFoundation) DEFINE_INTERFACE_METHOD_CONST_0("GetEntitiesBlockingMovement", std::vector, ICmpObstruction, GetEntitiesBlockingMovement) DEFINE_INTERFACE_METHOD_CONST_0("GetEntitiesBlockingConstruction", std::vector, ICmpObstruction, GetEntitiesBlockingConstruction) DEFINE_INTERFACE_METHOD_CONST_0("GetEntitiesDeletedUponConstruction", std::vector, ICmpObstruction, GetEntitiesDeletedUponConstruction) DEFINE_INTERFACE_METHOD_1("SetActive", void, ICmpObstruction, SetActive, bool) DEFINE_INTERFACE_METHOD_3("SetDisableBlockMovementPathfinding", void, ICmpObstruction, SetDisableBlockMovementPathfinding, bool, bool, int32_t) DEFINE_INTERFACE_METHOD_CONST_0("GetBlockMovementFlag", bool, ICmpObstruction, GetBlockMovementFlag) DEFINE_INTERFACE_METHOD_1("SetControlGroup", void, ICmpObstruction, SetControlGroup, entity_id_t) DEFINE_INTERFACE_METHOD_CONST_0("GetControlGroup", entity_id_t, ICmpObstruction, GetControlGroup) DEFINE_INTERFACE_METHOD_1("SetControlGroup2", void, ICmpObstruction, SetControlGroup2, entity_id_t) DEFINE_INTERFACE_METHOD_CONST_0("GetControlGroup2", entity_id_t, ICmpObstruction, GetControlGroup2) END_INTERFACE_WRAPPER(Obstruction) Index: ps/trunk/source/simulation2/components/ICmpObstruction.h =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 24009) +++ ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 24010) @@ -1,155 +1,159 @@ /* Copyright (C) 2020 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #ifndef INCLUDED_ICMPOBSTRUCTION #define INCLUDED_ICMPOBSTRUCTION #include "simulation2/system/Interface.h" #include "simulation2/components/ICmpObstructionManager.h" /** * Flags an entity as obstructing movement for other units, * and handles the processing of collision queries. */ class ICmpObstruction : public IComponent { public: enum EFoundationCheck { FOUNDATION_CHECK_SUCCESS, FOUNDATION_CHECK_FAIL_ERROR, FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION, FOUNDATION_CHECK_FAIL_OBSTRUCTS_FOUNDATION, FOUNDATION_CHECK_FAIL_TERRAIN_CLASS }; enum EObstructionType { STATIC, UNIT, CLUSTER }; virtual ICmpObstructionManager::tag_t GetObstruction() const = 0; /** * Gets the square corresponding to this obstruction shape. * @return true and updates @p out on success; * false on failure (e.g. object not in the world). */ virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const = 0; /** * Same as the method above, but returns an obstruction shape for the previous turn */ virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const = 0; + /** + * @return the size of the obstruction (either the clearance or a circumscribed circle). + */ virtual entity_pos_t GetSize() const = 0; + /** + * @return the size of the static obstruction or (0,0) for a unit shape. + */ virtual CFixedVector2D GetStaticSize() const = 0; - virtual entity_pos_t GetUnitRadius() const = 0; - virtual EObstructionType GetObstructionType() const = 0; virtual void SetUnitClearance(const entity_pos_t& clearance) = 0; virtual bool IsControlPersistent() const = 0; /** * Test whether the front of the obstruction square is in the water and the back is on the shore. */ virtual bool CheckShorePlacement() const = 0; /** * Test whether this entity is colliding with any obstruction that are set to * block the creation of foundations. * @param ignoredEntities List of entities to ignore during the test. * @return FOUNDATION_CHECK_SUCCESS if check passes, else an EFoundationCheck * value describing the type of failure. */ virtual EFoundationCheck CheckFoundation(const std::string& className) const = 0; virtual EFoundationCheck CheckFoundation(const std::string& className, bool onlyCenterPoint) const = 0; /** * CheckFoundation wrapper for script calls, to return friendly strings instead of an EFoundationCheck. * @return "success" if check passes, else a string describing the type of failure. */ virtual std::string CheckFoundation_wrapper(const std::string& className, bool onlyCenterPoint) const; /** * Test whether this entity is colliding with any obstructions that share its * control groups and block the creation of foundations. * @return true if foundation is valid (not obstructed) */ virtual bool CheckDuplicateFoundation() const = 0; /** * Returns a list of entities that have an obstruction matching the given flag and intersect the current obstruction. * @return vector of blocking entities */ virtual std::vector GetEntitiesByFlags(ICmpObstructionManager::flags_t flags) const = 0; /** * Returns a list of entities that are blocking movement. * @return vector of blocking entities */ virtual std::vector GetEntitiesBlockingMovement() const = 0; /** * Returns a list of entities that are blocking construction of a foundation. * @return vector of blocking entities */ virtual std::vector GetEntitiesBlockingConstruction() const = 0; /** * Returns a list of entities that shall be deleted when a construction on this obstruction starts, * for example sheep carcasses. */ virtual std::vector GetEntitiesDeletedUponConstruction() const = 0; /** * Detects collisions between foundation-blocking entities and * tries to fix them by setting control groups, if appropriate. */ virtual void ResolveFoundationCollisions() const = 0; virtual void SetActive(bool active) = 0; virtual void SetMovingFlag(bool enabled) = 0; virtual void SetDisableBlockMovementPathfinding(bool movementDisabled, bool pathfindingDisabled, int32_t shape) = 0; virtual bool GetBlockMovementFlag() const = 0; /** * Change the control group that the entity belongs to. * Control groups are used to let units ignore collisions with other units from * the same group. Default is the entity's own ID. */ virtual void SetControlGroup(entity_id_t group) = 0; /// See SetControlGroup. virtual entity_id_t GetControlGroup() const = 0; virtual void SetControlGroup2(entity_id_t group2) = 0; virtual entity_id_t GetControlGroup2() const = 0; DECLARE_INTERFACE_TYPE(Obstruction) }; #endif // INCLUDED_ICMPOBSTRUCTION Index: ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h =================================================================== --- ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h (revision 24009) +++ ps/trunk/source/simulation2/components/tests/test_ObstructionManager.h (revision 24010) @@ -1,594 +1,593 @@ /* Copyright (C) 2020 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "simulation2/system/ComponentTest.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpObstruction.h" class MockObstruction : public ICmpObstruction { public: DEFAULT_MOCK_COMPONENT() ICmpObstructionManager::ObstructionSquare obstruction; virtual ICmpObstructionManager::tag_t GetObstruction() const { return ICmpObstructionManager::tag_t(); } virtual bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const { out = obstruction; return true; } virtual bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& UNUSED(out)) const { return true; } virtual entity_pos_t GetSize() const { return entity_pos_t::Zero(); } virtual CFixedVector2D GetStaticSize() const { return CFixedVector2D(); } - virtual entity_pos_t GetUnitRadius() const { return entity_pos_t::Zero(); } virtual EObstructionType GetObstructionType() const { return ICmpObstruction::STATIC; } virtual void SetUnitClearance(const entity_pos_t& UNUSED(clearance)) { } virtual bool IsControlPersistent() const { return true; } virtual bool CheckShorePlacement() const { return true; } virtual EFoundationCheck CheckFoundation(const std::string& UNUSED(className)) const { return EFoundationCheck(); } virtual EFoundationCheck CheckFoundation(const std::string& UNUSED(className), bool UNUSED(onlyCenterPoint)) const { return EFoundationCheck(); } virtual std::string CheckFoundation_wrapper(const std::string& UNUSED(className), bool UNUSED(onlyCenterPoint)) const { return std::string(); } virtual bool CheckDuplicateFoundation() const { return true; } virtual std::vector GetEntitiesByFlags(ICmpObstructionManager::flags_t UNUSED(flags)) const { return std::vector(); } virtual std::vector GetEntitiesBlockingMovement() const { return std::vector(); } virtual std::vector GetEntitiesBlockingConstruction() const { return std::vector(); } virtual std::vector GetEntitiesDeletedUponConstruction() const { return std::vector(); } virtual void ResolveFoundationCollisions() const { } virtual void SetActive(bool UNUSED(active)) { } virtual void SetMovingFlag(bool UNUSED(enabled)) { } virtual void SetDisableBlockMovementPathfinding(bool UNUSED(movementDisabled), bool UNUSED(pathfindingDisabled), int32_t UNUSED(shape)) { } virtual bool GetBlockMovementFlag() const { return true; } virtual void SetControlGroup(entity_id_t UNUSED(group)) { } virtual entity_id_t GetControlGroup() const { return INVALID_ENTITY; } virtual void SetControlGroup2(entity_id_t UNUSED(group2)) { } virtual entity_id_t GetControlGroup2() const { return INVALID_ENTITY; } }; class TestCmpObstructionManager : public CxxTest::TestSuite { typedef ICmpObstructionManager::tag_t tag_t; typedef ICmpObstructionManager::ObstructionSquare ObstructionSquare; // some variables for setting up a scene with 3 shapes entity_id_t ent1, ent2, ent3; // entity IDs entity_angle_t ent1a; // angles entity_pos_t ent1x, ent1z, ent1w, ent1h, // positions/dimensions ent2x, ent2z, ent2c, ent3x, ent3z, ent3c; entity_id_t ent1g1, ent1g2, ent2g, ent3g; // control groups tag_t shape1, shape2, shape3; ICmpObstructionManager* cmp; ComponentTestHelper* testHelper; public: void setUp() { CXeromyces::Startup(); CxxTest::setAbortTestOnFail(true); // set up a simple scene with some predefined obstruction shapes // (we can't position shapes on the origin because the world bounds must range // from 0 to X, so instead we'll offset things by, say, 10). ent1 = 1; ent1a = fixed::Zero(); ent1w = fixed::FromFloat(4); ent1h = fixed::FromFloat(2); ent1x = fixed::FromInt(10); ent1z = fixed::FromInt(10); ent1g1 = ent1; ent1g2 = INVALID_ENTITY; ent2 = 2; ent2c = fixed::FromFloat(1); ent2x = ent1x; ent2z = ent1z; ent2g = ent1g1; ent3 = 3; ent3c = fixed::FromFloat(3); ent3x = ent2x; ent3z = ent2z + ent2c + ent3c; // ensure it just touches the border of ent2 ent3g = ent3; testHelper = new ComponentTestHelper(g_ScriptRuntime); cmp = testHelper->Add(CID_ObstructionManager, "", SYSTEM_ENTITY); cmp->SetBounds(fixed::FromInt(0), fixed::FromInt(0), fixed::FromInt(1000), fixed::FromInt(1000)); shape1 = cmp->AddStaticShape(ent1, ent1x, ent1z, ent1a, ent1w, ent1h, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_MOVING, ent1g1, ent1g2); shape2 = cmp->AddUnitShape(ent2, ent2x, ent2z, ent2c, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_FOUNDATION, ent2g); shape3 = cmp->AddUnitShape(ent3, ent3x, ent3z, ent3c, ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_BLOCK_FOUNDATION, ent3g); } void tearDown() { delete testHelper; cmp = NULL; // not our responsibility to deallocate CXeromyces::Terminate(); } /** * Verifies the collision testing procedure. Collision-tests some simple shapes against the shapes registered in * the scene, and verifies the result of the test against the expected value. */ void test_simple_collisions() { std::vector out; NullObstructionFilter nullFilter; // Collision-test a simple shape nested inside shape3 against all shapes in the scene. Since the tested shape // overlaps only with shape 3, we should find only shape 3 in the result. cmp->TestUnitShape(nullFilter, ent3x, ent3z, fixed::FromInt(1), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestStaticShape(nullFilter, ent3x, ent3z, fixed::Zero(), fixed::FromInt(1), fixed::FromInt(1), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // Similarly, collision-test a simple shape nested inside both shape1 and shape2. Since the tested shape overlaps // only with shapes 1 and 2, those are the only ones we should find in the result. cmp->TestUnitShape(nullFilter, ent2x, ent2z, ent2c/2, &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); cmp->TestStaticShape(nullFilter, ent2x, ent2z, fixed::Zero(), ent2c, ent2c, &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); } /** * Verifies the behaviour of the null obstruction filter. Tests with this filter will be performed against all * registered shapes. */ void test_filter_null() { std::vector out; // Collision test a scene-covering shape against all shapes in the scene. We should find all registered shapes // in the result. NullObstructionFilter nullFilter; cmp->TestUnitShape(nullFilter, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(3U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(nullFilter, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(3U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); } /** * Verifies the behaviour of the StationaryOnlyObstructionFilter. Tests with this filter will be performed only * against non-moving (stationary) shapes. */ void test_filter_stationary_only() { std::vector out; // Collision test a scene-covering shape against all shapes in the scene, but skipping shapes that are moving, // i.e. shapes that have the MOVING flag. Since only shape 1 is flagged as moving, we should find // shapes 2 and 3 in each case. StationaryOnlyObstructionFilter ignoreMoving; cmp->TestUnitShape(ignoreMoving, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(ignoreMoving, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); } /** * Verifies the behaviour of the SkipTagObstructionFilter. Tests with this filter will be performed against * all registered shapes that do not have the specified tag set. */ void test_filter_skip_tag() { std::vector out; // Collision-test shape 2's obstruction shape against all shapes in the scene, but skipping tests against // shape 2. Since shape 2 overlaps only with shape 1, we should find only shape 1's entity ID in the result. SkipTagObstructionFilter ignoreShape2(shape2); cmp->TestUnitShape(ignoreShape2, ent2x, ent2z, ent2c/2, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent1, out[0]); out.clear(); cmp->TestStaticShape(ignoreShape2, ent2x, ent2z, fixed::Zero(), ent2c, ent2c, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent1, out[0]); out.clear(); } /** * Verifies the behaviour of the SkipTagFlagsObstructionFilter. Tests with this filter will be performed against * all registered shapes that do not have the specified tag set, and that have at least one of required flags set. */ void test_filter_skip_tag_require_flag() { std::vector out; // Collision-test a scene-covering shape against all shapes in the scene, but skipping tests against shape 1 // and requiring the BLOCK_MOVEMENT flag. Since shape 1 is being ignored and shape 2 does not have the required // flag, we should find only shape 3 in the results. SkipTagRequireFlagsObstructionFilter skipShape1RequireBlockMovement(shape1, ICmpObstructionManager::FLAG_BLOCK_MOVEMENT); cmp->TestUnitShape(skipShape1RequireBlockMovement, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestStaticShape(skipShape1RequireBlockMovement, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // If we now do the same test, but require at least one of the entire set of available filters, we should find // all shapes that are not shape 1 and that have at least one flag set. Since all shapes in our testing scene // have at least one flag set, we should find shape 2 and shape 3 in the results. SkipTagRequireFlagsObstructionFilter skipShape1RequireAnyFlag(shape1, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipShape1RequireAnyFlag, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(skipShape1RequireAnyFlag, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); // And if we now do the same test yet again, but specify an empty set of flags, then it becomes impossible for // any shape to have at least one of the required flags, and we should hence find no shapes in the result. SkipTagRequireFlagsObstructionFilter skipShape1RejectAll(shape1, 0U); cmp->TestUnitShape(skipShape1RejectAll, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestStaticShape(skipShape1RejectAll, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); } /** * Verifies the behaviour of SkipControlGroupsRequireFlagObstructionFilter. Tests with this filter will be performed * against all registered shapes that are members of neither specified control groups, and that have at least one of * the specified flags set. */ void test_filter_skip_controlgroups_require_flag() { std::vector out; // Collision-test a shape that overlaps the entire scene, but ignoring shapes from shape1's control group // (which also includes shape 2), and requiring that either the BLOCK_FOUNDATION or the // BLOCK_CONSTRUCTION flag is set, or both. Since shape 1 and shape 2 both belong to shape 1's control // group, and shape 3 has the BLOCK_FOUNDATION flag (but not BLOCK_CONSTRUCTION), we should find only // shape 3 in the result. SkipControlGroupsRequireFlagObstructionFilter skipGroup1ReqFoundConstr(ent1g1, INVALID_ENTITY, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION | ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); cmp->TestUnitShape(skipGroup1ReqFoundConstr, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestStaticShape(skipGroup1ReqFoundConstr, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // Perform the same test, but now also exclude shape 3's control group (in addition to shape 1's control // group). Despite shape 3 having at least one of the required flags set, it should now also be ignored, // yielding an empty result set. SkipControlGroupsRequireFlagObstructionFilter skipGroup1And3ReqFoundConstr(ent1g1, ent3g, ICmpObstructionManager::FLAG_BLOCK_FOUNDATION | ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); cmp->TestUnitShape(skipGroup1And3ReqFoundConstr, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestStaticShape(skipGroup1And3ReqFoundConstr, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); // Same test, but this time excluding only shape 3's control group, and requiring any of the available flags // to be set. Since both shape 1 and shape 2 have at least one flag set and are both in a different control // group, we should find them in the result. SkipControlGroupsRequireFlagObstructionFilter skipGroup3RequireAnyFlag(ent3g, INVALID_ENTITY, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipGroup3RequireAnyFlag, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); cmp->TestStaticShape(skipGroup3RequireAnyFlag, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent1); TS_ASSERT_VECTOR_CONTAINS(out, ent2); out.clear(); // Finally, the same test as the one directly above, now with an empty set of required flags. Since it now becomes // impossible for shape 1 and shape 2 to have at least one of the required flags set, and shape 3 is excluded by // virtue of the control group filtering, we should find an empty result. SkipControlGroupsRequireFlagObstructionFilter skipGroup3RequireNoFlags(ent3g, INVALID_ENTITY, 0U); cmp->TestUnitShape(skipGroup3RequireNoFlags, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestStaticShape(skipGroup3RequireNoFlags, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); // ------------------------------------------------------------------------------------ // In the tests up until this point, the shapes have all been filtered out based on their primary control group. // Now, to verify that shapes are also filtered out based on their secondary control groups, add a fourth shape // with arbitrarily-chosen dual control groups, and also change shape 1's secondary control group to another // arbitrarily-chosen control group. Then, do a scene-covering collision test while filtering out a combination // of shape 1's secondary control group, and one of shape 4's control groups. We should find neither ent1 nor ent4 // in the result. entity_id_t ent4 = 4, ent4g1 = 17, ent4g2 = 19, ent1g2_new = 18; // new secondary control group for entity 1 entity_pos_t ent4x = fixed::FromInt(4), ent4z = fixed::Zero(), ent4w = fixed::FromInt(1), ent4h = fixed::FromInt(1); entity_angle_t ent4a = fixed::FromDouble(M_PI/3); cmp->AddStaticShape(ent4, ent4x, ent4z, ent4a, ent4w, ent4h, ICmpObstructionManager::FLAG_BLOCK_PATHFINDING, ent4g1, ent4g2); cmp->SetStaticControlGroup(shape1, ent1g1, ent1g2_new); // Exclude shape 1's and shape 4's secondary control groups from testing, and require any available flag to be set. // Since neither shape 2 nor shape 3 are part of those control groups and both have at least one available flag set, // the results should only those two shapes' entities. SkipControlGroupsRequireFlagObstructionFilter skipGroup1SecAnd4SecRequireAny(ent1g2_new, ent4g2, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipGroup1SecAnd4SecRequireAny, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(skipGroup1SecAnd4SecRequireAny, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); // Same as the above, but now exclude shape 1's secondary and shape 4's primary control group, while still requiring // any available flag to be set. (Note that the test above used shape 4's secondary control group). Results should // remain the same. SkipControlGroupsRequireFlagObstructionFilter skipGroup1SecAnd4PrimRequireAny(ent1g2_new, ent4g1, (ICmpObstructionManager::flags_t) -1); cmp->TestUnitShape(skipGroup1SecAnd4PrimRequireAny, ent1x, ent1z, fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->TestStaticShape(skipGroup1SecAnd4PrimRequireAny, ent1x, ent1z, fixed::Zero(), fixed::FromInt(10), fixed::FromInt(10), &out); TS_ASSERT_EQUALS(2U, out.size()); TS_ASSERT_VECTOR_CONTAINS(out, ent2); TS_ASSERT_VECTOR_CONTAINS(out, ent3); out.clear(); cmp->SetStaticControlGroup(shape1, ent1g1, ent1g2); // restore shape 1's original secondary control group } void test_adjacent_shapes() { std::vector out; NullObstructionFilter nullFilter; SkipTagObstructionFilter ignoreShape1(shape1); SkipTagObstructionFilter ignoreShape2(shape2); SkipTagObstructionFilter ignoreShape3(shape3); // Collision-test a shape that is perfectly adjacent to shape3. This should be counted as a hit according to // the code at the time of writing. entity_angle_t ent4a = fixed::FromDouble(M_PI); // rotated 180 degrees, should not affect collision test entity_pos_t ent4w = fixed::FromInt(2), ent4h = fixed::FromInt(1), ent4x = ent3x + ent3c + ent4w/2, // make ent4 adjacent to ent3 ent4z = ent3z; cmp->TestStaticShape(nullFilter, ent4x, ent4z, ent4a, ent4w, ent4h, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); cmp->TestUnitShape(nullFilter, ent4x, ent4z, ent4w/2, &out); TS_ASSERT_EQUALS(1U, out.size()); TS_ASSERT_EQUALS(ent3, out[0]); out.clear(); // now do the same tests, but move the shape a little bit to the right so that it doesn't touch anymore cmp->TestStaticShape(nullFilter, ent4x + fixed::FromFloat(1e-5f), ent4z, ent4a, ent4w, ent4h, &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); cmp->TestUnitShape(nullFilter, ent4x + fixed::FromFloat(1e-5f), ent4z, ent4w/2, &out); TS_ASSERT_EQUALS(0U, out.size()); out.clear(); } /** * Verifies that fetching the registered shapes from the obstruction manager yields the correct results. */ void test_get_obstruction() { ObstructionSquare obSquare1 = cmp->GetObstruction(shape1); ObstructionSquare obSquare2 = cmp->GetObstruction(shape2); ObstructionSquare obSquare3 = cmp->GetObstruction(shape3); TS_ASSERT_EQUALS(obSquare1.hh, ent1h/2); TS_ASSERT_EQUALS(obSquare1.hw, ent1w/2); TS_ASSERT_EQUALS(obSquare1.x, ent1x); TS_ASSERT_EQUALS(obSquare1.z, ent1z); TS_ASSERT_EQUALS(obSquare1.u, CFixedVector2D(fixed::FromInt(1), fixed::FromInt(0))); TS_ASSERT_EQUALS(obSquare1.v, CFixedVector2D(fixed::FromInt(0), fixed::FromInt(1))); TS_ASSERT_EQUALS(obSquare2.hh, ent2c); TS_ASSERT_EQUALS(obSquare2.hw, ent2c); TS_ASSERT_EQUALS(obSquare2.x, ent2x); TS_ASSERT_EQUALS(obSquare2.z, ent2z); TS_ASSERT_EQUALS(obSquare2.u, CFixedVector2D(fixed::FromInt(1), fixed::FromInt(0))); TS_ASSERT_EQUALS(obSquare2.v, CFixedVector2D(fixed::FromInt(0), fixed::FromInt(1))); TS_ASSERT_EQUALS(obSquare3.hh, ent3c); TS_ASSERT_EQUALS(obSquare3.hw, ent3c); TS_ASSERT_EQUALS(obSquare3.x, ent3x); TS_ASSERT_EQUALS(obSquare3.z, ent3z); TS_ASSERT_EQUALS(obSquare3.u, CFixedVector2D(fixed::FromInt(1), fixed::FromInt(0))); TS_ASSERT_EQUALS(obSquare3.v, CFixedVector2D(fixed::FromInt(0), fixed::FromInt(1))); } /** * Verifies the calculations of distances between shapes. */ void test_distance_to() { // Create two more entities to have non-zero distances entity_id_t ent4 = 4, ent4g1 = ent4, ent4g2 = INVALID_ENTITY, ent5 = 5, ent5g1 = ent5, ent5g2 = INVALID_ENTITY; entity_pos_t ent4a = fixed::Zero(), ent4w = fixed::FromInt(6), ent4h = fixed::Zero(), ent4x = ent1x, ent4z = fixed::FromInt(20), ent5a = fixed::Zero(), ent5w = fixed::FromInt(2), ent5h = fixed::FromInt(4), ent5x = fixed::FromInt(20), ent5z = ent1z; tag_t shape4 = cmp->AddStaticShape(ent4, ent4x, ent4z, ent4a, ent4w, ent4h, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_MOVING, ent4g1, ent4g2); tag_t shape5 = cmp->AddStaticShape(ent5, ent5x, ent5z, ent5a, ent5w, ent5h, ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION | ICmpObstructionManager::FLAG_BLOCK_MOVEMENT | ICmpObstructionManager::FLAG_MOVING, ent5g1, ent5g2); MockObstruction obstruction1, obstruction2, obstruction3, obstruction4, obstruction5; testHelper->AddMock(ent1, IID_Obstruction, obstruction1); testHelper->AddMock(ent2, IID_Obstruction, obstruction2); testHelper->AddMock(ent3, IID_Obstruction, obstruction3); testHelper->AddMock(ent4, IID_Obstruction, obstruction4); testHelper->AddMock(ent5, IID_Obstruction, obstruction5); obstruction1.obstruction = cmp->GetObstruction(shape1); obstruction2.obstruction = cmp->GetObstruction(shape2); obstruction3.obstruction = cmp->GetObstruction(shape3); obstruction4.obstruction = cmp->GetObstruction(shape4); obstruction5.obstruction = cmp->GetObstruction(shape5); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent1, ent2)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent2, ent1)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent2, ent3)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent3, ent2)); // Due to rounding errors we need to use some leeway TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(80)), cmp->MaxDistanceToTarget(ent2, ent3), fixed::FromFloat(0.0001)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(80)), cmp->MaxDistanceToTarget(ent3, ent2), fixed::FromFloat(0.0001)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent1, ent3)); TS_ASSERT_EQUALS(fixed::Zero(), cmp->DistanceToTarget(ent3, ent1)); TS_ASSERT_EQUALS(fixed::FromInt(6), cmp->DistanceToTarget(ent1, ent4)); TS_ASSERT_EQUALS(fixed::FromInt(6), cmp->DistanceToTarget(ent4, ent1)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(125) + 3), cmp->MaxDistanceToTarget(ent1, ent4), fixed::FromFloat(0.0001)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(125) + 3), cmp->MaxDistanceToTarget(ent4, ent1), fixed::FromFloat(0.0001)); TS_ASSERT_EQUALS(fixed::FromInt(7), cmp->DistanceToTarget(ent1, ent5)); TS_ASSERT_EQUALS(fixed::FromInt(7), cmp->DistanceToTarget(ent5, ent1)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(178)), cmp->MaxDistanceToTarget(ent1, ent5), fixed::FromFloat(0.0001)); TS_ASSERT_DELTA(fixed::FromFloat(std::sqrt(178)), cmp->MaxDistanceToTarget(ent5, ent1), fixed::FromFloat(0.0001)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent2, fixed::Zero(), fixed::FromInt(1), true)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent2, fixed::Zero(), fixed::FromInt(1), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent2, fixed::FromInt(1), fixed::FromInt(1), true)); TS_ASSERT(!cmp->IsInTargetRange(ent1, ent2, fixed::FromInt(1), fixed::FromInt(1), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::Zero(), fixed::FromInt(10), true)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::Zero(), fixed::FromInt(10), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(1), fixed::FromInt(10), true)); TS_ASSERT(!cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(1), fixed::FromInt(5), false)); TS_ASSERT(!cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(10), fixed::FromInt(10), false)); TS_ASSERT(cmp->IsInTargetRange(ent1, ent5, fixed::FromInt(10), fixed::FromInt(10), true)); } };