LCOV - code coverage report
Current view: top level - maps/random/rmgen-common - player.js (source / functions) Coverage Total Hit
Test: lcov.info Lines: 0.0 % 350 0
Test Date: 2026-11-22 03:02:19 Functions: 0.0 % 60 0

            Line data    Source code
       1              : /**
       2              :  * @file These functions locate and place the starting entities of players.
       3              :  */
       4              : 
       5            0 : var g_NomadTreasureTemplates = {
       6              :         "food": "gaia/treasure/food_jars",
       7              :         "wood": "gaia/treasure/wood",
       8              :         "stone": "gaia/treasure/stone",
       9              :         "metal": "gaia/treasure/metal"
      10              : };
      11              : 
      12              : /**
      13              :  * These are identifiers of functions that can generate parts of a player base.
      14              :  * There must be a function starting with placePlayerBase and ending with this name.
      15              :  * This is a global so mods can extend this from external files.
      16              :  */
      17            0 : var g_PlayerBaseFunctions = [
      18              :         // Possibly mark player class first here and use it afterwards
      19              :         "CityPatch",
      20              :         // Create the largest and most important entities first
      21              :         "Trees",
      22              :         "Mines",
      23              :         "Treasures",
      24              :         "Berries",
      25              :         "StartingAnimal",
      26              :         "Decoratives"
      27              : ];
      28              : 
      29              : function getNumPlayers()
      30              : {
      31            0 :         return g_MapSettings.PlayerData.length - 1;
      32              : }
      33              : 
      34              : function getCivCode(playerID)
      35              : {
      36            0 :         return g_MapSettings.PlayerData[playerID].Civ;
      37              : }
      38              : 
      39              : function areAllies(playerID1, playerID2)
      40              : {
      41            0 :         return g_MapSettings.PlayerData[playerID1].Team !== undefined &&
      42              :                g_MapSettings.PlayerData[playerID2].Team !== undefined &&
      43              :                g_MapSettings.PlayerData[playerID1].Team != -1 &&
      44              :                g_MapSettings.PlayerData[playerID2].Team != -1 &&
      45              :                g_MapSettings.PlayerData[playerID1].Team === g_MapSettings.PlayerData[playerID2].Team;
      46              : }
      47              : 
      48              : function getPlayerTeam(playerID)
      49              : {
      50            0 :         if (g_MapSettings.PlayerData[playerID].Team === undefined)
      51            0 :                 return -1;
      52              : 
      53            0 :         return g_MapSettings.PlayerData[playerID].Team;
      54              : }
      55              : 
      56              : /**
      57              :  * Gets the default starting entities for the civ of the given player, as defined by the civ file.
      58              :  */
      59              : function getStartingEntities(playerID)
      60              : {
      61            0 :         return g_CivData[getCivCode(playerID)].StartEntities;
      62              : }
      63              : 
      64              : /**
      65              :  * Places the given entities at the given location (typically a civic center and starting units).
      66              :  * @param location - A Vector2D specifying tile coordinates.
      67              :  * @param civEntities - An array of objects with the Template property and optionally a Count property.
      68              :  * The first entity is placed in the center, the other ones surround it.
      69              :  */
      70              : function placeStartingEntities(location, playerID, civEntities, dist = 6, orientation = BUILDING_ORIENTATION)
      71              : {
      72              :         // Place the central structure
      73            0 :         let i = 0;
      74            0 :         const firstTemplate = civEntities[i].Template;
      75            0 :         if (firstTemplate.startsWith("structures/"))
      76              :         {
      77            0 :                 g_Map.placeEntityPassable(firstTemplate, playerID, location, orientation);
      78            0 :                 ++i;
      79              :         }
      80              : 
      81              :         // Place entities surrounding it
      82            0 :         const space = 2;
      83            0 :         for (let j = i; j < civEntities.length; ++j)
      84              :         {
      85            0 :                 const angle = orientation - Math.PI * (1 - j / 2);
      86            0 :                 const count = civEntities[j].Count || 1;
      87              : 
      88            0 :                 for (let num = 0; num < count; ++num)
      89              :                 {
      90            0 :                         const position = Vector2D.sum([
      91              :                                 location,
      92              :                                 new Vector2D(dist, 0).rotate(-angle),
      93              :                                 new Vector2D(space * (-num + (count - 1) / 2), 0).rotate(angle)
      94              :                         ]);
      95              : 
      96            0 :                         g_Map.placeEntityPassable(civEntities[j].Template, playerID, position, angle);
      97              :                 }
      98              :         }
      99              : }
     100              : 
     101              : /**
     102              :  * Places the default starting entities as defined by the civilization definition, optionally including city walls.
     103              :  */
     104              : function placeCivDefaultStartingEntities(position, playerID, wallType, dist = 6, orientation = BUILDING_ORIENTATION)
     105              : {
     106            0 :         placeStartingEntities(position, playerID, getStartingEntities(playerID), dist, orientation);
     107            0 :         placeStartingWalls(position, playerID, wallType, orientation);
     108              : }
     109              : 
     110              : /**
     111              :  * If the map is large enough and the civilization defines them, places the initial city walls or towers.
     112              :  * @param {string|boolean} wallType - Either "towers" to only place the wall turrets or a boolean indicating enclosing city walls.
     113              :  */
     114              : function placeStartingWalls(position, playerID, wallType, orientation = BUILDING_ORIENTATION)
     115              : {
     116            0 :         const civ = getCivCode(playerID);
     117            0 :         if (civ != "iber" || g_Map.getSize() <= 128)
     118            0 :                 return;
     119              : 
     120              :         // TODO: should prevent trees inside walls
     121              :         // When fixing, remove the DeleteUponConstruction flag from template_gaia_flora.xml
     122              : 
     123            0 :         if (wallType == "towers")
     124            0 :                 placePolygonalWall(position, 15, ["entry"], "tower", civ, playerID, orientation, 7);
     125            0 :         else if (wallType)
     126            0 :                 placeGenericFortress(position, 20, playerID);
     127              : }
     128              : 
     129              : /**
     130              :  * Places the civic center and starting resources for all given players.
     131              :  */
     132              : function placePlayerBases(playerBaseArgs)
     133              : {
     134            0 :         g_Map.log("Creating playerbases");
     135              : 
     136            0 :         const [playerIDs, playerPosition] = Array.isArray(playerBaseArgs.PlayerPlacement) ?
     137              :                 playerBaseArgs.PlayerPlacement : Object.values(playerBaseArgs.PlayerPlacement);
     138              : 
     139            0 :         for (let i = 0; i < getNumPlayers(); ++i)
     140              :         {
     141            0 :                 playerBaseArgs.playerID = playerIDs[i];
     142            0 :                 playerBaseArgs.playerPosition = playerPosition[i];
     143            0 :                 placePlayerBase(playerBaseArgs);
     144              :         }
     145              : }
     146              : 
     147              : /**
     148              :  * Places the civic center and starting resources.
     149              :  */
     150              : function placePlayerBase(playerBaseArgs)
     151              : {
     152            0 :         if (g_MapSettings.Nomad)
     153            0 :                 return;
     154              : 
     155            0 :         placeCivDefaultStartingEntities(
     156              :                 playerBaseArgs.playerPosition,
     157              :                 playerBaseArgs.playerID,
     158              :                 playerBaseArgs.Walls !== undefined ? playerBaseArgs.Walls : true,
     159              :                 6,
     160              :                 BUILDING_ORIENTATION);
     161              : 
     162            0 :         if (playerBaseArgs.PlayerTileClass)
     163            0 :                 addCivicCenterAreaToClass(playerBaseArgs.playerPosition, playerBaseArgs.PlayerTileClass);
     164              : 
     165            0 :         const baseResourceConstraint = new AndConstraint([
     166              :                 playerBaseArgs.BaseResourceClass ? avoidClasses(playerBaseArgs.BaseResourceClass, 4) : [],
     167              :                 playerBaseArgs.baseResourceConstraint || []
     168              :         ].flat());
     169              : 
     170            0 :         for (const functionID of g_PlayerBaseFunctions)
     171              :         {
     172            0 :                 const funcName = "placePlayerBase" + functionID;
     173            0 :                 const func = global[funcName];
     174            0 :                 if (!func)
     175            0 :                         throw new Error("Could not find " + funcName);
     176              : 
     177            0 :                 if (!playerBaseArgs[functionID])
     178            0 :                         continue;
     179              : 
     180            0 :                 const args = playerBaseArgs[functionID];
     181              : 
     182              :                 // Copy some global arguments to the arguments for each function
     183            0 :                 for (const prop of ["playerID", "playerPosition", "BaseResourceClass"])
     184            0 :                         args[prop] = playerBaseArgs[prop];
     185              : 
     186            0 :                 func(args, baseResourceConstraint);
     187              :         }
     188              : }
     189              : 
     190              : function defaultPlayerBaseRadius()
     191              : {
     192            0 :         return scaleByMapSize(15, 25);
     193              : }
     194              : 
     195              : /**
     196              :  * Marks the corner and center tiles of an area that is about the size of a Civic Center with the given TileClass.
     197              :  * Used to prevent resource collisions with the Civic Center.
     198              :  */
     199              : function addCivicCenterAreaToClass(position, tileClass)
     200              : {
     201            0 :         createArea(
     202              :                 new DiskPlacer(5, position),
     203              :                 new TileClassPainter(tileClass));
     204              : }
     205              : 
     206              : function placePlayerBaseCityPatch(args)
     207              : {
     208            0 :         let painters = [];
     209              : 
     210            0 :         if (args.outerTerrain && args.innerTerrain)
     211            0 :                 painters.push(new LayeredPainter([args.outerTerrain, args.innerTerrain], [args.width ?? 1]));
     212              : 
     213            0 :         if (args.painters)
     214            0 :                 painters = painters.concat(args.painters);
     215              : 
     216            0 :         createArea(
     217              :                 new ClumpPlacer(
     218              :                         Math.floor(diskArea(args.radius ?? (defaultPlayerBaseRadius() / 3))),
     219              :                         args.coherence ?? 0.6,
     220              :                         args.smoothness ?? 0.3,
     221              :                         args.failFraction ?? Infinity,
     222              :                         args.playerPosition),
     223              :                 painters);
     224              : }
     225              : 
     226              : function placePlayerBaseStartingAnimal(args, baseResourceConstraint)
     227              : {
     228            0 :         const template = args.template ?? "gaia/fauna_chicken";
     229            0 :         const count = template === "gaia/fauna_chicken" ? 5 :
     230              :                 Math.round(5 * (Engine.GetTemplate("gaia/fauna_chicken").ResourceSupply.Max / Engine.GetTemplate(args.template).ResourceSupply.Max));
     231              : 
     232            0 :         for (let i = 0; i < (args.groupCount ?? 2); ++i)
     233              :         {
     234            0 :                 let success = false;
     235            0 :                 for (let tries = 0; tries < (args.maxTries ?? 30); ++tries)
     236              :                 {
     237            0 :                         const position = new Vector2D(0, args.distance ?? 9).rotate(randomAngle()).add(
     238              :                                 args.playerPosition);
     239            0 :                         if (createObjectGroup(
     240              :                                 new SimpleGroup(
     241              :                                         [
     242              :                                                 new SimpleObject(
     243              :                                                         template,
     244              :                                                         args.minGroupCount ?? count,
     245              :                                                         args.maxGroupCount ?? count,
     246              :                                                         args.minGroupDistance ?? 0,
     247              :                                                         args.maxGroupDistance ?? 2)
     248              :                                         ],
     249              :                                         true,
     250              :                                         args.BaseResourceClass,
     251              :                                         position),
     252              :                                 0,
     253              :                                 baseResourceConstraint))
     254              :                         {
     255            0 :                                 success = true;
     256            0 :                                 break;
     257              :                         }
     258              :                 }
     259              : 
     260            0 :                 if (!success)
     261              :                 {
     262            0 :                         error("Could not place startingAnimal for player " + args.playerID);
     263            0 :                         return;
     264              :                 }
     265              :         }
     266              : }
     267              : 
     268              : function placePlayerBaseBerries(args, baseResourceConstraint)
     269              : {
     270            0 :         for (let tries = 0; tries < (args.maxTries ?? 30); ++tries)
     271              :         {
     272              :                 const position =
     273            0 :                         new Vector2D(0, args.distance ?? 12).rotate(randomAngle()).add(args.playerPosition);
     274            0 :                 if (createObjectGroup(
     275              :                         new SimpleGroup(
     276              :                                 [new SimpleObject(args.template, args.minCount ?? 5, args.maxCount ?? 5,
     277              :                                         args.minDist ?? 1, args.maxDist ?? 3)],
     278              :                                 true,
     279              :                                 args.BaseResourceClass,
     280              :                                 position),
     281              :                         0,
     282              :                         baseResourceConstraint))
     283            0 :                         return;
     284              :         }
     285              : 
     286            0 :         error("Could not place berries for player " + args.playerID);
     287              : }
     288              : 
     289              : function placePlayerBaseMines(args, baseResourceConstraint)
     290              : {
     291            0 :         const angleBetweenMines = randFloat(args.minAngle ?? (Math.PI / 6), args.maxAngle ?? (Math.PI / 3));
     292            0 :         const mineCount = args.types.length;
     293              : 
     294            0 :         let groupElements = [];
     295            0 :         if (args.groupElements)
     296            0 :                 groupElements = groupElements.concat(args.groupElements);
     297              : 
     298            0 :         for (let tries = 0; tries < (args.maxTries ?? 75); ++tries)
     299              :         {
     300              :                 // First find a place where all mines can be placed
     301            0 :                 let pos = [];
     302            0 :                 const startAngle = randomAngle();
     303            0 :                 for (let i = 0; i < mineCount; ++i)
     304              :                 {
     305            0 :                         const angle = startAngle + angleBetweenMines * (i + (mineCount - 1) / 2);
     306            0 :                         pos[i] = new Vector2D(0, args.distance ?? 12).rotate(angle).add(
     307              :                                 args.playerPosition).round();
     308            0 :                         if (!g_Map.validTilePassable(pos[i]) || !baseResourceConstraint.allows(pos[i]))
     309              :                         {
     310            0 :                                 pos = undefined;
     311            0 :                                 break;
     312              :                         }
     313              :                 }
     314              : 
     315            0 :                 if (!pos)
     316            0 :                         continue;
     317              : 
     318              :                 // Place the mines
     319            0 :                 for (let i = 0; i < mineCount; ++i)
     320              :                 {
     321            0 :                         if (args.types[i].type && args.types[i].type == "stone_formation")
     322              :                         {
     323            0 :                                 createStoneMineFormation(pos[i], args.types[i].template, args.types[i].terrain);
     324            0 :                                 args.BaseResourceClass.add(pos[i]);
     325            0 :                                 continue;
     326              :                         }
     327              : 
     328            0 :                         createObjectGroup(
     329              :                                 new SimpleGroup(
     330              :                                         [new SimpleObject(args.types[i].template, 1, 1, 0, 0)].concat(groupElements),
     331              :                                         true,
     332              :                                         args.BaseResourceClass,
     333              :                                         pos[i]),
     334              :                                 0);
     335              :                 }
     336            0 :                 return;
     337              :         }
     338              : 
     339            0 :         error("Could not place mines for player " + args.playerID);
     340              : }
     341              : 
     342              : function placePlayerBaseTrees(args, baseResourceConstraint)
     343              : {
     344            0 :         const num = Math.floor(args.count ?? scaleByMapSize(7, 20));
     345              : 
     346            0 :         for (let x = 0; x < (args.maxTries ?? 30); ++x)
     347              :         {
     348            0 :                 const position = new Vector2D(0, randFloat(args.minDist ?? 11, args.maxDist ?? 13))
     349              :                         .rotate(randomAngle()).add(args.playerPosition).round();
     350              : 
     351            0 :                 if (createObjectGroup(
     352              :                         new SimpleGroup(
     353              :                                 [new SimpleObject(args.template, num, num, args.minDistGroup ?? 0,
     354              :                                         args.maxDistGroup ?? 5)],
     355              :                                 false,
     356              :                                 args.BaseResourceClass,
     357              :                                 position),
     358              :                         0,
     359              :                         baseResourceConstraint))
     360            0 :                         return;
     361              :         }
     362              : 
     363            0 :         error("Could not place starting trees for player " + args.playerID);
     364              : }
     365              : 
     366              : function placePlayerBaseTreasures(args, baseResourceConstraint)
     367              : {
     368            0 :         for (const resourceTypeArgs of args.types)
     369              :         {
     370            0 :                 let success = false;
     371              : 
     372            0 :                 for (let tries = 0; tries < (resourceTypeArgs.maxTries ?? 30); ++tries)
     373              :                 {
     374            0 :                         const position = new Vector2D(0,
     375              :                                 randFloat(resourceTypeArgs.minDist ?? 11, resourceTypeArgs.maxDist ?? 13))
     376              :                                 .rotate(randomAngle()).add(args.playerPosition).round();
     377              : 
     378            0 :                         if (createObjectGroup(
     379              :                                 new SimpleGroup(
     380              :                                         [new SimpleObject(resourceTypeArgs.template, resourceTypeArgs.count ?? 14,
     381              :                                                 resourceTypeArgs.count ?? 14, resourceTypeArgs.minDistGroup ?? 1,
     382              :                                                 resourceTypeArgs.maxDistGroup ?? 3)],
     383              :                                         false,
     384              :                                         args.BaseResourceClass,
     385              :                                         position),
     386              :                                 0,
     387              :                                 baseResourceConstraint))
     388              :                         {
     389            0 :                                 success = true;
     390            0 :                                 break;
     391              :                         }
     392              :                 }
     393            0 :                 if (!success)
     394              :                 {
     395            0 :                         error("Could not place treasure " + resourceTypeArgs.template + " for player " + args.playerID);
     396            0 :                         return;
     397              :                 }
     398              :         }
     399              : }
     400              : 
     401              : /**
     402              :  * Typically used for placing grass tufts around the civic centers.
     403              :  */
     404              : function placePlayerBaseDecoratives(args, baseResourceConstraint)
     405              : {
     406            0 :         for (let i = 0; i < (args.count ?? scaleByMapSize(2, 5)); ++i)
     407              :         {
     408            0 :                 let success = false;
     409            0 :                 for (let x = 0; x < (args.maxTries ?? 30); ++x)
     410              :                 {
     411            0 :                         const position = new Vector2D(0,
     412              :                                 randIntInclusive(args.minDist ?? 8, args.maxDist ?? 11))
     413              :                                 .rotate(randomAngle()).add(args.playerPosition).round();
     414              : 
     415            0 :                         if (createObjectGroup(
     416              :                                 new SimpleGroup(
     417              :                                         [new SimpleObject(args.template, args.minCount ?? 2, args.maxCount ?? 5, 0,
     418              :                                                 1)],
     419              :                                         false,
     420              :                                         args.BaseResourceClass,
     421              :                                         position),
     422              :                                 0,
     423              :                                 baseResourceConstraint))
     424              :                         {
     425            0 :                                 success = true;
     426            0 :                                 break;
     427              :                         }
     428              :                 }
     429            0 :                 if (!success)
     430              :                         // Don't warn since the decoratives are not important
     431            0 :                         return;
     432              :         }
     433              : }
     434              : 
     435              : function placePlayersNomad(playerClass, constraints)
     436              : {
     437            0 :         if (!g_MapSettings.Nomad)
     438            0 :                 return undefined;
     439              : 
     440            0 :         g_Map.log("Placing nomad starting units");
     441              : 
     442            0 :         const distance = scaleByMapSize(60, 240);
     443            0 :         const constraint = new StaticConstraint(constraints);
     444              : 
     445            0 :         const numPlayers = getNumPlayers();
     446            0 :         const playerIDs = shuffleArray(getPlayerIDs());
     447            0 :         const playerPosition = [];
     448              : 
     449            0 :         for (let i = 0; i < numPlayers; ++i)
     450              :         {
     451            0 :                 const objects = getStartingEntities(playerIDs[i]).filter(ents => ents.Template.startsWith("units/")).map(
     452            0 :                         ents => new SimpleObject(ents.Template, ents.Count || 1, ents.Count || 1, 1, 3));
     453              : 
     454              :                 // Add treasure if too few resources for a civic center
     455            0 :                 const ccCost = Engine.GetTemplate("structures/" + getCivCode(playerIDs[i]) + "/civil_centre").Cost.Resources;
     456            0 :                 for (const resourceType in ccCost)
     457              :                 {
     458            0 :                         const treasureTemplate = g_NomadTreasureTemplates[resourceType];
     459              : 
     460            0 :                         const count = Math.max(0, Math.ceil(
     461              :                                 (ccCost[resourceType] - (g_MapSettings.StartingResources || 0)) /
     462              :                                 Engine.GetTemplate(treasureTemplate).Treasure.Resources[resourceType]));
     463              : 
     464            0 :                         objects.push(new SimpleObject(treasureTemplate, count, count, 3, 5));
     465              :                 }
     466              : 
     467              :                 // Try place these entities at a random location
     468            0 :                 const group = new SimpleGroup(objects, true, playerClass);
     469            0 :                 let success = false;
     470            0 :                 for (const distanceFactor of [1, 1/2, 1/4, 0])
     471            0 :                         if (createObjectGroups(group, playerIDs[i], new AndConstraint([constraint, avoidClasses(playerClass, distance * distanceFactor)]), 1, 200, false).length)
     472              :                         {
     473            0 :                                 success = true;
     474            0 :                                 playerPosition[i] = group.centerPosition;
     475            0 :                                 break;
     476              :                         }
     477              : 
     478            0 :                 if (!success)
     479            0 :                         throw new Error("Could not place starting units for player " + playerIDs[i] + "!");
     480              :         }
     481              : 
     482            0 :         return [playerIDs, playerPosition];
     483              : }
     484              : 
     485              : /**
     486              :  * Get the player IDs
     487              :  *
     488              :  * @returns {Array} - an array with sequential integers from 1 to the number of players
     489              :  */
     490              : function getPlayerIDs()
     491              : {
     492            0 :         return Array.from(Array(getNumPlayers()), (_, index) => index + 1);
     493              : }
     494              : 
     495              : /**
     496              :  * Sorts an array of player IDs by team index.
     497              :  * Players without teams come first. Randomize order for players of the same team.
     498              :  */
     499              : function sortPlayers(playerIDs)
     500              : {
     501            0 :         return shuffleArray(playerIDs).sort((playerID1, playerID2) => getPlayerTeam(playerID1) - getPlayerTeam(playerID2));
     502              : }
     503              : 
     504              : /**
     505              :  * Randomize playerIDs but sort by team.
     506              :  *
     507              :  * @returns {Array} - every item is an array of player indices
     508              :  */
     509              : function sortAllPlayers()
     510              : {
     511            0 :         return sortPlayers(getPlayerIDs());
     512              : }
     513              : 
     514              : /**
     515              :  * Rearrange order so that teams of neighboring players alternate (if the given IDs are sorted by team).
     516              :  */
     517              : function primeSortPlayers(playerIDs)
     518              : {
     519            0 :         const prime = [];
     520            0 :         for (let i = 0; i < Math.floor(playerIDs.length / 2); ++i)
     521              :         {
     522            0 :                 prime.push(playerIDs[i]);
     523            0 :                 prime.push(playerIDs[playerIDs.length - 1 - i]);
     524              :         }
     525              : 
     526            0 :         if (playerIDs.length % 2)
     527            0 :                 prime.push(playerIDs[Math.floor(playerIDs.length / 2)]);
     528              : 
     529            0 :         return prime;
     530              : }
     531              : 
     532              : function primeSortAllPlayers()
     533              : {
     534            0 :         return primeSortPlayers(sortAllPlayers());
     535              : }
     536              : 
     537              : /*
     538              :  * Separates playerIDs into two arrays such that teammates are in the same array,
     539              :  * unless everyone's on the same team in which case they'll be split in half.
     540              :  */
     541              : function partitionPlayers(playerIDs)
     542              : {
     543            0 :         const teamIDs = Array.from(new Set(playerIDs.map(getPlayerTeam)));
     544            0 :         let teams = teamIDs.map(teamID => playerIDs.filter(playerID => getPlayerTeam(playerID) == teamID));
     545            0 :         if (teamIDs.indexOf(-1) != -1)
     546            0 :                 teams = teams.concat(teams.splice(teamIDs.indexOf(-1), 1)[0].map(playerID => [playerID]));
     547              : 
     548            0 :         if (teams.length == 1)
     549              :         {
     550            0 :                 const idx = Math.floor(teams[0].length / 2);
     551            0 :                 teams = [teams[0].slice(idx), teams[0].slice(0, idx)];
     552              :         }
     553              : 
     554            0 :         teams.sort((a, b) => b.length - a.length);
     555              : 
     556              :         // Use the greedy algorithm: add the next team to the side with fewer players
     557            0 :         return teams.reduce(([east, west], team) =>
     558            0 :                 east.length > west.length ?
     559              :                         [east, west.concat(team)] :
     560              :                         [east.concat(team), west],
     561              :         [[], []]);
     562              : }
     563              : 
     564              : /**
     565              :  * Return an array where each element is an array of playerIndices of a team.
     566              :  */
     567              : function getTeamsArray()
     568              : {
     569            0 :         const playerIDs = getPlayerIDs();
     570            0 :         const numPlayers = getNumPlayers();
     571              : 
     572              :         // Group players by team
     573            0 :         const teams = [];
     574            0 :         for (let i = 0; i < numPlayers; ++i)
     575              :         {
     576            0 :                 const team = getPlayerTeam(playerIDs[i]);
     577            0 :                 if (team == -1)
     578            0 :                         continue;
     579              : 
     580            0 :                 if (!teams[team])
     581            0 :                         teams[team] = [];
     582              : 
     583            0 :                 teams[team].push(playerIDs[i]);
     584              :         }
     585              : 
     586              :         // Players without a team get a custom index
     587            0 :         for (let i = 0; i < numPlayers; ++i)
     588            0 :                 if (getPlayerTeam(playerIDs[i]) == -1)
     589            0 :                         teams.push([playerIDs[i]]);
     590              : 
     591              :         // Remove unused indices
     592            0 :         return teams.filter(team => true);
     593              : }
     594              : 
     595              : /**
     596              :  * Determine player starting positions based on the specified pattern.
     597              :  */
     598              : function playerPlacementByPattern(patternName, distance = undefined, groupedDistance = undefined, angle = undefined, center = undefined)
     599              : {
     600            0 :         if (patternName === undefined)
     601            0 :                 patternName = g_MapSettings.PlayerPlacement;
     602              : 
     603            0 :         switch (patternName)
     604              :         {
     605              :         case "circle":
     606            0 :                 return playerPlacementCircle(distance, angle, center);
     607              :         case "river":
     608            0 :                 return playerPlacementRiver(angle, distance, center);
     609              :         case "groupedLines":
     610            0 :                 return placeLine(getTeamsArray(), distance, groupedDistance, angle);
     611              :         case "stronghold":
     612            0 :                 return placeStronghold(getTeamsArray(), distance, groupedDistance * 1.4, angle);
     613              :         case "randomGroup":
     614            0 :                 return playerPlacementRandom(getPlayerIDs(), undefined);
     615              :         default:
     616            0 :                 throw new Error("Unknown placement pattern: " + patternName);
     617              :         }
     618              : }
     619              : 
     620              : /**
     621              :  * Determine player starting positions on a circular pattern.
     622              :  */
     623              : function playerPlacementCircle(radius, startingAngle = undefined, center = undefined)
     624              : {
     625            0 :         const startAngle = startingAngle !== undefined ? startingAngle : randomAngle();
     626            0 :         const [playerPosition, playerAngle] = distributePointsOnCircle(getNumPlayers(), startAngle, radius, center || g_Map.getCenter());
     627            0 :         return {
     628              :                 "playerIDs": getPlayerIDs(),
     629            0 :                 "playerPosition": playerPosition.map(p => p.round()),
     630              :                 "playerAngle": playerAngle,
     631              :                 "startAngle": startAngle
     632              :         };
     633              : }
     634              : 
     635              : /**
     636              :  * Determine player starting positions on a circular pattern, with a custom angle for each player.
     637              :  * Commonly used for gulf terrains.
     638              :  */
     639              : function playerPlacementCustomAngle(radius, center, playerAngleFunc)
     640              : {
     641            0 :         const playerPosition = [];
     642            0 :         const playerAngle = [];
     643              : 
     644            0 :         const numPlayers = getNumPlayers();
     645              : 
     646            0 :         for (let i = 0; i < numPlayers; ++i)
     647              :         {
     648            0 :                 playerAngle[i] = playerAngleFunc(i);
     649            0 :                 playerPosition[i] = Vector2D.add(center, new Vector2D(radius, 0).rotate(-playerAngle[i])).round();
     650              :         }
     651              : 
     652            0 :         return [playerPosition, playerAngle];
     653              : }
     654              : 
     655              : /**
     656              :  * Returns player starting positions equally spaced along an arc.
     657              :  */
     658              : function playerPlacementArc(playerIDs, center, radius, startAngle, endAngle)
     659              : {
     660            0 :         return distributePointsOnCircularSegment(
     661              :                 playerIDs.length + 2,
     662              :                 endAngle - startAngle,
     663              :                 startAngle,
     664              :                 radius,
     665              :                 center
     666            0 :         )[0].slice(1, -1).map(p => p.round());
     667              : }
     668              : 
     669              : /**
     670              :  * Returns player starting positions located on two symmetrically placed arcs, with teammates placed on the same arc.
     671              :  */
     672              : function playerPlacementArcs(playerIDs, center, radius, mapAngle, startAngle, endAngle)
     673              : {
     674            0 :         const [east, west] = partitionPlayers(playerIDs);
     675            0 :         const eastPosition = playerPlacementArc(east, center, radius, mapAngle + startAngle, mapAngle + endAngle);
     676            0 :         const westPosition = playerPlacementArc(west, center, radius, mapAngle - startAngle, mapAngle - endAngle);
     677            0 :         return playerIDs.map(playerID => east.indexOf(playerID) != -1 ?
     678              :                 eastPosition[east.indexOf(playerID)] :
     679              :                 westPosition[west.indexOf(playerID)]);
     680              : }
     681              : 
     682              : /**
     683              :  * Returns player starting positions located on two parallel lines, typically used by central river maps.
     684              :  * If there are two teams with an equal number of players, each team will occupy exactly one line.
     685              :  * Angle 0 means the players are placed in north to south direction, i.e. along the Z axis.
     686              :  */
     687              : function playerPlacementRiver(angle, width, center = undefined)
     688              : {
     689            0 :         const numPlayers = getNumPlayers();
     690            0 :         const numPlayersEven = numPlayers % 2 == 0;
     691            0 :         const mapSize = g_Map.getSize();
     692            0 :         const centerPosition = center || g_Map.getCenter();
     693            0 :         const playerPosition = [];
     694              : 
     695            0 :         for (let i = 0; i < numPlayers; ++i)
     696              :         {
     697            0 :                 const currentPlayerEven = i % 2 == 0;
     698              : 
     699            0 :                 const offsetDivident = numPlayersEven || currentPlayerEven ? (i + 1) % 2 : 0;
     700            0 :                 const offsetDivisor = numPlayersEven ? 0 : currentPlayerEven ? +1 : -1;
     701              : 
     702            0 :                 playerPosition[i] = new Vector2D(
     703              :                         width * (i % 2) + (mapSize - width) / 2,
     704              :                         fractionToTiles(((i - 1 + offsetDivident) / 2 + 1) / ((numPlayers + offsetDivisor) / 2 + 1))
     705              :                 ).rotateAround(angle, centerPosition).round();
     706              :         }
     707              : 
     708            0 :         return groupPlayersByArea(new Array(numPlayers).fill(0).map((_p, i) => i + 1), playerPosition);
     709              : }
     710              : 
     711              : /**
     712              :  * Returns starting positions located on two parallel lines.
     713              :  * The locations on the first line are shifted in comparison to the other line.
     714              :  */
     715              : function playerPlacementLine(angle, center, width)
     716              : {
     717            0 :         const playerPosition = [];
     718            0 :         const numPlayers = getNumPlayers();
     719              : 
     720            0 :         for (let i = 0; i < numPlayers; ++i)
     721            0 :                 playerPosition[i] = Vector2D.add(
     722              :                         center,
     723              :                         new Vector2D(
     724              :                                 fractionToTiles((i + 1) / (numPlayers + 1) - 0.5),
     725              :                                 width * (i % 2 - 1/2)
     726              :                         ).rotate(angle)
     727              :                 ).round();
     728              : 
     729            0 :         return playerPosition;
     730              : }
     731              : 
     732              : /**
     733              :  * Place teams in a line-pattern.
     734              :  *
     735              :  * @param {Array} playerIDs - typically randomized indices of players of a single team
     736              :  * @param {number} distance - radial distance from the center of the map
     737              :  * @param {number} groupedDistance - distance between players
     738              :  * @param {number} startAngle - determined by the map that might want to place something between players.
     739              :  *
     740              :  * @returns {Array} - contains id, angle, x, z for every player
     741              :  */
     742              : function placeLine(teamsArray, distance, groupedDistance, startAngle)
     743              : {
     744            0 :         const playerIDs = [];
     745            0 :         const playerPosition = [];
     746              : 
     747            0 :         const mapCenter = g_Map.getCenter();
     748            0 :         const numAcross = 2 * getNumPlayers() / teamsArray.length; // if its two teams, numAcross is the same as numPlayers.
     749            0 :         const dist = fractionToTiles(numAcross == 2 ? 0.45 : 0.66 + (-0.01 * numAcross));
     750            0 :         groupedDistance *= (3.00 + (-0.225 * numAcross));
     751            0 :         for (let i = 0; i < teamsArray.length; ++i)
     752              :         {
     753            0 :                 let safeDist = distance;
     754            0 :                 if (distance + teamsArray[i].length * groupedDistance > dist)
     755            0 :                         safeDist = dist - teamsArray[i].length * groupedDistance;
     756              : 
     757            0 :                 const teamAngle = startAngle + (i + 1) * 2 * Math.PI / teamsArray.length;
     758              : 
     759            0 :                 for (let p = 0; p < teamsArray[i].length; ++p)
     760              :                 {
     761            0 :                         playerIDs.push(teamsArray[i][p]);
     762            0 :                         playerPosition.push(Vector2D.add(mapCenter, new Vector2D(safeDist + p * groupedDistance, 0).rotate(-teamAngle)).round());
     763              :                 }
     764              :         }
     765              : 
     766            0 :         return {
     767              :                 "playerIDs": playerIDs,
     768              :                 "playerPosition": playerPosition
     769              :         };
     770              : }
     771              : 
     772              : /**
     773              :  * Place given players in a stronghold-pattern.
     774              :  *
     775              :  * @param teamsArray - each item is an array of playerIDs placed per stronghold
     776              :  * @param distance - radial distance from the center of the map
     777              :  * @param groupedDistance - distance between neighboring players
     778              :  * @param {number} startAngle - determined by the map that might want to place something between players
     779              :  */
     780              : function placeStronghold(teamsArray, distance, groupedDistance, startAngle)
     781              : {
     782            0 :         const mapCenter = g_Map.getCenter();
     783              : 
     784            0 :         const playerIDs = [];
     785            0 :         const playerPosition = [];
     786            0 :         const teamPositions = [];
     787            0 :         const strongholdRadius = teamsArray.map(team =>
     788              :         {
     789              :                 // If we have a solo player, place them on the center of the team's location
     790            0 :                 if (team.length == 1)
     791            0 :                         return 0;
     792              : 
     793            0 :                 return groupedDistance / 2 / Math.sin(Math.PI / team.length);
     794              :         });
     795              : 
     796            0 :         const distanceBetweenStrongholds = (distance * 2 * Math.PI -
     797            0 :                 2 * strongholdRadius.reduce((a, b) => a + b)) / strongholdRadius.length;
     798              : 
     799            0 :         const relativeTeamAngles = strongholdRadius.map((r1, i) =>
     800              :         {
     801            0 :                 return (distanceBetweenStrongholds + strongholdRadius.at(i - 1) + r1) / distance;
     802              :         });
     803              : 
     804            0 :         const teamAngles = relativeTeamAngles.reduce((acc, angle, i) =>
     805              :         {
     806            0 :                 acc.push((i === 0 ? startAngle : acc.at(-1)) + angle);
     807            0 :                 return acc;
     808              :         }, []);
     809              : 
     810            0 :         for (let i = 0; i < teamsArray.length; ++i)
     811              :         {
     812            0 :                 const teamPosition = Vector2D.add(mapCenter,
     813              :                         new Vector2D(distance * 0.8, 0).rotate(-teamAngles[i]));
     814              : 
     815              :                 // TODO: Ensure players are not placed outside of the map area, similar to placeLine
     816              : 
     817              :                 // Create player base
     818            0 :                 for (let p = 0; p < teamsArray[i].length; ++p)
     819              :                 {
     820            0 :                         const angle = startAngle + (p + 1) * 2 * Math.PI / teamsArray[i].length;
     821            0 :                         playerIDs.push(teamsArray[i][p]);
     822            0 :                         playerPosition.push(Vector2D.add(teamPosition,
     823              :                                 new Vector2D(strongholdRadius[i], 0).rotate(-angle)).round());
     824              :                 }
     825            0 :                 teamPositions.push(teamPosition);
     826              :         }
     827              : 
     828            0 :         return {
     829              :                 "playerIDs": playerIDs,
     830              :                 "playerPosition": playerPosition,
     831              :                 "teamPosition": teamPositions,
     832              :                 "teamAngle": teamAngles,
     833              :                 "strongholdRadius": strongholdRadius
     834              :         };
     835              : }
     836              : 
     837              : /**
     838              :  * Returns a random location for each player that meets the given constraints and
     839              :  * orders the playerIDs so that players become grouped by team.
     840              :  */
     841              : function playerPlacementRandom(playerIDs, constraints = undefined)
     842              : {
     843            0 :         let locations = [];
     844            0 :         let attempts = 0;
     845            0 :         let resets = 0;
     846              : 
     847            0 :         const mapCenter = g_Map.getCenter();
     848            0 :         let playerMinDistSquared = Math.square(fractionToTiles(0.25));
     849            0 :         const borderDistance = fractionToTiles(0.08);
     850              : 
     851            0 :         const area = createArea(new MapBoundsPlacer(), undefined, new AndConstraint(constraints));
     852              : 
     853            0 :         for (let i = 0; i < getNumPlayers(); ++i)
     854              :         {
     855            0 :                 const position = pickRandom(area.getPoints());
     856            0 :                 if (!position)
     857            0 :                         return undefined;
     858              : 
     859              :                 // Minimum distance between initial bases must be a quarter of the map diameter
     860            0 :                 if (locations.some(loc => loc.distanceToSquared(position) < playerMinDistSquared) ||
     861              :                     position.distanceToSquared(mapCenter) > Math.square(mapCenter.x - borderDistance))
     862              :                 {
     863            0 :                         --i;
     864            0 :                         ++attempts;
     865              : 
     866              :                         // Reset if we're in what looks like an infinite loop
     867            0 :                         if (attempts > 500)
     868              :                         {
     869            0 :                                 locations = [];
     870            0 :                                 i = -1;
     871            0 :                                 attempts = 0;
     872            0 :                                 ++resets;
     873              : 
     874              :                                 // Reduce minimum player distance progressively
     875            0 :                                 if (resets % 25 == 0)
     876            0 :                                         playerMinDistSquared *= 0.95;
     877              : 
     878              :                                 // If we only pick bad locations, stop trying to place randomly
     879            0 :                                 if (resets == 500)
     880            0 :                                         return undefined;
     881              :                         }
     882            0 :                         continue;
     883              :                 }
     884              : 
     885            0 :                 locations[i] = position;
     886              :         }
     887            0 :         return groupPlayersByArea(playerIDs, locations);
     888              : }
     889              : 
     890              : /**
     891              :  *  Pick locations from the given set so that teams end up grouped.
     892              :  */
     893              : function groupPlayersByArea(playerIDs, locations)
     894              : {
     895            0 :         playerIDs = sortPlayers(playerIDs);
     896              : 
     897            0 :         let minDist = Infinity;
     898              :         let minLocations;
     899              : 
     900              :         // Of all permutations of starting locations, find the one where
     901              :         // the sum of the distances between allies is minimal, weighted by teamsize.
     902            0 :         heapsPermute(shuffleArray(locations).slice(0, playerIDs.length), v => v.clone(), permutation =>
     903              :         {
     904            0 :                 let dist = 0;
     905            0 :                 let teamDist = 0;
     906            0 :                 let teamSize = 0;
     907              : 
     908            0 :                 for (let i = 1; i < playerIDs.length; ++i)
     909              :                 {
     910            0 :                         const team1 = getPlayerTeam(playerIDs[i - 1]);
     911            0 :                         const team2 = getPlayerTeam(playerIDs[i]);
     912            0 :                         ++teamSize;
     913            0 :                         if (team1 != -1 && team1 == team2)
     914            0 :                                 teamDist += permutation[i - 1].distanceTo(permutation[i]);
     915              :                         else
     916              :                         {
     917            0 :                                 dist += teamDist / teamSize;
     918            0 :                                 teamDist = 0;
     919            0 :                                 teamSize = 0;
     920              :                         }
     921              :                 }
     922              : 
     923            0 :                 if (teamSize)
     924            0 :                         dist += teamDist / teamSize;
     925              : 
     926            0 :                 if (dist < minDist)
     927              :                 {
     928            0 :                         minDist = dist;
     929            0 :                         minLocations = permutation;
     930              :                 }
     931              :         });
     932              : 
     933            0 :         return {
     934              :                 "playerIDs": playerIDs,
     935              :                 "playerPosition": minLocations
     936              :         };
     937              : }
     938              : 
     939              : /**
     940              :  * Sorts the playerIDs so that team members are as close as possible on a ring.
     941              :  */
     942              : function groupPlayersCycle(startLocations)
     943              : {
     944            0 :         const startLocationOrder = sortPointsShortestCycle(startLocations);
     945              : 
     946            0 :         const newStartLocations = [];
     947            0 :         for (let i = 0; i < startLocations.length; ++i)
     948            0 :                 newStartLocations.push(startLocations[startLocationOrder[i]]);
     949              : 
     950            0 :         startLocations = newStartLocations;
     951              : 
     952              :         // Sort players by team
     953            0 :         let playerIDs = [];
     954            0 :         const teams = [];
     955            0 :         for (let i = 0; i < g_MapSettings.PlayerData.length - 1; ++i)
     956              :         {
     957            0 :                 playerIDs.push(i+1);
     958            0 :                 const t = g_MapSettings.PlayerData[i + 1].Team;
     959            0 :                 if (teams.indexOf(t) == -1 && t !== undefined)
     960            0 :                         teams.push(t);
     961              :         }
     962              : 
     963            0 :         playerIDs = sortPlayers(playerIDs);
     964              : 
     965            0 :         if (!teams.length)
     966            0 :                 return [playerIDs, startLocations];
     967              : 
     968              :         // Minimize maximum distance between players within a team
     969            0 :         let minDistance = Infinity;
     970              :         let bestShift;
     971            0 :         for (let s = 0; s < playerIDs.length; ++s)
     972              :         {
     973            0 :                 let maxTeamDist = 0;
     974            0 :                 for (let pi = 0; pi < playerIDs.length - 1; ++pi)
     975              :                 {
     976            0 :                         const t1 = getPlayerTeam(playerIDs[(pi + s) % playerIDs.length]);
     977              : 
     978            0 :                         if (teams.indexOf(t1) === -1)
     979            0 :                                 continue;
     980              : 
     981            0 :                         for (let pj = pi + 1; pj < playerIDs.length; ++pj)
     982              :                         {
     983            0 :                                 if (t1 != getPlayerTeam(playerIDs[(pj + s) % playerIDs.length]))
     984            0 :                                         continue;
     985              : 
     986            0 :                                 maxTeamDist = Math.max(
     987              :                                         maxTeamDist,
     988              :                                         Math.euclidDistance2D(
     989              :                                                 startLocations[pi].x,
     990              :                                                 startLocations[pi].y,
     991              :                                                 startLocations[pj].x,
     992              :                                                 startLocations[pj].y));
     993              :                         }
     994              :                 }
     995              : 
     996            0 :                 if (maxTeamDist < minDistance)
     997              :                 {
     998            0 :                         minDistance = maxTeamDist;
     999            0 :                         bestShift = s;
    1000              :                 }
    1001              :         }
    1002              : 
    1003            0 :         if (bestShift)
    1004              :         {
    1005            0 :                 const newPlayerIDs = [];
    1006            0 :                 for (let i = 0; i < playerIDs.length; ++i)
    1007            0 :                         newPlayerIDs.push(playerIDs[(i + bestShift) % playerIDs.length]);
    1008            0 :                 playerIDs = newPlayerIDs;
    1009              :         }
    1010              : 
    1011            0 :         return [playerIDs, startLocations];
    1012              : }
        

Generated by: LCOV version 2.0-1