Index: ps/trunk/binaries/data/mods/public/maps/random/rmgen-common/player.js =================================================================== --- ps/trunk/binaries/data/mods/public/maps/random/rmgen-common/player.js (revision 21623) +++ ps/trunk/binaries/data/mods/public/maps/random/rmgen-common/player.js (revision 21624) @@ -1,786 +1,789 @@ /** * @file These functions locate and place the starting entities of players. */ var g_NomadTreasureTemplates = { "food": "gaia/treasure/food_jars", "wood": "gaia/treasure/wood", "stone": "gaia/treasure/stone", "metal": "gaia/treasure/metal" }; /** * These are identifiers of functions that can generate parts of a player base. * There must be a function starting with placePlayerBase and ending with this name. * This is a global so mods can extend this from external files. */ var g_PlayerBaseFunctions = [ // Possibly mark player class first here and use it afterwards "CityPatch", // Create the largest and most important entities first "Trees", "Mines", "Treasures", "Berries", "Chicken", "Decoratives" ]; function isNomad() { return !!g_MapSettings.Nomad; } function getNumPlayers() { return g_MapSettings.PlayerData.length - 1; } function getCivCode(playerID) { return g_MapSettings.PlayerData[playerID].Civ; } function areAllies(playerID1, playerID2) { return g_MapSettings.PlayerData[playerID1].Team !== undefined && g_MapSettings.PlayerData[playerID2].Team !== undefined && g_MapSettings.PlayerData[playerID1].Team != -1 && g_MapSettings.PlayerData[playerID2].Team != -1 && g_MapSettings.PlayerData[playerID1].Team === g_MapSettings.PlayerData[playerID2].Team; } function getPlayerTeam(playerID) { if (g_MapSettings.PlayerData[playerID].Team === undefined) return -1; return g_MapSettings.PlayerData[playerID].Team; } /** * Gets the default starting entities for the civ of the given player, as defined by the civ file. */ function getStartingEntities(playerID) { return g_CivData[getCivCode(playerID)].StartEntities; } /** * Places the given entities at the given location (typically a civic center and starting units). * @param location - A Vector2D specifying tile coordinates. * @param civEntities - An array of objects with the Template property and optionally a Count property. * The first entity is placed in the center, the other ones surround it. */ function placeStartingEntities(location, playerID, civEntities, dist = 6, orientation = BUILDING_ORIENTATION) { // Place the central structure let i = 0; let firstTemplate = civEntities[i].Template; if (firstTemplate.startsWith("structures/")) { g_Map.placeEntityPassable(firstTemplate, playerID, location, orientation); ++i; } // Place entities surrounding it let space = 2; for (let j = i; j < civEntities.length; ++j) { let angle = orientation - Math.PI * (1 - j / 2); let count = civEntities[j].Count || 1; for (let num = 0; num < count; ++num) { let position = Vector2D.sum([ location, new Vector2D(dist, 0).rotate(-angle), new Vector2D(space * (-num + (count - 1) / 2), 0).rotate(angle) ]); g_Map.placeEntityPassable(civEntities[j].Template, playerID, position, angle); } } } /** * Places the default starting entities as defined by the civilization definition, optionally including city walls. */ function placeCivDefaultStartingEntities(position, playerID, wallType, dist = 6, orientation = BUILDING_ORIENTATION) { placeStartingEntities(position, playerID, getStartingEntities(playerID), dist, orientation); placeStartingWalls(position, playerID, wallType, orientation); } /** * If the map is large enough and the civilization defines them, places the initial city walls or towers. * @param {string|boolean} wallType - Either "towers" to only place the wall turrets or a boolean indicating enclosing city walls. */ function placeStartingWalls(position, playerID, wallType, orientation = BUILDING_ORIENTATION) { let civ = getCivCode(playerID); if (civ != "iber" || g_Map.getSize() <= 128) return; + // TODO: should prevent trees inside walls + // When fixing, remove the DeleteUponConstruction flag from template_gaia_flora.xml + if (wallType == "towers") placePolygonalWall(position, 15, ["entry"], "tower", civ, playerID, orientation, 7); else if (wallType) placeGenericFortress(position, 20, playerID); } /** * Places the civic center and starting resources for all given players. */ function placePlayerBases(playerBaseArgs) { g_Map.log("Creating playerbases"); let [playerIDs, playerPosition] = playerBaseArgs.PlayerPlacement; for (let i = 0; i < getNumPlayers(); ++i) { playerBaseArgs.playerID = playerIDs[i]; playerBaseArgs.playerPosition = playerPosition[i]; placePlayerBase(playerBaseArgs); } } /** * Places the civic center and starting resources. */ function placePlayerBase(playerBaseArgs) { if (isNomad()) return; placeCivDefaultStartingEntities(playerBaseArgs.playerPosition, playerBaseArgs.playerID, playerBaseArgs.Walls !== undefined ? playerBaseArgs.Walls : true); if (playerBaseArgs.PlayerTileClass) addCivicCenterAreaToClass(playerBaseArgs.playerPosition, playerBaseArgs.PlayerTileClass); for (let functionID of g_PlayerBaseFunctions) { let funcName = "placePlayerBase" + functionID; let func = global[funcName]; if (!func) throw new Error("Could not find " + funcName); if (!playerBaseArgs[functionID]) continue; let args = playerBaseArgs[functionID]; // Copy some global arguments to the arguments for each function for (let prop of ["playerID", "playerPosition", "BaseResourceClass", "baseResourceConstraint"]) args[prop] = playerBaseArgs[prop]; func(args); } } function defaultPlayerBaseRadius() { return scaleByMapSize(15, 25); } /** * Marks the corner and center tiles of an area that is about the size of a Civic Center with the given TileClass. * Used to prevent resource collisions with the Civic Center. */ function addCivicCenterAreaToClass(position, tileClass) { createArea( new DiskPlacer(5, position), new TileClassPainter(tileClass)); } /** * Helper function. */ function getPlayerBaseArgs(playerBaseArgs) { let baseResourceConstraint = playerBaseArgs.BaseResourceClass && avoidClasses(playerBaseArgs.BaseResourceClass, 4); if (playerBaseArgs.baseResourceConstraint) baseResourceConstraint = new AndConstraint([baseResourceConstraint, playerBaseArgs.baseResourceConstraint]); return [ (property, defaultVal) => playerBaseArgs[property] === undefined ? defaultVal : playerBaseArgs[property], playerBaseArgs.playerPosition, baseResourceConstraint ]; } function placePlayerBaseCityPatch(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); let painters = []; if (args.outerTerrain && args.innerTerrain) painters.push(new LayeredPainter([args.outerTerrain, args.innerTerrain], [get("width", 1)])); if (args.painters) painters = painters.concat(args.painters); createArea( new ClumpPlacer( Math.floor(diskArea(get("radius", defaultPlayerBaseRadius() / 3))), get("coherence", 0.6), get("smoothness", 0.3), get("failFraction", Infinity), basePosition), painters); } function placePlayerBaseChicken(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); for (let i = 0; i < get("groupCount", 2); ++i) { let success = false; for (let tries = 0; tries < get("maxTries", 30); ++tries) { let position = new Vector2D(0, get("distance", 9)).rotate(randomAngle()).add(basePosition); if (createObjectGroup( new SimpleGroup( [ new SimpleObject( get("template", "gaia/fauna_chicken"), get("minGroupCount", 5), get("maxGroupCount", 5), get("minGroupDistance", 0), get("maxGroupDistance", 2)) ], true, args.BaseResourceClass, position), 0, baseResourceConstraint)) { success = true; break; } } if (!success) { error("Could not place chicken for player " + args.playerID); return; } } } function placePlayerBaseBerries(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); for (let tries = 0; tries < get("maxTries", 30); ++tries) { let position = new Vector2D(0, get("distance", 12)).rotate(randomAngle()).add(basePosition); if (createObjectGroup( new SimpleGroup( [new SimpleObject(args.template, get("minCount", 5), get("maxCount", 5), get("maxDist", 1), get("maxDist", 3))], true, args.BaseResourceClass, position), 0, baseResourceConstraint)) return; } error("Could not place berries for player " + args.playerID); } function placePlayerBaseMines(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); let angleBetweenMines = randFloat(get("minAngle", Math.PI / 6), get("maxAngle", Math.PI / 3)); let mineCount = args.types.length; let groupElements = []; if (args.groupElements) groupElements = groupElements.concat(args.groupElements); for (let tries = 0; tries < get("maxTries", 75); ++tries) { // First find a place where all mines can be placed let pos = []; let startAngle = randomAngle(); for (let i = 0; i < mineCount; ++i) { let angle = startAngle + angleBetweenMines * (i + (mineCount - 1) / 2); pos[i] = new Vector2D(0, get("distance", 12)).rotate(angle).add(basePosition).round(); if (!g_Map.validTilePassable(pos[i]) || !baseResourceConstraint.allows(pos[i])) { pos = undefined; break; } } if (!pos) continue; // Place the mines for (let i = 0; i < mineCount; ++i) { if (args.types[i].type && args.types[i].type == "stone_formation") { createStoneMineFormation(pos[i], args.types[i].template, args.types[i].terrain); args.BaseResourceClass.add(pos[i]); continue; } createObjectGroup( new SimpleGroup( [new SimpleObject(args.types[i].template, 1, 1, 0, 0)].concat(groupElements), true, args.BaseResourceClass, pos[i]), 0); } return; } error("Could not place mines for player " + args.playerID); } function placePlayerBaseTrees(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); let num = Math.floor(get("count", scaleByMapSize(7, 20))); for (let x = 0; x < get("maxTries", 30); ++x) { let position = new Vector2D(0, randFloat(get("minDist", 11), get("maxDist", 13))).rotate(randomAngle()).add(basePosition).round(); if (createObjectGroup( new SimpleGroup( [new SimpleObject(args.template, num, num, get("minDistGroup", 0), get("maxDistGroup", 5))], false, args.BaseResourceClass, position), 0, baseResourceConstraint)) return; } error("Could not place starting trees for player " + args.playerID); } function placePlayerBaseTreasures(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); for (let resourceTypeArgs of args.types) { get = (property, defaultVal) => resourceTypeArgs[property] === undefined ? defaultVal : resourceTypeArgs[property]; let success = false; for (let tries = 0; tries < get("maxTries", 30); ++tries) { let position = new Vector2D(0, randFloat(get("minDist", 11), get("maxDist", 13))).rotate(randomAngle()).add(basePosition).round(); if (createObjectGroup( new SimpleGroup( [new SimpleObject(resourceTypeArgs.template, get("count", 14), get("count", 14), get("minDistGroup", 1), get("maxDistGroup", 3))], false, args.BaseResourceClass, position), 0, baseResourceConstraint)) { success = true; break; } } if (!success) { error("Could not place treasure " + resourceTypeArgs.template + " for player " + args.playerID); return; } } } /** * Typically used for placing grass tufts around the civic centers. */ function placePlayerBaseDecoratives(args) { let [get, basePosition, baseResourceConstraint] = getPlayerBaseArgs(args); for (let i = 0; i < get("count", scaleByMapSize(2, 5)); ++i) { let success = false; for (let x = 0; x < get("maxTries", 30); ++x) { let position = new Vector2D(0, randIntInclusive(get("minDist", 8), get("maxDist", 11))).rotate(randomAngle()).add(basePosition).round(); if (createObjectGroup( new SimpleGroup( [new SimpleObject(args.template, get("minCount", 2), get("maxCount", 5), 0, 1)], false, args.BaseResourceClass, position), 0, baseResourceConstraint)) { success = true; break; } } if (!success) // Don't warn since the decoratives are not important return; } } function placePlayersNomad(playerClass, constraints) { if (!isNomad()) return undefined; g_Map.log("Placing nomad starting units"); let distance = scaleByMapSize(60, 240); let constraint = new StaticConstraint(constraints); let numPlayers = getNumPlayers(); let playerIDs = shuffleArray(sortAllPlayers()); let playerPosition = []; for (let i = 0; i < numPlayers; ++i) { let objects = getStartingEntities(playerIDs[i]).filter(ents => ents.Template.startsWith("units/")).map( ents => new SimpleObject(ents.Template, ents.Count || 1, ents.Count || 1, 1, 3)); // Add treasure if too few resources for a civic center let ccCost = Engine.GetTemplate("structures/" + getCivCode(playerIDs[i]) + "_civil_centre").Cost.Resources; for (let resourceType in ccCost) { let treasureTemplate = g_NomadTreasureTemplates[resourceType]; let count = Math.max(0, Math.ceil( (ccCost[resourceType] - (g_MapSettings.StartingResources || 0)) / Engine.GetTemplate(treasureTemplate).ResourceSupply.Amount)); objects.push(new SimpleObject(treasureTemplate, count, count, 3, 5)); } // Try place these entities at a random location let group = new SimpleGroup(objects, true, playerClass); let success = false; for (let distanceFactor of [1, 1/2, 1/4, 0]) if (createObjectGroups(group, playerIDs[i], new AndConstraint([constraint, avoidClasses(playerClass, distance * distanceFactor)]), 1, 200, false).length) { success = true; playerPosition[i] = group.centerPosition; break; } if (!success) throw new Error("Could not place starting units for player " + playerIDs[i] + "!"); } return [playerIDs, playerPosition]; } /** * Sorts an array of player IDs by team index. Players without teams come first. * Randomize order for players of the same team. */ function sortPlayers(playerIDs) { return shuffleArray(playerIDs).sort((playerID1, playerID2) => getPlayerTeam(playerID1) - getPlayerTeam(playerID2)); } /** * Randomize playerIDs but sort by team. * * @returns {Array} - every item is an array of player indices */ function sortAllPlayers() { let playerIDs = []; for (let i = 0; i < getNumPlayers(); ++i) playerIDs.push(i+1); return sortPlayers(playerIDs); } /** * Rearrange order so that teams of neighboring players alternate (if the given IDs are sorted by team). */ function primeSortPlayers(playerIDs) { let prime = []; for (let i = 0; i < Math.floor(playerIDs.length / 2); ++i) { prime.push(playerIDs[i]); prime.push(playerIDs[playerIDs.length - 1 - i]); } if (playerIDs.length % 2) prime.push(playerIDs[Math.floor(playerIDs.length / 2)]); return prime; } function primeSortAllPlayers() { return primeSortPlayers(sortAllPlayers()); } /** * Determine player starting positions on a circular pattern. */ function playerPlacementCircle(radius, startingAngle = undefined, center = undefined) { let startAngle = startingAngle !== undefined ? startingAngle : randomAngle(); let [playerPosition, playerAngle] = distributePointsOnCircle(getNumPlayers(), startAngle, radius, center || g_Map.getCenter()); return [sortAllPlayers(), playerPosition.map(p => p.round()), playerAngle, startAngle]; } /** * Determine player starting positions on a circular pattern, with a custom angle for each player. * Commonly used for gulf terrains. */ function playerPlacementCustomAngle(radius, center, playerAngleFunc) { let playerPosition = []; let playerAngle = []; let numPlayers = getNumPlayers(); for (let i = 0; i < numPlayers; ++i) { playerAngle[i] = playerAngleFunc(i); playerPosition[i] = Vector2D.add(center, new Vector2D(radius, 0).rotate(-playerAngle[i])).round(); } return [playerPosition, playerAngle]; } /** * Returns player starting positions located on two parallel lines, typically used by central river maps. * If there are two teams with an equal number of players, each team will occupy exactly one line. * Angle 0 means the players are placed in north to south direction, i.e. along the Z axis. */ function playerPlacementRiver(angle, width, center = undefined) { let numPlayers = getNumPlayers(); let numPlayersEven = numPlayers % 2 == 0; let mapSize = g_Map.getSize(); let centerPosition = center || g_Map.getCenter(); let playerPosition = []; for (let i = 0; i < numPlayers; ++i) { let currentPlayerEven = i % 2 == 0; let offsetDivident = numPlayersEven || currentPlayerEven ? (i + 1) % 2 : 0; let offsetDivisor = numPlayersEven ? 0 : currentPlayerEven ? +1 : -1; playerPosition[i] = new Vector2D( width * (i % 2) + (mapSize - width) / 2, fractionToTiles(((i - 1 + offsetDivident) / 2 + 1) / ((numPlayers + offsetDivisor) / 2 + 1)) ).rotateAround(angle, centerPosition).round(); } return [primeSortAllPlayers(), playerPosition]; } /** * Returns starting positions located on two parallel lines. * The locations on the first line are shifted in comparison to the other line. */ function playerPlacementLine(angle, center, width) { let playerPosition = []; let numPlayers = getNumPlayers(); for (let i = 0; i < numPlayers; ++i) playerPosition[i] = Vector2D.add( center, new Vector2D( fractionToTiles((i + 1) / (numPlayers + 1) - 0.5), width * (i % 2 - 1/2) ).rotate(angle) ).round(); return playerPosition; } /** * Returns a random location for each player that meets the given constraints and * orders the playerIDs so that players become grouped by team. */ function playerPlacementRandom(playerIDs, constraints = undefined) { let locations = []; let attempts = 0; let resets = 0; let mapCenter = g_Map.getCenter(); let playerMinDistSquared = Math.square(fractionToTiles(0.25)); let borderDistance = fractionToTiles(0.08); let area = createArea(new MapBoundsPlacer(), undefined, new AndConstraint(constraints)); for (let i = 0; i < getNumPlayers(); ++i) { let position = pickRandom(area.getPoints()); // Minimum distance between initial bases must be a quarter of the map diameter if (locations.some(loc => loc.distanceToSquared(position) < playerMinDistSquared) || position.distanceToSquared(mapCenter) > Math.square(mapCenter.x - borderDistance)) { --i; ++attempts; // Reset if we're in what looks like an infinite loop if (attempts > 500) { locations = []; i = -1; attempts = 0; ++resets; // Reduce minimum player distance progressively if (resets % 25 == 0) playerMinDistSquared *= 0.95; // If we only pick bad locations, stop trying to place randomly if (resets == 500) return undefined; } continue; } locations[i] = position; } return groupPlayersByArea(playerIDs, locations); } /** * Pick locations from the given set so that teams end up grouped. */ function groupPlayersByArea(playerIDs, locations) { playerIDs = sortPlayers(playerIDs); let minDist = Infinity; let minLocations; // Of all permutations of starting locations, find the one where // the sum of the distances between allies is minimal, weighted by teamsize. heapsPermute(shuffleArray(locations).slice(0, playerIDs.length), v => v.clone(), permutation => { let dist = 0; let teamDist = 0; let teamSize = 0; for (let i = 1; i < playerIDs.length; ++i) { let team1 = getPlayerTeam(playerIDs[i - 1]); let team2 = getPlayerTeam(playerIDs[i]); ++teamSize; if (team1 != -1 && team1 == team2) teamDist += permutation[i - 1].distanceTo(permutation[i]); else { dist += teamDist / teamSize; teamDist = 0; teamSize = 0; } } if (teamSize) dist += teamDist / teamSize; if (dist < minDist) { minDist = dist; minLocations = permutation; } }); return [playerIDs, minLocations]; } /** * Sorts the playerIDs so that team members are as close as possible on a ring. */ function groupPlayersCycle(startLocations) { let startLocationOrder = sortPointsShortestCycle(startLocations); let newStartLocations = []; for (let i = 0; i < startLocations.length; ++i) newStartLocations.push(startLocations[startLocationOrder[i]]); startLocations = newStartLocations; // Sort players by team let playerIDs = []; let teams = []; for (let i = 0; i < g_MapSettings.PlayerData.length - 1; ++i) { playerIDs.push(i+1); let t = g_MapSettings.PlayerData[i + 1].Team; if (teams.indexOf(t) == -1 && t !== undefined) teams.push(t); } playerIDs = sortPlayers(playerIDs); if (!teams.length) return [playerIDs, startLocations]; // Minimize maximum distance between players within a team let minDistance = Infinity; let bestShift; for (let s = 0; s < playerIDs.length; ++s) { let maxTeamDist = 0; for (let pi = 0; pi < playerIDs.length - 1; ++pi) { let t1 = getPlayerTeam(playerIDs[(pi + s) % playerIDs.length]); if (teams.indexOf(t1) === -1) continue; for (let pj = pi + 1; pj < playerIDs.length; ++pj) { if (t1 != getPlayerTeam(playerIDs[(pj + s) % playerIDs.length])) continue; maxTeamDist = Math.max( maxTeamDist, Math.euclidDistance2D( startLocations[pi].x, startLocations[pi].y, startLocations[pj].x, startLocations[pj].y)); } } if (maxTeamDist < minDistance) { minDistance = maxTeamDist; bestShift = s; } } if (bestShift) { let newPlayerIDs = []; for (let i = 0; i < playerIDs.length; ++i) newPlayerIDs.push(playerIDs[(i + bestShift) % playerIDs.length]); playerIDs = newPlayerIDs; } return [playerIDs, startLocations]; } Index: ps/trunk/binaries/data/mods/public/simulation/components/Foundation.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/Foundation.js (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/components/Foundation.js (revision 21624) @@ -1,434 +1,425 @@ function Foundation() {} Foundation.prototype.Schema = ""; Foundation.prototype.Init = function() { // Foundations are initially 'uncommitted' and do not block unit movement at all // (to prevent players exploiting free foundations to confuse enemy units). // The first builder to reach the uncommitted foundation will tell friendly units // and animals to move out of the way, then will commit the foundation and enable // its obstruction once there's nothing in the way. this.committed = false; this.builders = new Map(); // Map of builder entities to their work per second this.totalBuilderRate = 0; // Total amount of work the builders do each second this.buildMultiplier = 1; // Multiplier for the amount of work builders do this.buildTimePenalty = 0.7; // Penalty for having multiple builders this.previewEntity = INVALID_ENTITY; }; Foundation.prototype.InitialiseConstruction = function(owner, template) { this.finalTemplateName = template; // We need to know the owner in OnDestroy, but at that point the entity has already been // decoupled from its owner, so we need to remember it in here (and assume it won't change) this.owner = owner; // Remember the cost here, so if it changes after construction begins (from auras or technologies) // we will use the correct values to refund partial construction costs let cmpCost = Engine.QueryInterface(this.entity, IID_Cost); if (!cmpCost) error("A foundation must have a cost component to know the build time"); this.costs = cmpCost.GetResourceCosts(owner); this.maxProgress = 0; this.initialised = true; }; /** * Moving the revelation logic from Build to here makes the building sink if * it is attacked. */ Foundation.prototype.OnHealthChanged = function(msg) { // Gradually reveal the final building preview var cmpPosition = Engine.QueryInterface(this.previewEntity, IID_Position); if (cmpPosition) cmpPosition.SetConstructionProgress(this.GetBuildProgress()); Engine.PostMessage(this.entity, MT_FoundationProgressChanged, { "to": this.GetBuildPercentage() }); }; /** * Returns the current build progress in a [0,1] range. */ Foundation.prototype.GetBuildProgress = function() { var cmpHealth = Engine.QueryInterface(this.entity, IID_Health); if (!cmpHealth) return 0; var hitpoints = cmpHealth.GetHitpoints(); var maxHitpoints = cmpHealth.GetMaxHitpoints(); return hitpoints / maxHitpoints; }; Foundation.prototype.GetBuildPercentage = function() { return Math.floor(this.GetBuildProgress() * 100); }; Foundation.prototype.GetNumBuilders = function() { return this.builders.size; }; Foundation.prototype.IsFinished = function() { return (this.GetBuildProgress() == 1.0); }; Foundation.prototype.OnDestroy = function() { // Refund a portion of the construction cost, proportional to the amount of build progress remaining if (!this.initialised) // this happens if the foundation was destroyed because the player had insufficient resources return; if (this.previewEntity != INVALID_ENTITY) { Engine.DestroyEntity(this.previewEntity); this.previewEntity = INVALID_ENTITY; } if (this.IsFinished()) return; let cmpPlayer = QueryPlayerIDInterface(this.owner); for (var r in this.costs) { var scaled = Math.ceil(this.costs[r] * (1.0 - this.maxProgress)); if (scaled) { cmpPlayer.AddResource(r, scaled); var cmpStatisticsTracker = QueryPlayerIDInterface(this.owner, IID_StatisticsTracker); if (cmpStatisticsTracker) cmpStatisticsTracker.IncreaseResourceUsedCounter(r, -scaled); } } }; /** * Adds a builder to the counter. */ Foundation.prototype.AddBuilder = function(builderEnt) { if (this.builders.has(builderEnt)) return; this.builders.set(builderEnt, Engine.QueryInterface(builderEnt, IID_Builder).GetRate()); this.totalBuilderRate += this.builders.get(builderEnt); this.SetBuildMultiplier(); let cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpVisual) cmpVisual.SetVariable("numbuilders", this.builders.size); Engine.PostMessage(this.entity, MT_FoundationBuildersChanged, { "to": Array.from(this.builders.keys()) }); }; Foundation.prototype.RemoveBuilder = function(builderEnt) { if (!this.builders.has(builderEnt)) return; this.totalBuilderRate -= this.builders.get(builderEnt); this.builders.delete(builderEnt); this.SetBuildMultiplier(); let cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpVisual) cmpVisual.SetVariable("numbuilders", this.builders.size); Engine.PostMessage(this.entity, MT_FoundationBuildersChanged, { "to": Array.from(this.builders.keys()) }); }; /** * The build multiplier is a penalty that is applied to each builder. * For example, ten women build at a combined rate of 10^0.7 = 5.01 instead of 10. */ Foundation.prototype.CalculateBuildMultiplier = function(num) { // Avoid division by zero, in particular 0/0 = NaN which isn't reliably serialized return num < 2 ? 1 : Math.pow(num, this.buildTimePenalty) / num; }; Foundation.prototype.SetBuildMultiplier = function() { this.buildMultiplier = this.CalculateBuildMultiplier(this.GetNumBuilders()); }; Foundation.prototype.GetBuildTime = function() { let timeLeft = (1 - this.GetBuildProgress()) * Engine.QueryInterface(this.entity, IID_Cost).GetBuildTime(); let rate = this.totalBuilderRate * this.buildMultiplier; // The rate if we add another woman to the foundation. let rateNew = (this.totalBuilderRate + 1) * this.CalculateBuildMultiplier(this.GetNumBuilders() + 1); return { // Avoid division by zero, in particular 0/0 = NaN which isn't reliably serialized "timeRemaining": rate ? timeLeft / rate : 0, "timeRemainingNew": timeLeft / rateNew }; }; /** * Perform some number of seconds of construction work. * Returns true if the construction is completed. */ Foundation.prototype.Build = function(builderEnt, work) { // Do nothing if we've already finished building // (The entity will be destroyed soon after completion so // this won't happen much) if (this.GetBuildProgress() == 1.0) return; - // If there's any units in the way, ask them to move away - // and return early from this method. var cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); + // If there are any units in the way, ask them to move away and return early from this method. if (cmpObstruction && cmpObstruction.GetBlockMovementFlag()) { - // Remove all obstructions at the new entity, especially animal corpses - let collisions = cmpObstruction.GetEntityCollisions(); + // Remove animal corpses + for (let ent of cmpObstruction.GetEntitiesDeletedUponConstruction()) + Engine.DestroyEntity(ent); + let collisions = cmpObstruction.GetEntitiesBlockingConstruction(); if (collisions.length) { - var cmpFoundationOwnership = Engine.QueryInterface(this.entity, IID_Ownership); for (var ent of collisions) { var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI); if (cmpUnitAI) cmpUnitAI.LeaveFoundation(this.entity); - else - { - // If obstructing fauna is gaia or our own but doesn't have UnitAI, just destroy it - var cmpOwnership = Engine.QueryInterface(ent, IID_Ownership); - var cmpIdentity = Engine.QueryInterface(ent, IID_Identity); - if (cmpOwnership && cmpIdentity && cmpIdentity.HasClass("Animal") - && (cmpOwnership.GetOwner() == 0 || cmpFoundationOwnership && cmpOwnership.GetOwner() == cmpFoundationOwnership.GetOwner())) - Engine.DestroyEntity(ent); - } // TODO: What if an obstruction has no UnitAI? } // TODO: maybe we should tell the builder to use a special // animation to indicate they're waiting for people to get // out the way return; } } // Handle the initial 'committing' of the foundation if (!this.committed) { // The obstruction always blocks new foundations/construction, // but we've temporarily allowed units to walk all over it // (via CCmpTemplateManager). Now we need to remove that temporary // blocker-disabling, so that we'll perform standard unit blocking instead. if (cmpObstruction && cmpObstruction.GetBlockMovementFlag()) cmpObstruction.SetDisableBlockMovementPathfinding(false, false, -1); // Call the related trigger event var cmpTrigger = Engine.QueryInterface(SYSTEM_ENTITY, IID_Trigger); cmpTrigger.CallEvent("ConstructionStarted", { "foundation": this.entity, "template": this.finalTemplateName }); // Switch foundation to scaffold variant var cmpFoundationVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpFoundationVisual) cmpFoundationVisual.SelectAnimation("scaffold", false, 1.0); // Create preview entity and copy various parameters from the foundation if (cmpFoundationVisual && cmpFoundationVisual.HasConstructionPreview()) { this.previewEntity = Engine.AddEntity("construction|"+this.finalTemplateName); var cmpFoundationOwnership = Engine.QueryInterface(this.entity, IID_Ownership); var cmpPreviewOwnership = Engine.QueryInterface(this.previewEntity, IID_Ownership); cmpPreviewOwnership.SetOwner(cmpFoundationOwnership.GetOwner()); // Initially hide the preview underground var cmpPreviewPosition = Engine.QueryInterface(this.previewEntity, IID_Position); cmpPreviewPosition.SetConstructionProgress(0.0); var cmpPreviewVisual = Engine.QueryInterface(this.previewEntity, IID_Visual); if (cmpPreviewVisual) { cmpPreviewVisual.SetActorSeed(cmpFoundationVisual.GetActorSeed()); cmpPreviewVisual.SelectAnimation("scaffold", false, 1.0, ""); } var cmpFoundationPosition = Engine.QueryInterface(this.entity, IID_Position); var pos = cmpFoundationPosition.GetPosition2D(); var rot = cmpFoundationPosition.GetRotation(); cmpPreviewPosition.SetYRotation(rot.y); cmpPreviewPosition.SetXZRotation(rot.x, rot.z); cmpPreviewPosition.JumpTo(pos.x, pos.y); } this.committed = true; } // Add an appropriate proportion of hitpoints var cmpHealth = Engine.QueryInterface(this.entity, IID_Health); if (!cmpHealth) { error("Foundation " + this.entity + " does not have a health component."); return; } var deltaHP = work * this.GetBuildRate() * this.buildMultiplier; if (deltaHP > 0) cmpHealth.Increase(deltaHP); // Update the total builder rate this.totalBuilderRate += work - this.builders.get(builderEnt); this.builders.set(builderEnt, work); var progress = this.GetBuildProgress(); // Remember our max progress for partial refund in case of destruction this.maxProgress = Math.max(this.maxProgress, progress); if (progress >= 1.0) { // Finished construction // Create the real entity var building = Engine.AddEntity(this.finalTemplateName); // Copy various parameters from the foundation var cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); var cmpBuildingVisual = Engine.QueryInterface(building, IID_Visual); if (cmpVisual && cmpBuildingVisual) cmpBuildingVisual.SetActorSeed(cmpVisual.GetActorSeed()); var cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (!cmpPosition || !cmpPosition.IsInWorld()) { error("Foundation " + this.entity + " does not have a position in-world."); Engine.DestroyEntity(building); return; } var cmpBuildingPosition = Engine.QueryInterface(building, IID_Position); if (!cmpBuildingPosition) { error("New building " + building + " has no position component."); Engine.DestroyEntity(building); return; } var pos = cmpPosition.GetPosition2D(); cmpBuildingPosition.JumpTo(pos.x, pos.y); var rot = cmpPosition.GetRotation(); cmpBuildingPosition.SetYRotation(rot.y); cmpBuildingPosition.SetXZRotation(rot.x, rot.z); // TODO: should add a ICmpPosition::CopyFrom() instead of all this var cmpRallyPoint = Engine.QueryInterface(this.entity, IID_RallyPoint); var cmpBuildingRallyPoint = Engine.QueryInterface(building, IID_RallyPoint); if(cmpRallyPoint && cmpBuildingRallyPoint) { var rallyCoords = cmpRallyPoint.GetPositions(); var rallyData = cmpRallyPoint.GetData(); for (var i = 0; i < rallyCoords.length; ++i) { cmpBuildingRallyPoint.AddPosition(rallyCoords[i].x, rallyCoords[i].z); cmpBuildingRallyPoint.AddData(rallyData[i]); } } // ---------------------------------------------------------------------- var owner; var cmpTerritoryDecay = Engine.QueryInterface(building, IID_TerritoryDecay); if (cmpTerritoryDecay && cmpTerritoryDecay.HasTerritoryOwnership()) { let cmpTerritoryManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TerritoryManager); owner = cmpTerritoryManager.GetOwner(pos.x, pos.y); } else { let cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership); if (!cmpOwnership) { error("Foundation " + this.entity + " has no ownership."); Engine.DestroyEntity(building); return; } owner = cmpOwnership.GetOwner(); } var cmpBuildingOwnership = Engine.QueryInterface(building, IID_Ownership); if (!cmpBuildingOwnership) { error("New Building " + building + " has no ownership."); Engine.DestroyEntity(building); return; } cmpBuildingOwnership.SetOwner(owner); /* Copy over the obstruction control group IDs from the foundation entities. This is needed to ensure that when a foundation is completed and replaced by a new entity, it remains in the same control group(s) as any other foundation entities that may surround it. This is the mechanism that is used to e.g. enable wall pieces to be built closely together, ignoring their mutual obstruction shapes (since they would otherwise be prevented from being built so closely together). If the control groups are not copied over, the new entity will default to a new control group containing only itself, and will hence block construction of any surrounding foundations that it was previously in the same control group with. Note that this will result in the completed building entities having control group IDs that equal entity IDs of old (and soon to be deleted) foundation entities. This should not have any consequences, however, since the control group IDs are only meant to be unique identifiers, which is still true when reusing the old ones. */ var cmpBuildingObstruction = Engine.QueryInterface(building, IID_Obstruction); if (cmpObstruction && cmpBuildingObstruction) { cmpBuildingObstruction.SetControlGroup(cmpObstruction.GetControlGroup()); cmpBuildingObstruction.SetControlGroup2(cmpObstruction.GetControlGroup2()); } var cmpPlayerStatisticsTracker = QueryOwnerInterface(this.entity, IID_StatisticsTracker); if (cmpPlayerStatisticsTracker) cmpPlayerStatisticsTracker.IncreaseConstructedBuildingsCounter(building); var cmpBuildingHealth = Engine.QueryInterface(building, IID_Health); if (cmpBuildingHealth) cmpBuildingHealth.SetHitpoints(cmpHealth.GetHitpoints()); PlaySound("constructed", building); Engine.PostMessage(this.entity, MT_ConstructionFinished, { "entity": this.entity, "newentity": building }); Engine.PostMessage(this.entity, MT_EntityRenamed, { "entity": this.entity, "newentity": building }); Engine.DestroyEntity(this.entity); } }; Foundation.prototype.GetBuildRate = function() { let cmpHealth = Engine.QueryInterface(this.entity, IID_Health); let cmpCost = Engine.QueryInterface(this.entity, IID_Cost); // Return infinity for instant structure conversion return cmpHealth.GetMaxHitpoints() / cmpCost.GetBuildTime(); }; Engine.RegisterComponentType(IID_Foundation, "Foundation", Foundation); Index: ps/trunk/binaries/data/mods/public/simulation/components/Gate.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/Gate.js (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/components/Gate.js (revision 21624) @@ -1,244 +1,249 @@ function Gate() {} Gate.prototype.Schema = "Controls behavior of wall gates" + "" + "20" + "" + "" + "" + ""; /** * Initialize Gate component */ Gate.prototype.Init = function() { this.allies = []; this.opened = false; this.locked = false; }; Gate.prototype.OnOwnershipChanged = function(msg) { if (msg.to != INVALID_PLAYER) { this.SetupRangeQuery(msg.to); // Set the initial state, but don't play unlocking sound if (!this.locked) this.UnlockGate(true); } }; Gate.prototype.OnDiplomacyChanged = function(msg) { var cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership); if (cmpOwnership && cmpOwnership.GetOwner() == msg.player) { this.allies = []; this.SetupRangeQuery(msg.player); } }; /** * Cleanup on destroy */ Gate.prototype.OnDestroy = function() { // Clean up range query var cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); if (this.unitsQuery) cmpRangeManager.DestroyActiveQuery(this.unitsQuery); // Cancel the closing-blocked timer if it's running. if (this.timer) { var cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); cmpTimer.CancelTimer(this.timer); this.timer = undefined; } }; /** * Setup the range query to detect units coming in & out of range */ Gate.prototype.SetupRangeQuery = function(owner) { var cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); if (this.unitsQuery) cmpRangeManager.DestroyActiveQuery(this.unitsQuery); // Only allied units can make the gate open. var players = QueryPlayerIDInterface(owner).GetAllies(); var range = this.GetPassRange(); if (range > 0) { // Only find entities with IID_UnitAI interface this.unitsQuery = cmpRangeManager.CreateActiveQuery(this.entity, 0, range, players, IID_UnitAI, cmpRangeManager.GetEntityFlagMask("normal")); cmpRangeManager.EnableActiveQuery(this.unitsQuery); } }; /** * Called when units enter or leave range */ Gate.prototype.OnRangeUpdate = function(msg) { if (msg.tag != this.unitsQuery) return; if (msg.added.length > 0) for (let entity of msg.added) this.allies.push(entity); if (msg.removed.length > 0) for (let entity of msg.removed) this.allies.splice(this.allies.indexOf(entity), 1); this.OperateGate(); }; /** * Get the range in which units are detected */ Gate.prototype.GetPassRange = function() { return +this.template.PassRange; }; /** * Attempt to open or close the gate. * An ally must be in range to open the gate, but an unlocked gate will only close * if there are no allies in range and no units are inside the gate's obstruction. */ Gate.prototype.OperateGate = function() { // Cancel the closing-blocked timer if it's running. if (this.timer) { var cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); cmpTimer.CancelTimer(this.timer); this.timer = undefined; } if (this.opened && (this.allies.length == 0 || this.locked)) this.CloseGate(); else if (!this.opened && this.allies.length) this.OpenGate(); }; Gate.prototype.IsLocked = function() { return this.locked; }; /** * Lock the gate, with sound. It will close at the next opportunity. */ Gate.prototype.LockGate = function() { this.locked = true; + + // Delete animal corpses to prevent units trying to gather the unreachable entity + let cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); + if (cmpObstruction && cmpObstruction.GetBlockMovementFlag()) + for (let ent of cmpObstruction.GetEntitiesDeletedUponConstruction()) + Engine.DestroyEntity(ent); + // If the door is closed, enable 'block pathfinding' // Else 'block pathfinding' will be enabled the next time the gate close if (!this.opened) { - var cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); - if (!cmpObstruction) - return; - cmpObstruction.SetDisableBlockMovementPathfinding(false, false, 0); + if (cmpObstruction) + cmpObstruction.SetDisableBlockMovementPathfinding(false, false, 0); } else this.OperateGate(); // TODO: Possibly move the lock/unlock sounds to UI? Needs testing PlaySound("gate_locked", this.entity); }; /** * Unlock the gate, with sound. May open the gate if allied units are within range. * If quiet is true, no sound will be played (used for initial setup). */ Gate.prototype.UnlockGate = function(quiet) { var cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); if (!cmpObstruction) return; // Disable 'block pathfinding' cmpObstruction.SetDisableBlockMovementPathfinding(this.opened, true, 0); this.locked = false; // TODO: Possibly move the lock/unlock sounds to UI? Needs testing if (!quiet) PlaySound("gate_unlocked", this.entity); // If the gate is closed, open it if necessary if (!this.opened) this.OperateGate(); }; /** * Open the gate if unlocked, with sound and animation. */ Gate.prototype.OpenGate = function() { // Do not open the gate if it has been locked if (this.locked) return; var cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); if (!cmpObstruction) return; // Disable 'block movement' cmpObstruction.SetDisableBlockMovementPathfinding(true, true, 0); this.opened = true; PlaySound("gate_opening", this.entity); var cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpVisual) cmpVisual.SelectAnimation("gate_opening", true, 1.0); }; /** * Close the gate, with sound and animation. * * The gate may fail to close due to unit obstruction. If this occurs, the * gate will start a timer and attempt to close on each simulation update. */ Gate.prototype.CloseGate = function() { var cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction); if (!cmpObstruction) return; // The gate can't be closed if there are entities colliding with it. - var collisions = cmpObstruction.GetUnitCollisions(); + var collisions = cmpObstruction.GetEntitiesBlockingConstruction(); if (collisions.length) { if (!this.timer) { // Set an "instant" timer which will run on the next simulation turn. var cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer); this.timer = cmpTimer.SetTimeout(this.entity, IID_Gate, "OperateGate", 0, {}); } return; } // If we ordered the gate to be locked, enable 'block movement' and 'block pathfinding' if (this.locked) cmpObstruction.SetDisableBlockMovementPathfinding(false, false, 0); // Else just enable 'block movement' else cmpObstruction.SetDisableBlockMovementPathfinding(false, true, 0); this.opened = false; PlaySound("gate_closing", this.entity); var cmpVisual = Engine.QueryInterface(this.entity, IID_Visual); if (cmpVisual) cmpVisual.SelectAnimation("gate_closing", true, 1.0); }; Engine.RegisterComponentType(IID_Gate, "Gate", Gate); Index: ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Foundation.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Foundation.js (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/components/tests/test_Foundation.js (revision 21624) @@ -1,209 +1,210 @@ Engine.LoadHelperScript("Player.js"); Engine.LoadComponentScript("interfaces/Builder.js"); Engine.LoadComponentScript("interfaces/Cost.js"); Engine.LoadComponentScript("interfaces/Foundation.js"); Engine.LoadComponentScript("interfaces/Health.js"); Engine.LoadComponentScript("interfaces/StatisticsTracker.js"); Engine.LoadComponentScript("interfaces/TerritoryDecay.js"); Engine.LoadComponentScript("interfaces/Trigger.js"); Engine.LoadComponentScript("Foundation.js"); let player = 1; let playerEnt = 3; let foundationEnt = 20; let previewEnt = 21; let newEnt = 22; function testFoundation(...mocks) { ResetState(); AddMock(SYSTEM_ENTITY, IID_Trigger, { "CallEvent": () => {}, }); AddMock(SYSTEM_ENTITY, IID_PlayerManager, { "GetPlayerByID": () => playerEnt, }); AddMock(SYSTEM_ENTITY, IID_TerritoryManager, { "GetOwner": (x, y) => { TS_ASSERT_EQUALS(x, pos.x); TS_ASSERT_EQUALS(y, pos.y); return player; }, }); Engine.RegisterGlobal("PlaySound", (name, source) => { TS_ASSERT_EQUALS(name, "constructed"); TS_ASSERT_EQUALS(source, newEnt); }); Engine.RegisterGlobal("MT_EntityRenamed", "entityRenamed"); let finalTemplate = "structures/athen_civil_centre.xml"; let foundationHP = 1; let maxHP = 100; let rot = new Vector3D(1, 2, 3); let pos = new Vector2D(4, 5); AddMock(foundationEnt, IID_Cost, { "GetBuildTime": () => 50, "GetResourceCosts": () => ({ "wood": 100 }), }); AddMock(foundationEnt, IID_Health, { "GetHitpoints": () => foundationHP, "GetMaxHitpoints": () => maxHP, "Increase": hp => { foundationHP = Math.min(foundationHP + hp, maxHP); cmpFoundation.OnHealthChanged(); }, }); AddMock(foundationEnt, IID_Obstruction, { "GetBlockMovementFlag": () => true, - "GetEntityCollisions": () => [], + "GetEntitiesBlockingConstruction": () => [], + "GetEntitiesDeletedUponConstruction": () => [], "SetDisableBlockMovementPathfinding": () => {}, }); AddMock(foundationEnt, IID_Ownership, { "GetOwner": () => player, }); AddMock(foundationEnt, IID_Position, { "GetPosition2D": () => pos, "GetRotation": () => rot, "SetConstructionProgress": () => {}, "IsInWorld": () => true, }); AddMock(previewEnt, IID_Ownership, { "SetOwner": owner => { TS_ASSERT_EQUALS(owner, player); }, }); AddMock(previewEnt, IID_Position, { "JumpTo": (x, y) => { TS_ASSERT_EQUALS(x, pos.x); TS_ASSERT_EQUALS(y, pos.y); }, "SetConstructionProgress": p => {}, "SetYRotation": r => { TS_ASSERT_EQUALS(r, rot.y); }, "SetXZRotation": (rx, rz) => { TS_ASSERT_EQUALS(rx, rot.x); TS_ASSERT_EQUALS(rz, rot.z); }, }); AddMock(newEnt, IID_Ownership, { "SetOwner": owner => { TS_ASSERT_EQUALS(owner, player); }, }); AddMock(newEnt, IID_Position, { "JumpTo": (x, y) => { TS_ASSERT_EQUALS(x, pos.x); TS_ASSERT_EQUALS(y, pos.y); }, "SetYRotation": r => { TS_ASSERT_EQUALS(r, rot.y); }, "SetXZRotation": (rx, rz) => { TS_ASSERT_EQUALS(rx, rot.x); TS_ASSERT_EQUALS(rz, rot.z); }, }); for (let mock of mocks) AddMock(...mock); // INITIALISE Engine.AddEntity = function(template) { TS_ASSERT_EQUALS(template, "construction|" + finalTemplate); return previewEnt; }; let cmpFoundation = ConstructComponent(foundationEnt, "Foundation", {}); cmpFoundation.InitialiseConstruction(player, finalTemplate); TS_ASSERT_EQUALS(cmpFoundation.owner, player); TS_ASSERT_EQUALS(cmpFoundation.finalTemplateName, finalTemplate); TS_ASSERT_EQUALS(cmpFoundation.maxProgress, 0); TS_ASSERT_EQUALS(cmpFoundation.initialised, true); // BUILDER COUNT, BUILD RATE, TIME REMAINING AddMock(10, IID_Builder, { "GetRate": () => 1.0 }); AddMock(11, IID_Builder, { "GetRate": () => 1.0 }); let twoBuilderMultiplier = Math.pow(2, cmpFoundation.buildTimePenalty) / 2; let threeBuilderMultiplier = Math.pow(3, cmpFoundation.buildTimePenalty) / 3; TS_ASSERT_EQUALS(cmpFoundation.CalculateBuildMultiplier(1), 1); TS_ASSERT_EQUALS(cmpFoundation.CalculateBuildMultiplier(2), twoBuilderMultiplier); TS_ASSERT_EQUALS(cmpFoundation.CalculateBuildMultiplier(3), threeBuilderMultiplier); TS_ASSERT_EQUALS(cmpFoundation.GetBuildRate(), 2); TS_ASSERT_EQUALS(cmpFoundation.GetNumBuilders(), 0); TS_ASSERT_EQUALS(cmpFoundation.totalBuilderRate, 0); cmpFoundation.AddBuilder(10); TS_ASSERT_EQUALS(cmpFoundation.GetNumBuilders(), 1); TS_ASSERT_EQUALS(cmpFoundation.buildMultiplier, 1); TS_ASSERT_EQUALS(cmpFoundation.totalBuilderRate, 1); // Foundation starts with 1 hp, so there's 50 * 99/100 = 49.5 seconds left. TS_ASSERT_UNEVAL_EQUALS(cmpFoundation.GetBuildTime(), { 'timeRemaining': 49.5, 'timeRemainingNew': 49.5 / (2 * twoBuilderMultiplier) }); cmpFoundation.AddBuilder(11); TS_ASSERT_EQUALS(cmpFoundation.GetNumBuilders(), 2); TS_ASSERT_EQUALS(cmpFoundation.buildMultiplier, twoBuilderMultiplier); TS_ASSERT_EQUALS(cmpFoundation.totalBuilderRate, 2); TS_ASSERT_UNEVAL_EQUALS(cmpFoundation.GetBuildTime(), { 'timeRemaining': 49.5 / (2 * twoBuilderMultiplier), 'timeRemainingNew': 49.5 / (3 * threeBuilderMultiplier) }); cmpFoundation.AddBuilder(11); TS_ASSERT_EQUALS(cmpFoundation.GetNumBuilders(), 2); TS_ASSERT_EQUALS(cmpFoundation.buildMultiplier, twoBuilderMultiplier); cmpFoundation.RemoveBuilder(11); TS_ASSERT_EQUALS(cmpFoundation.GetNumBuilders(), 1); TS_ASSERT_EQUALS(cmpFoundation.buildMultiplier, 1); cmpFoundation.RemoveBuilder(11); TS_ASSERT_EQUALS(cmpFoundation.GetNumBuilders(), 1); TS_ASSERT_EQUALS(cmpFoundation.buildMultiplier, 1); TS_ASSERT_EQUALS(cmpFoundation.totalBuilderRate, 1); // COMMIT FOUNDATION TS_ASSERT_EQUALS(cmpFoundation.committed, false); let work = 5; cmpFoundation.Build(10, work); TS_ASSERT_EQUALS(cmpFoundation.committed, true); TS_ASSERT_EQUALS(foundationHP, 1 + work * cmpFoundation.GetBuildRate() * cmpFoundation.buildMultiplier); TS_ASSERT_EQUALS(cmpFoundation.maxProgress, foundationHP / maxHP); TS_ASSERT_EQUALS(cmpFoundation.totalBuilderRate, 5); // FINISH CONSTRUCTION Engine.AddEntity = function(template) { TS_ASSERT_EQUALS(template, finalTemplate); return newEnt; }; cmpFoundation.Build(10, 1000); TS_ASSERT_EQUALS(cmpFoundation.maxProgress, 1); TS_ASSERT_EQUALS(foundationHP, maxHP); } testFoundation(); testFoundation([foundationEnt, IID_Visual, { "SetVariable": (key, num) => { TS_ASSERT_EQUALS(key, "numbuilders"); TS_ASSERT(num == 1 || num == 2); }, "SelectAnimation": (name, once, speed) => name, "HasConstructionPreview": () => true, }]); testFoundation([newEnt, IID_TerritoryDecay, { "HasTerritoryOwnership": () => true, }]); testFoundation([playerEnt, IID_StatisticsTracker, { "IncreaseConstructedBuildingsCounter": ent => { TS_ASSERT_EQUALS(ent, newEnt); }, }]); Index: ps/trunk/binaries/data/mods/public/simulation/helpers/Transform.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/helpers/Transform.js (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/helpers/Transform.js (revision 21624) @@ -1,241 +1,245 @@ // Helper functions to change an entity's template and check if the transformation is possible // returns the ID of the new entity or INVALID_ENTITY. function ChangeEntityTemplate(oldEnt, newTemplate) { // Done un/packing, copy our parameters to the final entity var newEnt = Engine.AddEntity(newTemplate); if (newEnt == INVALID_ENTITY) { error("Transform.js: Error replacing entity " + oldEnt + " for a '" + newTemplate + "'"); return INVALID_ENTITY; } var cmpPosition = Engine.QueryInterface(oldEnt, IID_Position); var cmpNewPosition = Engine.QueryInterface(newEnt, IID_Position); if (cmpPosition && cmpNewPosition) { if (cmpPosition.IsInWorld()) { let pos = cmpPosition.GetPosition2D(); cmpNewPosition.JumpTo(pos.x, pos.y); } let rot = cmpPosition.GetRotation(); cmpNewPosition.SetYRotation(rot.y); cmpNewPosition.SetXZRotation(rot.x, rot.z); cmpNewPosition.SetHeightOffset(cmpPosition.GetHeightOffset()); } var cmpOwnership = Engine.QueryInterface(oldEnt, IID_Ownership); var cmpNewOwnership = Engine.QueryInterface(newEnt, IID_Ownership); if (cmpOwnership && cmpNewOwnership) cmpNewOwnership.SetOwner(cmpOwnership.GetOwner()); // Copy control groups CopyControlGroups(oldEnt, newEnt); // Rescale capture points var cmpCapturable = Engine.QueryInterface(oldEnt, IID_Capturable); var cmpNewCapturable = Engine.QueryInterface(newEnt, IID_Capturable); if (cmpCapturable && cmpNewCapturable) { let scale = cmpCapturable.GetMaxCapturePoints() / cmpNewCapturable.GetMaxCapturePoints(); let newCp = cmpCapturable.GetCapturePoints().map(v => v / scale); cmpNewCapturable.SetCapturePoints(newCp); } // Maintain current health level var cmpHealth = Engine.QueryInterface(oldEnt, IID_Health); var cmpNewHealth = Engine.QueryInterface(newEnt, IID_Health); if (cmpHealth && cmpNewHealth) { var healthLevel = Math.max(0, Math.min(1, cmpHealth.GetHitpoints() / cmpHealth.GetMaxHitpoints())); cmpNewHealth.SetHitpoints(cmpNewHealth.GetMaxHitpoints() * healthLevel); } var cmpUnitAI = Engine.QueryInterface(oldEnt, IID_UnitAI); var cmpNewUnitAI = Engine.QueryInterface(newEnt, IID_UnitAI); if (cmpUnitAI && cmpNewUnitAI) { let pos = cmpUnitAI.GetHeldPosition(); if (pos) cmpNewUnitAI.SetHeldPosition(pos.x, pos.z); if (cmpUnitAI.GetStanceName()) cmpNewUnitAI.SwitchToStance(cmpUnitAI.GetStanceName()); cmpNewUnitAI.AddOrders(cmpUnitAI.GetOrders()); if (cmpUnitAI.IsGuardOf()) { let guarded = cmpUnitAI.IsGuardOf(); let cmpGuard = Engine.QueryInterface(guarded, IID_Guard); if (cmpGuard) { cmpGuard.RenameGuard(oldEnt, newEnt); cmpNewUnitAI.SetGuardOf(guarded); } } } // Maintain the list of guards let cmpGuard = Engine.QueryInterface(oldEnt, IID_Guard); let cmpNewGuard = Engine.QueryInterface(newEnt, IID_Guard); if (cmpGuard && cmpNewGuard) { let entities = cmpGuard.GetEntities(); if (entities.length) { cmpNewGuard.SetEntities(entities); for (let ent of entities) { let cmpEntUnitAI = Engine.QueryInterface(ent, IID_UnitAI); if (cmpEntUnitAI) cmpEntUnitAI.SetGuardOf(newEnt); } } } TransferGarrisonedUnits(oldEnt, newEnt); Engine.PostMessage(oldEnt, MT_EntityRenamed, { "entity": oldEnt, "newentity": newEnt }); if (cmpPosition && cmpPosition.IsInWorld()) cmpPosition.MoveOutOfWorld(); Engine.DestroyEntity(oldEnt); return newEnt; } function CanGarrisonedChangeTemplate(ent, template) { var cmpPosition = Engine.QueryInterface(ent, IID_Position); var unitAI = Engine.QueryInterface(ent, IID_UnitAI); if (cmpPosition && !cmpPosition.IsInWorld() && unitAI && unitAI.IsGarrisoned()) { // We're a garrisoned unit, assume impossibility as I've been unable to find a way to get the holder ID. // TODO: change this if that ever becomes possibles return false; } return true; } function CopyControlGroups(oldEnt, newEnt) { let cmpObstruction = Engine.QueryInterface(oldEnt, IID_Obstruction); let cmpNewObstruction = Engine.QueryInterface(newEnt, IID_Obstruction); if (cmpObstruction && cmpNewObstruction) { cmpNewObstruction.SetControlGroup(cmpObstruction.GetControlGroup()); cmpNewObstruction.SetControlGroup2(cmpObstruction.GetControlGroup2()); } } function ObstructionsBlockingTemplateChange(ent, templateArg) { var previewEntity = Engine.AddEntity("preview|"+templateArg); if (previewEntity == INVALID_ENTITY) return true; CopyControlGroups(ent, previewEntity); var cmpBuildRestrictions = Engine.QueryInterface(previewEntity, IID_BuildRestrictions); var cmpPosition = Engine.QueryInterface(ent, IID_Position); var cmpOwnership = Engine.QueryInterface(ent, IID_Ownership); var cmpNewPosition = Engine.QueryInterface(previewEntity, IID_Position); // Return false if no ownership as BuildRestrictions.CheckPlacement needs an owner and I have no idea if false or true is better // Plus there are no real entities without owners currently. if (!cmpBuildRestrictions || !cmpPosition || !cmpOwnership) return DeleteEntityAndReturn(previewEntity, cmpPosition, null, null, cmpNewPosition, false); var pos = cmpPosition.GetPosition2D(); var angle = cmpPosition.GetRotation(); // move us away to prevent our own obstruction from blocking the upgrade. cmpPosition.MoveOutOfWorld(); cmpNewPosition.JumpTo(pos.x, pos.y); cmpNewPosition.SetYRotation(angle.y); var cmpNewOwnership = Engine.QueryInterface(previewEntity, IID_Ownership); cmpNewOwnership.SetOwner(cmpOwnership.GetOwner()); var checkPlacement = cmpBuildRestrictions.CheckPlacement(); if (checkPlacement && !checkPlacement.success) return DeleteEntityAndReturn(previewEntity, cmpPosition, pos, angle, cmpNewPosition, true); var cmpTemplateManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager); var template = cmpTemplateManager.GetTemplate(cmpTemplateManager.GetCurrentTemplateName(ent)); var newTemplate = cmpTemplateManager.GetTemplate(templateArg); // Check if units are blocking our template change if (template.Obstruction && newTemplate.Obstruction) { // This only needs to be done if the new template is strictly bigger than the old one // "Obstructions" are annoying to test so just check. if (newTemplate.Obstruction.Obstructions || newTemplate.Obstruction.Static && template.Obstruction.Static && (newTemplate.Obstruction.Static["@width"] > template.Obstruction.Static["@width"] || newTemplate.Obstruction.Static["@depth"] > template.Obstruction.Static["@depth"]) || newTemplate.Obstruction.Static && template.Obstruction.Unit && (newTemplate.Obstruction.Static["@width"] > template.Obstruction.Unit["@radius"] || newTemplate.Obstruction.Static["@depth"] > template.Obstruction.Unit["@radius"]) || newTemplate.Obstruction.Unit && template.Obstruction.Unit && newTemplate.Obstruction.Unit["@radius"] > template.Obstruction.Unit["@radius"] || newTemplate.Obstruction.Unit && template.Obstruction.Static && (newTemplate.Obstruction.Unit["@radius"] > template.Obstruction.Static["@width"] || newTemplate.Obstruction.Unit["@radius"] > template.Obstruction.Static["@depth"])) { var cmpNewObstruction = Engine.QueryInterface(previewEntity, IID_Obstruction); if (cmpNewObstruction && cmpNewObstruction.GetBlockMovementFlag()) { - let collisions = cmpNewObstruction.GetEntityCollisions(); + // Remove all obstructions at the new entity, especially animal corpses + for (let ent of cmpNewObstruction.GetEntitiesDeletedUponConstruction()) + Engine.DestroyEntity(ent); + + let collisions = cmpNewObstruction.GetEntitiesBlockingConstruction(); if (collisions.length) return DeleteEntityAndReturn(previewEntity, cmpPosition, pos, angle, cmpNewPosition, true); } } } return DeleteEntityAndReturn(previewEntity, cmpPosition, pos, angle, cmpNewPosition, false); } function DeleteEntityAndReturn(ent, cmpPosition, position, angle, cmpNewPosition, ret) { // prevent preview from interfering in the world cmpNewPosition.MoveOutOfWorld(); if (position !== null) { cmpPosition.JumpTo(position.x, position.y); cmpPosition.SetYRotation(angle.y); } Engine.DestroyEntity(ent); return ret; } function TransferGarrisonedUnits(oldEnt, newEnt) { // Transfer garrisoned units if possible, or unload them let cmpOldGarrison = Engine.QueryInterface(oldEnt, IID_GarrisonHolder); if (!cmpOldGarrison || !cmpOldGarrison.GetEntities().length) return; let cmpNewGarrison = Engine.QueryInterface(newEnt, IID_GarrisonHolder); let entities = cmpOldGarrison.GetEntities().slice(); for (let ent of entities) { cmpOldGarrison.Eject(ent); if (!cmpNewGarrison) continue; let cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI); if (!cmpUnitAI) continue; cmpUnitAI.Autogarrison(newEnt); cmpNewGarrison.Garrison(ent); } } Engine.RegisterGlobal("ChangeEntityTemplate", ChangeEntityTemplate); Engine.RegisterGlobal("CanGarrisonedChangeTemplate", CanGarrisonedChangeTemplate); Engine.RegisterGlobal("ObstructionsBlockingTemplateChange", ObstructionsBlockingTemplateChange); Index: ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/mirage.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/mirage.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/mirage.xml (revision 21624) @@ -1,28 +1,29 @@ false false false false + false Index: ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/preview.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/preview.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/preview.xml (revision 21624) @@ -1,33 +1,34 @@ false + false true true Index: ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/resource.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/resource.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/special/filter/resource.xml (revision 21624) @@ -1,29 +1,30 @@ true false false false - false + true + true false false Index: ps/trunk/binaries/data/mods/public/simulation/templates/template_gaia.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/template_gaia.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/template_gaia.xml (revision 21624) @@ -1,38 +1,39 @@ gaia Gaia true true true true true true false false + false 2.0 0.333 5.0 true false false false 0 false true false Index: ps/trunk/binaries/data/mods/public/simulation/templates/template_gaia_flora.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/template_gaia_flora.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/template_gaia_flora.xml (revision 21624) @@ -1,39 +1,41 @@ ForestPlant gaia/flora_tree_generic.png wood + + true false 200 wood.tree 8 circle/128x128.png circle/128x128_mask.png Index: ps/trunk/binaries/data/mods/public/simulation/templates/template_structure.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/template_structure.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/template_structure.xml (revision 21624) @@ -1,153 +1,154 @@ 1 1 1 1 1 1 0 0 Infantry Cavalry land own 500 0.5 5.0 0 0 10 0 0 0 0 false false 0.0 3.0 9.8 0.85 0.65 0.35 corpse 0 0 true Structure Structure ConquestCritical false 0 0 10 0 0 structure true true true true true false false + false 1.0 1.0 1.0 1.0 special/rallypoint art/textures/misc/rallypoint_line.png art/textures/misc/rallypoint_line_mask.png 0.25 square round default 2.0 outline_border.png outline_border_mask.png 0.4 interface/complete/building/complete_universal.xml attack/destruction/building_collapse_large.xml interface/alarm/alarm_attackplayer.xml attack/weapon/arrowfly.xml attack/impact/arrow_metal.xml 6.0 0.6 12.0 20 true false false false 40 false false true false Index: ps/trunk/binaries/data/mods/public/simulation/templates/template_unit.xml =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/templates/template_unit.xml (revision 21623) +++ ps/trunk/binaries/data/mods/public/simulation/templates/template_unit.xml (revision 21624) @@ -1,138 +1,139 @@ 1 1 15 1 0 1 0 0 0 0 false false 80.0 0.01 0.0 2.5 corpse 100 0 0 false Unit Unit ConquestCritical special/formations/null special/formations/box special/formations/column_closed special/formations/line_closed special/formations/column_open special/formations/line_open special/formations/flank special/formations/battle_line false unit true true false false true false false + false 2.0 1.0 1 10 10 10 10 circle/128x128.png circle/128x128_mask.png interface/alarm/alarm_attackplayer.xml attack/weapon/sword.xml 2.0 0.333 5.0 aggressive 12.0 false true true false 9.0 15.0 50.0 0.0 0.1 0.2 default false false false false 12 false true false false Index: ps/trunk/source/simulation2/components/CCmpObstruction.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 21623) +++ ps/trunk/source/simulation2/components/CCmpObstruction.cpp (revision 21624) @@ -1,844 +1,834 @@ /* Copyright (C) 2018 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: enum { STATIC, UNIT, CLUSTER } 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 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 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 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 GetUnitCollisions() const + virtual std::vector GetEntitiesByFlags(flags_t flags) const { std::vector ret; CmpPtr cmpObstructionManager(GetSystemEntity()); if (!cmpObstructionManager) return ret; // error - // There are four 'block' flags: construction, foundation, movement, - // and pathfinding. Structures have all of these flags, while most units - // block only movement and construction. - flags_t flags = ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION; - // 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); + cmpObstructionManager->GetUnitsOnObstruction(square, ret, filter, false); + cmpObstructionManager->GetStaticObstructionsOnObstruction(square, ret, filter); return ret; } - virtual std::vector GetEntityCollisions() const + virtual std::vector GetEntitiesBlockingConstruction() const { - std::vector ret; - - CmpPtr cmpObstructionManager(GetSystemEntity()); - if (!cmpObstructionManager) - return ret; // error - - // Ignore collisions within the same control group. - SkipControlGroupsRequireFlagObstructionFilter filter(true, m_ControlGroup, m_ControlGroup2, 0); - - ICmpObstructionManager::ObstructionSquare square; - if (!GetObstructionSquare(square)) - return ret; // error - - cmpObstructionManager->GetUnitsOnObstruction(square, ret, filter, false); - cmpObstructionManager->GetStaticObstructionsOnObstruction(square, ret, filter); + return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION); + } - return ret; + 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 21623) +++ ps/trunk/source/simulation2/components/ICmpObstruction.cpp (revision 21624) @@ -1,62 +1,62 @@ /* Copyright (C) 2018 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("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("GetUnitCollisions", std::vector, ICmpObstruction, GetUnitCollisions) -DEFINE_INTERFACE_METHOD_CONST_0("GetEntityCollisions", std::vector, ICmpObstruction, GetEntityCollisions) +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 21623) +++ ps/trunk/source/simulation2/components/ICmpObstruction.h (revision 21624) @@ -1,134 +1,139 @@ /* Copyright (C) 2018 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 }; 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; virtual entity_pos_t GetSize() const = 0; virtual entity_pos_t GetUnitRadius() 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 units that are colliding with this entity. - * @return vector of blocking units + * 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 GetUnitCollisions() const = 0; + virtual std::vector GetEntitiesByFlags(ICmpObstructionManager::flags_t flags) const = 0; /** - * Returns a list of entities that are colliding with this entity (excluding self). - * This can be used to retrieve units with static obstructions, such as animal corpses. - * @return vector of blocking units + * Returns a list of entities that are blocking construction of a foundation. + * @return vector of blocking entities */ - virtual std::vector GetEntityCollisions() const = 0; + 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/ICmpObstructionManager.h =================================================================== --- ps/trunk/source/simulation2/components/ICmpObstructionManager.h (revision 21623) +++ ps/trunk/source/simulation2/components/ICmpObstructionManager.h (revision 21624) @@ -1,495 +1,496 @@ /* Copyright (C) 2018 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_ICMPOBSTRUCTIONMANAGER #define INCLUDED_ICMPOBSTRUCTIONMANAGER #include "simulation2/system/Interface.h" #include "simulation2/helpers/Pathfinding.h" #include "maths/FixedVector2D.h" class IObstructionTestFilter; /** * Obstruction manager: provides efficient spatial queries over objects in the world. * * The class deals with two types of shape: * "static" shapes, typically representing buildings, which are rectangles with a given * width and height and angle; * and "unit" shapes, representing units that can move around the world, which have a * radius and no rotation. (Units sometimes act as axis-aligned squares, sometimes * as approximately circles, due to the algorithm used by the short pathfinder.) * * Other classes (particularly ICmpObstruction) register shapes with this interface * and keep them updated. * * The @c Test functions provide exact collision tests. * The edge of a shape counts as 'inside' the shape, for the purpose of collisions. * The functions accept an IObstructionTestFilter argument, which can restrict the * set of shapes that are counted as collisions. * * Units can be marked as either moving or stationary, which simply determines whether * certain filters include or exclude them. * * The @c Rasterize function approximates the current set of shapes onto a 2D grid, * for use with tile-based pathfinding. */ class ICmpObstructionManager : public IComponent { public: /** * External identifiers for shapes. * (This is a struct rather than a raw u32 for type-safety.) */ struct tag_t { tag_t() : n(0) {} explicit tag_t(u32 n) : n(n) {} bool valid() const { return n != 0; } u32 n; }; /** * Boolean flags affecting the obstruction behaviour of a shape. */ enum EFlags { - FLAG_BLOCK_MOVEMENT = (1 << 0), // prevents units moving through this shape - FLAG_BLOCK_FOUNDATION = (1 << 1), // prevents foundations being placed on this shape - FLAG_BLOCK_CONSTRUCTION = (1 << 2), // prevents buildings being constructed on this shape - FLAG_BLOCK_PATHFINDING = (1 << 3), // prevents the tile pathfinder choosing paths through this shape - FLAG_MOVING = (1 << 4) // indicates this unit is currently moving + FLAG_BLOCK_MOVEMENT = (1 << 0), // prevents units moving through this shape + FLAG_BLOCK_FOUNDATION = (1 << 1), // prevents foundations being placed on this shape + FLAG_BLOCK_CONSTRUCTION = (1 << 2), // prevents buildings being constructed on this shape + FLAG_BLOCK_PATHFINDING = (1 << 3), // prevents the tile pathfinder choosing paths through this shape + FLAG_MOVING = (1 << 4), // indicates this unit is currently moving + FLAG_DELETE_UPON_CONSTRUCTION = (1 << 5) // this entity is deleted when construction of a building placed on top of this entity starts }; /** * Bitmask of EFlag values. */ typedef u8 flags_t; /** * Set the bounds of the world. * Any point outside the bounds is considered obstructed. * @param x0,z0,x1,z1 Coordinates of the corners of the world */ virtual void SetBounds(entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1) = 0; /** * Register a static shape. * * @param ent entity ID associated with this shape (or INVALID_ENTITY if none) * @param x,z coordinates of center, in world space * @param a angle of rotation (clockwise from +Z direction) * @param w width (size along X axis) * @param h height (size along Z axis) * @param flags a set of EFlags values * @param group primary control group of the shape. Must be a valid control group ID. * @param group2 Optional; secondary control group of the shape. Defaults to INVALID_ENTITY. * @return a valid tag for manipulating the shape * @see StaticShape */ virtual tag_t AddStaticShape(entity_id_t ent, entity_pos_t x, entity_pos_t z, entity_angle_t a, entity_pos_t w, entity_pos_t h, flags_t flags, entity_id_t group, entity_id_t group2 = INVALID_ENTITY) = 0; /** * Register a unit shape. * * @param ent entity ID associated with this shape (or INVALID_ENTITY if none) * @param x,z coordinates of center, in world space * @param clearance pathfinding clearance of the unit (works as a radius) * @param flags a set of EFlags values * @param group control group (typically the owner entity, or a formation controller entity * - units ignore collisions with others in the same group) * @return a valid tag for manipulating the shape * @see UnitShape */ virtual tag_t AddUnitShape(entity_id_t ent, entity_pos_t x, entity_pos_t z, entity_pos_t clearance, flags_t flags, entity_id_t group) = 0; /** * Adjust the position and angle of an existing shape. * @param tag tag of shape (must be valid) * @param x X coordinate of center, in world space * @param z Z coordinate of center, in world space * @param a angle of rotation (clockwise from +Z direction); ignored for unit shapes */ virtual void MoveShape(tag_t tag, entity_pos_t x, entity_pos_t z, entity_angle_t a) = 0; /** * Set whether a unit shape is moving or stationary. * @param tag tag of shape (must be valid and a unit shape) * @param moving whether the unit is currently moving through the world or is stationary */ virtual void SetUnitMovingFlag(tag_t tag, bool moving) = 0; /** * Set the control group of a unit shape. * @param tag tag of shape (must be valid and a unit shape) * @param group control group entity ID */ virtual void SetUnitControlGroup(tag_t tag, entity_id_t group) = 0; /** * Sets the control group of a static shape. * @param tag Tag of the shape to set the control group for. Must be a valid and static shape tag. * @param group Control group entity ID. */ virtual void SetStaticControlGroup(tag_t tag, entity_id_t group, entity_id_t group2) = 0; /** * Remove an existing shape. The tag will be made invalid and must not be used after this. * @param tag tag of shape (must be valid) */ virtual void RemoveShape(tag_t tag) = 0; /** * Returns the distance from the obstruction to the point (px, pz), or -1 if the entity is out of the world. */ virtual fixed DistanceToPoint(entity_id_t ent, entity_pos_t px, entity_pos_t pz) const = 0; /** * Collision test a flat-ended thick line against the current set of shapes. * The line caps extend by @p r beyond the end points. * Only intersections going from outside to inside a shape are counted. * @param filter filter to restrict the shapes that are counted * @param x0 X coordinate of line's first point * @param z0 Z coordinate of line's first point * @param x1 X coordinate of line's second point * @param z1 Z coordinate of line's second point * @param r radius (half width) of line * @param relaxClearanceForUnits whether unit-unit collisions should be more permissive. * @return true if there is a collision */ virtual bool TestLine(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, entity_pos_t r, bool relaxClearanceForUnits) const = 0; /** * Collision test a static square shape against the current set of shapes. * @param filter filter to restrict the shapes that are being tested against * @param x X coordinate of center * @param z Z coordinate of center * @param a angle of rotation (clockwise from +Z direction) * @param w width (size along X axis) * @param h height (size along Z axis) * @param out if non-NULL, all colliding shapes' entities will be added to this list * @return true if there is a collision */ virtual bool TestStaticShape(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t a, entity_pos_t w, entity_pos_t h, std::vector* out) const = 0; /** * Collision test a unit shape against the current set of registered shapes, and optionally writes a list of the colliding * shapes' entities to an output list. * * @param filter filter to restrict the shapes that are being tested against * @param x X coordinate of shape's center * @param z Z coordinate of shape's center * @param clearance clearance of the shape's unit * @param out if non-NULL, all colliding shapes' entities will be added to this list * * @return true if there is a collision */ virtual bool TestUnitShape(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t clearance, std::vector* out) const = 0; /** * Convert the current set of shapes onto a navcell grid, for all passability classes contained in @p passClasses. * If @p fullUpdate is false, the function will only go through dirty shapes. * Shapes are expanded by the @p passClasses clearances, by ORing their masks onto the @p grid. */ virtual void Rasterize(Grid& grid, const std::vector& passClasses, bool fullUpdate) = 0; /** * Gets dirtiness information and resets it afterwards. Then it's the role of CCmpPathfinder * to pass the information to other components if needed. (AIs, etc.) * The return value is false if an update is unnecessary. */ virtual void UpdateInformations(GridUpdateInformation& informations) = 0; /** * Standard representation for all types of shapes, for use with geometry processing code. */ struct ObstructionSquare { entity_pos_t x, z; // position of center CFixedVector2D u, v; // 'horizontal' and 'vertical' orthogonal unit vectors, representing orientation entity_pos_t hw, hh; // half width, half height of square }; /** * Find all the obstructions that are inside (or partially inside) the given range. * @param filter filter to restrict the shapes that are counted * @param x0 X coordinate of left edge of range * @param z0 Z coordinate of bottom edge of range * @param x1 X coordinate of right edge of range * @param z1 Z coordinate of top edge of range * @param squares output list of obstructions */ virtual void GetObstructionsInRange(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, std::vector& squares) const = 0; virtual void GetStaticObstructionsInRange(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, std::vector& squares) const = 0; virtual void GetUnitObstructionsInRange(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, std::vector& squares) const = 0; virtual void GetStaticObstructionsOnObstruction(const ObstructionSquare& square, std::vector& out, const IObstructionTestFilter& filter) const = 0; /** * Returns the entity IDs of all unit shapes that intersect the given * obstruction square, filtering out using the given filter. * @param square the Obstruction squre we want to compare with. * @param out output list of obstructions * @param filter filter for the obstructing units * @param strict whether to be strict in the check or more permissive (ie rasterize more or less). Default false. */ virtual void GetUnitsOnObstruction(const ObstructionSquare& square, std::vector& out, const IObstructionTestFilter& filter, bool strict = false) const = 0; /** * Get the obstruction square representing the given shape. * @param tag tag of shape (must be valid) */ virtual ObstructionSquare GetObstruction(tag_t tag) const = 0; virtual ObstructionSquare GetUnitShapeObstruction(entity_pos_t x, entity_pos_t z, entity_pos_t clearance) const = 0; virtual ObstructionSquare GetStaticShapeObstruction(entity_pos_t x, entity_pos_t z, entity_angle_t a, entity_pos_t w, entity_pos_t h) const = 0; /** * Set the passability to be restricted to a circular map. */ virtual void SetPassabilityCircular(bool enabled) = 0; virtual bool GetPassabilityCircular() const = 0; /** * Toggle the rendering of debug info. */ virtual void SetDebugOverlay(bool enabled) = 0; DECLARE_INTERFACE_TYPE(ObstructionManager) }; /** * Interface for ICmpObstructionManager @c Test functions to filter out unwanted shapes. */ class IObstructionTestFilter { public: typedef ICmpObstructionManager::tag_t tag_t; typedef ICmpObstructionManager::flags_t flags_t; virtual ~IObstructionTestFilter() {} /** * Return true if the shape with the specified parameters should be tested for collisions. * This is called for all shapes that would collide, and also for some that wouldn't. * * @param tag tag of shape being tested * @param flags set of EFlags for the shape * @param group the control group of the shape (typically the shape's unit, or the unit's formation controller, or 0) * @param group2 an optional secondary control group of the shape, or INVALID_ENTITY if none specified. Currently * exists only for static shapes. */ virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t group, entity_id_t group2) const = 0; }; /** * Obstruction test filter that will test against all shapes. */ class NullObstructionFilter : public IObstructionTestFilter { public: virtual bool TestShape(tag_t UNUSED(tag), flags_t UNUSED(flags), entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return true; } }; /** * Obstruction test filter that will test only against stationary (i.e. non-moving) shapes. */ class StationaryOnlyObstructionFilter : public IObstructionTestFilter { public: virtual bool TestShape(tag_t UNUSED(tag), flags_t flags, entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return !(flags & ICmpObstructionManager::FLAG_MOVING); } }; /** * Obstruction test filter that reject shapes in a given control group, * and rejects shapes that don't block unit movement, and optionally rejects moving shapes. */ class ControlGroupMovementObstructionFilter : public IObstructionTestFilter { bool m_AvoidMoving; entity_id_t m_Group; public: ControlGroupMovementObstructionFilter(bool avoidMoving, entity_id_t group) : m_AvoidMoving(avoidMoving), m_Group(group) {} virtual bool TestShape(tag_t UNUSED(tag), flags_t flags, entity_id_t group, entity_id_t group2) const { if (group == m_Group || (group2 != INVALID_ENTITY && group2 == m_Group)) return false; if (!(flags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT)) return false; if ((flags & ICmpObstructionManager::FLAG_MOVING) && !m_AvoidMoving) return false; return true; } }; /** * Obstruction test filter that will test only against shapes that: * - are part of neither one of the specified control groups * - AND, depending on the value of the 'exclude' argument: * - have at least one of the specified flags set. * - OR have none of the specified flags set. * * The first (primary) control group to reject shapes from must be specified and valid. The secondary * control group to reject entities from may be set to INVALID_ENTITY to not use it. * * This filter is useful to e.g. allow foundations within the same control group to be placed and * constructed arbitrarily close together (e.g. for wall pieces that need to link up tightly). */ class SkipControlGroupsRequireFlagObstructionFilter : public IObstructionTestFilter { bool m_Exclude; entity_id_t m_Group; entity_id_t m_Group2; flags_t m_Mask; public: SkipControlGroupsRequireFlagObstructionFilter(bool exclude, entity_id_t group1, entity_id_t group2, flags_t mask) : m_Exclude(exclude), m_Group(group1), m_Group2(group2), m_Mask(mask) { Init(); } SkipControlGroupsRequireFlagObstructionFilter(entity_id_t group1, entity_id_t group2, flags_t mask) : m_Exclude(false), m_Group(group1), m_Group2(group2), m_Mask(mask) { Init(); } virtual bool TestShape(tag_t UNUSED(tag), flags_t flags, entity_id_t group, entity_id_t group2) const { // Don't test shapes that share one or more of our control groups. if (group == m_Group || group == m_Group2 || (group2 != INVALID_ENTITY && (group2 == m_Group || group2 == m_Group2))) return false; // If m_Exclude is true, don't test against shapes that have any of the // obstruction flags specified in m_Mask. if (m_Exclude) return (flags & m_Mask) == 0; // Otherwise, only include shapes that match at least one flag in m_Mask. return (flags & m_Mask) != 0; } private: void Init() { // the primary control group to filter out must be valid ENSURE(m_Group != INVALID_ENTITY); // for simplicity, if m_Group2 is INVALID_ENTITY (i.e. not used), then set it equal to m_Group // so that we have fewer special cases to consider in TestShape(). if (m_Group2 == INVALID_ENTITY) m_Group2 = m_Group; } }; /** * Obstruction test filter that will test only against shapes that: * - are part of both of the specified control groups * - AND have at least one of the specified flags set. * * The first (primary) control group to include shapes from must be specified and valid. * * This filter is useful for preventing entities with identical control groups * from colliding e.g. building a new wall segment on top of an existing wall) * * @todo This filter needs test cases. */ class SkipTagRequireControlGroupsAndFlagObstructionFilter : public IObstructionTestFilter { tag_t m_Tag; entity_id_t m_Group; entity_id_t m_Group2; flags_t m_Mask; public: SkipTagRequireControlGroupsAndFlagObstructionFilter(tag_t tag, entity_id_t group1, entity_id_t group2, flags_t mask) : m_Tag(tag), m_Group(group1), m_Group2(group2), m_Mask(mask) { ENSURE(m_Group != INVALID_ENTITY); } virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t group, entity_id_t group2) const { // To be included in testing, a shape must not have the specified tag, and must // match at least one of the flags in m_Mask, as well as both control groups. return (tag.n != m_Tag.n && (flags & m_Mask) != 0 && ((group == m_Group && group2 == m_Group2) || (group2 == m_Group && group == m_Group2))); } }; /** * Obstruction test filter that will test only against shapes that do not have the specified tag set. */ class SkipTagObstructionFilter : public IObstructionTestFilter { tag_t m_Tag; public: SkipTagObstructionFilter(tag_t tag) : m_Tag(tag) { } virtual bool TestShape(tag_t tag, flags_t UNUSED(flags), entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return tag.n != m_Tag.n; } }; /** * Obstruction test filter that will test only against shapes that: * - do not have the specified tag * - AND have at least one of the specified flags set. */ class SkipTagRequireFlagsObstructionFilter : public IObstructionTestFilter { tag_t m_Tag; flags_t m_Mask; public: SkipTagRequireFlagsObstructionFilter(tag_t tag, flags_t mask) : m_Tag(tag), m_Mask(mask) { } virtual bool TestShape(tag_t tag, flags_t flags, entity_id_t UNUSED(group), entity_id_t UNUSED(group2)) const { return (tag.n != m_Tag.n && (flags & m_Mask) != 0); } }; #endif // INCLUDED_ICMPOBSTRUCTIONMANAGER