src/town_cmd.cpp
branchgamebalance
changeset 9908 0fa543611bbe
parent 9906 6f41b8713b65
child 9909 dce9a6923bb7
equal deleted inserted replaced
9907:3b068c3a1c74 9908:0fa543611bbe
   150 	DrawGroundSprite(image, pal);
   150 	DrawGroundSprite(image, pal);
   151 
   151 
   152 	/* Add a house on top of the ground? */
   152 	/* Add a house on top of the ground? */
   153 	image = dcts->building.sprite;
   153 	image = dcts->building.sprite;
   154 	if (image != 0) {
   154 	if (image != 0) {
   155 		if (_display_opt & DO_TRANS_BUILDINGS) {
   155 		if (HASBIT(_transparent_opt, TO_HOUSES)) {
   156 			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
   156 			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
   157 			pal = PALETTE_TO_TRANSPARENT;
   157 			pal = PALETTE_TO_TRANSPARENT;
   158 		} else {
   158 		} else {
   159 			pal = dcts->building.pal;
   159 			pal = dcts->building.pal;
   160 		}
   160 		}
   166 			dcts->height + 1,
   166 			dcts->height + 1,
   167 			dcts->dz,
   167 			dcts->dz,
   168 			ti->z
   168 			ti->z
   169 		);
   169 		);
   170 
   170 
   171 		if (_display_opt & DO_TRANS_BUILDINGS) return;
   171 		if (HASBIT(_transparent_opt, TO_HOUSES)) return;
   172 	}
   172 	}
   173 
   173 
   174 	{
   174 	{
   175 		int proc = dcts->draw_proc - 1;
   175 		int proc = dcts->draw_proc - 1;
   176 
   176 
   197 		return;
   197 		return;
   198 	}
   198 	}
   199 
   199 
   200 	if (_tick_counter & 3) return;
   200 	if (_tick_counter & 3) return;
   201 
   201 
   202 	// If the house is not one with a lift anymore, then stop this animating.
   202 	/* If the house is not one with a lift anymore, then stop this animating.
   203 	// Not exactly sure when this happens, but probably when a house changes.
   203 	 * Not exactly sure when this happens, but probably when a house changes.
   204 	// Before this was just a return...so it'd leak animated tiles..
   204 	 * Before this was just a return...so it'd leak animated tiles..
   205 	// That bug seems to have been here since day 1??
   205 	 * That bug seems to have been here since day 1?? */
   206 	if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
   206 	if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
   207 		DeleteAnimatedTile(tile);
   207 		DeleteAnimatedTile(tile);
   208 		return;
   208 		return;
   209 	}
   209 	}
   210 
   210 
   211 	if (!LiftHasDestination(tile)) {
   211 	if (!LiftHasDestination(tile)) {
   212 		int i;
   212 		int i;
   213 
   213 
   214 		/** Building has 6 floors, number 0 .. 6, where 1 is illegal.
   214 		/*  Building has 6 floors, number 0 .. 6, where 1 is illegal.
   215 		 *  This is due to the fact that the first floor is, in the graphics,
   215 		 *  This is due to the fact that the first floor is, in the graphics,
   216 		 *  the height of 2 'normal' floors.
   216 		 *  the height of 2 'normal' floors.
   217 		 *  Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
   217 		 *  Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
   218 		do {
   218 		do {
   219 			i = (Random() & 7) - 1;
   219 			i = (Random() & 7) - 1;
   327 	/* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
   327 	/* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
   328 	 * doesn't exist any more, so don't continue here. */
   328 	 * doesn't exist any more, so don't continue here. */
   329 	if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
   329 	if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
   330 
   330 
   331 	if (!IsHouseCompleted(tile)) {
   331 	if (!IsHouseCompleted(tile)) {
   332 		/*Construction is not completed. See if we can go further in construction*/
   332 		/* Construction is not completed. See if we can go further in construction*/
   333 		MakeTownHouseBigger(tile);
   333 		MakeTownHouseBigger(tile);
   334 		return;
   334 		return;
   335 	}
   335 	}
   336 
   336 
   337 	/* If the lift has a destination, it is already an animated tile. */
   337 	/* If the lift has a destination, it is already an animated tile. */
   356 	}
   356 	}
   357 
   357 
   358 	_current_player = OWNER_TOWN;
   358 	_current_player = OWNER_TOWN;
   359 
   359 
   360 	if (hs->building_flags & BUILDING_HAS_1_TILE && HASBIT(t->flags12, TOWN_IS_FUNDED) && CanDeleteHouse(tile) && --t->time_until_rebuild == 0) {
   360 	if (hs->building_flags & BUILDING_HAS_1_TILE && HASBIT(t->flags12, TOWN_IS_FUNDED) && CanDeleteHouse(tile) && --t->time_until_rebuild == 0) {
   361 		t->time_until_rebuild = GB(r, 16, 6) + 130;
   361 		t->time_until_rebuild = GB(r, 16, 8) + 192;
   362 
   362 
   363 		ClearTownHouse(t, tile);
   363 		ClearTownHouse(t, tile);
   364 
   364 
   365 		// rebuild with another house?
   365 		/* Rebuild with another house? */
   366 		if (GB(r, 24, 8) >= 12) DoBuildTownHouse(t, tile);
   366 		if (GB(r, 24, 8) >= 12) DoBuildTownHouse(t, tile);
   367 	}
   367 	}
   368 
   368 
   369 	_current_player = OWNER_NONE;
   369 	_current_player = OWNER_NONE;
   370 }
   370 }
   439 	{ 0, -1},
   439 	{ 0, -1},
   440 	{ 1,  0},
   440 	{ 1,  0},
   441 	{ 0,  1},
   441 	{ 0,  1},
   442 	{-1,  0},
   442 	{-1,  0},
   443 
   443 
   444 	// Store the first 3 elements again.
   444 	/* Store the first 3 elements again.
   445 	// Lets us rotate without using &3.
   445 	 * Lets us rotate without using &3. */
   446 	{ 0, -1},
   446 	{ 0, -1},
   447 	{ 1,  0},
   447 	{ 1,  0},
   448 	{ 0,  1}
   448 	{ 0,  1}
   449 };
   449 };
   450 
   450 
   503 static bool IsRoadAllowedHere(TileIndex tile, int dir)
   503 static bool IsRoadAllowedHere(TileIndex tile, int dir)
   504 {
   504 {
   505 	Slope k;
   505 	Slope k;
   506 	Slope slope;
   506 	Slope slope;
   507 
   507 
   508 	// If this assertion fails, it might be because the world contains
   508 	/* If this assertion fails, it might be because the world contains
   509 	//  land at the edges. This is not ok.
   509 	 *  land at the edges. This is not ok. */
   510 	TILE_ASSERT(tile);
   510 	TILE_ASSERT(tile);
   511 
   511 
   512 	for (;;) {
   512 	for (;;) {
   513 		// Check if there already is a road at this point?
   513 		/* Check if there already is a road at this point? */
   514 		if (GetAnyRoadTrackBits(tile) == 0) {
   514 		if (GetAnyRoadTrackBits(tile) == 0) {
   515 			// No, try to build one in the direction.
   515 			/* No, try to build one in the direction.
   516 			// if that fails clear the land, and if that fails exit.
   516 			 * if that fails clear the land, and if that fails exit.
   517 			// This is to make sure that we can build a road here later.
   517 			 * This is to make sure that we can build a road here later. */
   518 			if (CmdFailed(DoCommand(tile, (dir & 1 ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
   518 			if (CmdFailed(DoCommand(tile, (dir & 1 ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
   519 					CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
   519 					CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
   520 				return false;
   520 				return false;
   521 		}
   521 		}
   522 
   522 
   523 		slope = GetTileSlope(tile, NULL);
   523 		slope = GetTileSlope(tile, NULL);
   524 		if (slope == SLOPE_FLAT) {
   524 		if (slope == SLOPE_FLAT) {
   525 no_slope:
   525 no_slope:
   526 			// Tile has no slope
   526 			/* Tile has no slope
   527 			// Disallow the road if any neighboring tile has a road.
   527 			 * Disallow the road if any neighboring tile has a road. */
   528 			if (HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+1]))), dir^2) ||
   528 			if (HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+1]))), dir^2) ||
   529 					HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+3]))), dir^2) ||
   529 					HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+3]))), dir^2) ||
   530 					HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+1]) + ToTileIndexDiff(_roadblock_tileadd[dir+2]))), dir) ||
   530 					HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+1]) + ToTileIndexDiff(_roadblock_tileadd[dir+2]))), dir) ||
   531 					HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+3]) + ToTileIndexDiff(_roadblock_tileadd[dir+2]))), dir))
   531 					HASBIT(GetTownRoadMask(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[dir+3]) + ToTileIndexDiff(_roadblock_tileadd[dir+2]))), dir))
   532 				return false;
   532 				return false;
   533 
   533 
   534 			// Otherwise allow
   534 			/* Otherwise allow */
   535 			return true;
   535 			return true;
   536 		}
   536 		}
   537 
   537 
   538 		// If the tile is not a slope in the right direction, then
   538 		/* If the tile is not a slope in the right direction, then
   539 		// maybe terraform some.
   539 		 * maybe terraform some. */
   540 		k = (dir & 1) ? SLOPE_NE : SLOPE_NW;
   540 		k = (dir & 1) ? SLOPE_NE : SLOPE_NW;
   541 		if (k != slope && ComplementSlope(k) != slope) {
   541 		if (k != slope && ComplementSlope(k) != slope) {
   542 			uint32 r = Random();
   542 			uint32 r = Random();
   543 
   543 
   544 			if (CHANCE16I(1, 8, r) && !_generating_world) {
   544 			if (CHANCE16I(1, 8, r) && !_generating_world) {
   550 				} else {
   550 				} else {
   551 					res = DoCommand(tile, slope ^ 0xF, 1, DC_EXEC | DC_AUTO | DC_NO_WATER,
   551 					res = DoCommand(tile, slope ^ 0xF, 1, DC_EXEC | DC_AUTO | DC_NO_WATER,
   552 					                      CMD_TERRAFORM_LAND);
   552 					                      CMD_TERRAFORM_LAND);
   553 				}
   553 				}
   554 				if (CmdFailed(res) && CHANCE16I(1, 3, r)) {
   554 				if (CmdFailed(res) && CHANCE16I(1, 3, r)) {
   555 					// We can consider building on the slope, though.
   555 					/* We can consider building on the slope, though. */
   556 					goto no_slope;
   556 					goto no_slope;
   557 				}
   557 				}
   558 			}
   558 			}
   559 			return false;
   559 			return false;
   560 		}
   560 		}
   578 {
   578 {
   579 	Slope tileh;
   579 	Slope tileh;
   580 
   580 
   581 	TILE_ASSERT(tile);
   581 	TILE_ASSERT(tile);
   582 
   582 
   583 	// Don't terraform if land is plain or if there's a house there.
   583 	/* Don't terraform if land is plain or if there's a house there. */
   584 	if (IsTileType(tile, MP_HOUSE)) return;
   584 	if (IsTileType(tile, MP_HOUSE)) return;
   585 	tileh = GetTileSlope(tile, NULL);
   585 	tileh = GetTileSlope(tile, NULL);
   586 	if (tileh == SLOPE_FLAT) return;
   586 	if (tileh == SLOPE_FLAT) return;
   587 
   587 
   588 	// First try up, then down
   588 	/* First try up, then down */
   589 	if (!TerraformTownTile(tile, ~tileh & 0xF, 1)) {
   589 	if (!TerraformTownTile(tile, ~tileh & 0xF, 1)) {
   590 		TerraformTownTile(tile, tileh & 0xF, 0);
   590 		TerraformTownTile(tile, tileh & 0xF, 0);
   591 	}
   591 	}
   592 }
   592 }
   593 
   593 
   603 
   603 
   604 	if (mask == 0) {
   604 	if (mask == 0) {
   605 		int a;
   605 		int a;
   606 		int b;
   606 		int b;
   607 
   607 
   608 		// Tile has no road. First reset the status counter
   608 		/* Tile has no road. First reset the status counter
   609 		// to say that this is the last iteration.
   609 		 * to say that this is the last iteration. */
   610 		_grow_town_result = 0;
   610 		_grow_town_result = 0;
   611 
   611 
   612 		// Remove hills etc
   612 		/* Remove hills etc */
   613 		LevelTownLand(tile);
   613 		LevelTownLand(tile);
   614 
   614 
   615 		// Is a road allowed here?
   615 		/* Is a road allowed here? */
   616 		if (!IsRoadAllowedHere(tile, block)) return;
   616 		if (!IsRoadAllowedHere(tile, block)) return;
   617 
   617 
   618 		// Randomize new road block numbers
   618 		/* Randomize new road block numbers */
   619 		a = block;
   619 		a = block;
   620 		b = block ^ 2;
   620 		b = block ^ 2;
   621 		if (CHANCE16(1, 4)) {
   621 		if (CHANCE16(1, 4)) {
   622 			do {
   622 			do {
   623 				a = GB(Random(), 0, 2);
   623 				a = GB(Random(), 0, 2);
   624 			} while (a == b);
   624 			} while (a == b);
   625 		}
   625 		}
   626 
   626 
   627 		if (!IsRoadAllowedHere(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a])), a)) {
   627 		if (!IsRoadAllowedHere(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a])), a)) {
   628 			// A road is not allowed to continue the randomized road,
   628 			/* A road is not allowed to continue the randomized road,
   629 			//   return if the road we're trying to build is curved.
   629 			 *   return if the road we're trying to build is curved. */
   630 			if (a != (b ^ 2)) return;
   630 			if (a != (b ^ 2)) return;
   631 
   631 
   632 			// Return if neither side of the new road is a house
   632 			/* Return if neither side of the new road is a house */
   633 			if (!IsTileType(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a + 1])), MP_HOUSE) &&
   633 			if (!IsTileType(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a + 1])), MP_HOUSE) &&
   634 					!IsTileType(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a + 3])), MP_HOUSE))
   634 					!IsTileType(TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[a + 3])), MP_HOUSE))
   635 				return;
   635 				return;
   636 
   636 
   637 			// That means that the road is only allowed if there is a house
   637 			/* That means that the road is only allowed if there is a house
   638 			//  at any side of the new road.
   638 			 *  at any side of the new road. */
   639 		}
   639 		}
   640 		rcmd = (RoadBits)((1 << a) + (1 << b));
   640 		rcmd = (RoadBits)((1 << a) + (1 << b));
   641 
   641 
   642 	} else if (block < 5 && !HASBIT(mask,block^2)) {
   642 	} else if (block < 5 && !HASBIT(mask,block^2)) {
   643 		// Continue building on a partial road.
   643 		/* Continue building on a partial road.
   644 		// Always OK.
   644 		 * Always OK. */
   645 		_grow_town_result = 0;
   645 		_grow_town_result = 0;
   646 		rcmd = (RoadBits)(1 << (block ^ 2));
   646 		rcmd = (RoadBits)(1 << (block ^ 2));
   647 	} else {
   647 	} else {
   648 		int i;
   648 		int i;
   649 
   649 
   650 		// Reached a tunnel/bridge? Then continue at the other side of it.
   650 		/* Reached a tunnel/bridge? Then continue at the other side of it. */
   651 		if (IsTileType(tile, MP_TUNNELBRIDGE)) {
   651 		if (IsTileType(tile, MP_TUNNELBRIDGE)) {
   652 			if (IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_ROAD) {
   652 			if (IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_ROAD) {
   653 				*tile_ptr = GetOtherTunnelEnd(tile);
   653 				*tile_ptr = GetOtherTunnelEnd(tile);
   654 			} else if (IsBridge(tile) && GetBridgeTransportType(tile) == TRANSPORT_ROAD) {
   654 			} else if (IsBridge(tile) && GetBridgeTransportType(tile) == TRANSPORT_ROAD) {
   655 				*tile_ptr = GetOtherBridgeEnd(tile);
   655 				*tile_ptr = GetOtherBridgeEnd(tile);
   656 			}
   656 			}
   657 			return;
   657 			return;
   658 		}
   658 		}
   659 
   659 
   660 		// Possibly extend the road in a direction.
   660 		/* Possibly extend the road in a direction.
   661 		// Randomize a direction and if it has a road, bail out.
   661 		 * Randomize a direction and if it has a road, bail out. */
   662 		i = GB(Random(), 0, 2);
   662 		i = GB(Random(), 0, 2);
   663 		if (HASBIT(mask, i)) return;
   663 		if (HASBIT(mask, i)) return;
   664 
   664 
   665 		// This is the tile we will reach if we extend to this direction.
   665 		/* This is the tile we will reach if we extend to this direction. */
   666 		tmptile = TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[i]));
   666 		tmptile = TILE_ADD(tile, ToTileIndexDiff(_roadblock_tileadd[i]));
   667 
   667 
   668 		// Don't do it if it reaches to water.
   668 		/* Don't do it if it reaches to water. */
   669 		if (IsClearWaterTile(tmptile)) return;
   669 		if (IsClearWaterTile(tmptile)) return;
   670 
   670 
   671 		// Build a house at the edge. 60% chance or
   671 		/* Build a house at the edge. 60% chance or
   672 		//  always ok if no road allowed.
   672 		 *  always ok if no road allowed. */
   673 		if (!IsRoadAllowedHere(tmptile, i) || CHANCE16(6, 10)) {
   673 		if (!IsRoadAllowedHere(tmptile, i) || CHANCE16(6, 10)) {
   674 			// But not if there already is a house there.
   674 			/* But not if there already is a house there. */
   675 			if (!IsTileType(tmptile, MP_HOUSE)) {
   675 			if (!IsTileType(tmptile, MP_HOUSE)) {
   676 				// Level the land if possible
   676 				/* Level the land if possible */
   677 				LevelTownLand(tmptile);
   677 				LevelTownLand(tmptile);
   678 
   678 
   679 				// And build a house.
   679 				/* And build a house.
   680 				// Set result to -1 if we managed to build it.
   680 				 * Set result to -1 if we managed to build it. */
   681 				if (BuildTownHouse(t1, tmptile)) _grow_town_result = -1;
   681 				if (BuildTownHouse(t1, tmptile)) _grow_town_result = -1;
   682 			}
   682 			}
   683 			return;
   683 			return;
   684 		}
   684 		}
   685 
   685 
   686 		_grow_town_result = 0;
   686 		_grow_town_result = 0;
   687 		rcmd = (RoadBits)(1 << i);
   687 		rcmd = (RoadBits)(1 << i);
   688 	}
   688 	}
   689 
   689 
   690 	// Return if a water tile
   690 	/* Return if a water tile */
   691 	if (IsClearWaterTile(tile)) return;
   691 	if (IsClearWaterTile(tile)) return;
   692 
   692 
   693 	// Determine direction of slope,
   693 	/* Determine direction of slope,
   694 	//  and build a road if not a special slope.
   694 	 *  and build a road if not a special slope. */
   695 	switch (GetTileSlope(tile, NULL)) {
   695 	switch (GetTileSlope(tile, NULL)) {
   696 		case SLOPE_SW: i = DIAGDIR_NE; break;
   696 		case SLOPE_SW: i = DIAGDIR_NE; break;
   697 		case SLOPE_SE: i = DIAGDIR_NW; break;
   697 		case SLOPE_SE: i = DIAGDIR_NW; break;
   698 		case SLOPE_NW: i = DIAGDIR_SE; break;
   698 		case SLOPE_NW: i = DIAGDIR_SE; break;
   699 		case SLOPE_NE: i = DIAGDIR_SW; break;
   699 		case SLOPE_NE: i = DIAGDIR_SW; break;
   706 			return;
   706 			return;
   707 	}
   707 	}
   708 
   708 
   709 	tmptile = tile;
   709 	tmptile = tile;
   710 
   710 
   711 	// Now it contains the direction of the slope
   711 	/* Now it contains the direction of the slope */
   712 	j = -11; // max 11 tile long bridges
   712 	j = -11; // max 11 tile long bridges
   713 	do {
   713 	do {
   714 		if (++j == 0)
   714 		if (++j == 0)
   715 			goto build_road_and_exit;
   715 			goto build_road_and_exit;
   716 		tmptile = TILE_MASK(tmptile + TileOffsByDiagDir(i));
   716 		tmptile = TILE_MASK(tmptile + TileOffsByDiagDir(i));
   717 	} while (IsClearWaterTile(tmptile));
   717 	} while (IsClearWaterTile(tmptile));
   718 
   718 
   719 	// no water tiles in between?
   719 	/* no water tiles in between? */
   720 	if (j == -10)
   720 	if (j == -10)
   721 		goto build_road_and_exit;
   721 		goto build_road_and_exit;
   722 
   722 
   723 	// Quit if it selecting an appropiate bridge type fails a large number of times.
   723 	/* Quit if it selecting an appropiate bridge type fails a large number of times. */
   724 	j = 22;
   724 	j = 22;
   725 	{
   725 	{
   726 		int32 bridge_len = GetBridgeLength(tile, tmptile);
   726 		int32 bridge_len = GetBridgeLength(tile, tmptile);
   727 		do {
   727 		do {
   728 			byte bridge_type = RandomRange(MAX_BRIDGES - 1);
   728 			byte bridge_type = RandomRange(MAX_BRIDGES - 1);
   729 			if (CheckBridge_Stuff(bridge_type, bridge_len)) {
   729 			if (CheckBridge_Stuff(bridge_type, bridge_len)) {
   730 				if (!CmdFailed(DoCommand(tile, tmptile, 0x8000 + bridge_type, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE)))
   730 				if (!CmdFailed(DoCommand(tile, tmptile, 0x8000 + bridge_type, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE)))
   731 					_grow_town_result = -1;
   731 					_grow_town_result = -1;
   732 
   732 
   733 				// obviously, if building any bridge would fail, there is no need to try other bridge-types
   733 				/* obviously, if building any bridge would fail, there is no need to try other bridge-types */
   734 				return;
   734 				return;
   735 			}
   735 			}
   736 		} while (--j != 0);
   736 		} while (--j != 0);
   737 	}
   737 	}
   738 }
   738 }
   739 
   739 
   740 // Returns true if a house was built, or no if the build failed.
   740 /** Returns "growth" if a house was built, or no if the build failed.
       
   741  * @param t town to inquiry
       
   742  * @param tile to inquiry
       
   743  * @return something other than zero(0)if town expansion was possible
       
   744  */
   741 static int GrowTownAtRoad(Town *t, TileIndex tile)
   745 static int GrowTownAtRoad(Town *t, TileIndex tile)
   742 {
   746 {
   743 	int block = 5; // special case
   747 	int block = 5; // special case
   744 
   748 
   745 	TILE_ASSERT(tile);
   749 	TILE_ASSERT(tile);
   746 
   750 
   747 	// Number of times to search.
   751 	/* Number of times to search. */
   748 	_grow_town_result = 10 + t->num_houses * 4 / 9;
   752 	_grow_town_result = 10 + t->num_houses * 4 / 9;
   749 
   753 
   750 	do {
   754 	do {
   751 		// Get a bitmask of the road blocks on a tile
   755 		/* Get a bitmask of the road blocks on a tile */
   752 		RoadBits mask = GetTownRoadMask(tile);
   756 		RoadBits mask = GetTownRoadMask(tile);
   753 
   757 
   754 		// Try to grow the town from this point
   758 		/* Try to grow the town from this point */
   755 		GrowTownInTile(&tile,mask,block,t);
   759 		GrowTownInTile(&tile, mask, block, t);
   756 
   760 
   757 		// Exclude the source position from the bitmask
   761 		/* Exclude the source position from the bitmask
   758 		// and return if no more road blocks available
   762 		 * and return if no more road blocks available */
   759 		ClrBitT(mask, (block ^ 2));
   763 		ClrBitT(mask, (block ^ 2));
   760 		if (mask == 0)
   764 		if (mask == 0)
   761 			return _grow_town_result;
   765 			return _grow_town_result;
   762 
   766 
   763 		// Select a random bit from the blockmask, walk a step
   767 		/* Select a random bit from the blockmask, walk a step
   764 		// and continue the search from there.
   768 		 * and continue the search from there. */
   765 		do block = Random() & 3; while (!HASBIT(mask,block));
   769 		do block = Random() & 3; while (!HASBIT(mask,block));
   766 		tile += ToTileIndexDiff(_roadblock_tileadd[block]);
   770 		tile += ToTileIndexDiff(_roadblock_tileadd[block]);
   767 
   771 
   768 		if (IsTileType(tile, MP_STREET)) {
   772 		if (IsTileType(tile, MP_STREET)) {
   769 			/* Don't allow building over roads of other cities */
   773 			/* Don't allow building over roads of other cities */
   775 				SetTileOwner(tile, OWNER_TOWN);
   779 				SetTileOwner(tile, OWNER_TOWN);
   776 				SetTownIndex(tile, t->index);
   780 				SetTownIndex(tile, t->index);
   777 			}
   781 			}
   778 		}
   782 		}
   779 
   783 
   780 		// Max number of times is checked.
   784 		/* Max number of times is checked. */
   781 	} while (--_grow_town_result >= 0);
   785 	} while (--_grow_town_result >= 0);
   782 
   786 
   783 	return (_grow_town_result == -2);
   787 	return (_grow_town_result == -2);
   784 }
   788 }
   785 
   789 
   786 // Generate a random road block
   790 /** Generate a random road block
   787 // The probability of a straight road
   791  * The probability of a straight road
   788 // is somewhat higher than a curved.
   792  * is somewhat higher than a curved. */
   789 static RoadBits GenRandomRoadBits()
   793 static RoadBits GenRandomRoadBits()
   790 {
   794 {
   791 	uint32 r = Random();
   795 	uint32 r = Random();
   792 	uint a = GB(r, 0, 2);
   796 	uint a = GB(r, 0, 2);
   793 	uint b = GB(r, 8, 2);
   797 	uint b = GB(r, 8, 2);
   794 	if (a == b) b ^= 2;
   798 	if (a == b) b ^= 2;
   795 	return (RoadBits)((1 << a) + (1 << b));
   799 	return (RoadBits)((1 << a) + (1 << b));
   796 }
   800 }
   797 
   801 
   798 // Grow the town
   802 /** Grow the town
   799 // Returns true if a house was built, or no if the build failed.
   803  * @Return true if a house was built, or no if the build failed. */
   800 static bool GrowTown(Town *t)
   804 static bool GrowTown(Town *t)
   801 {
   805 {
   802 	TileIndex tile;
   806 	TileIndex tile;
   803 	const TileIndexDiffC *ptr;
   807 	const TileIndexDiffC *ptr;
   804 	PlayerID old_player;
   808 	PlayerID old_player;
   817 		{ 2,  2},
   821 		{ 2,  2},
   818 		{ 2, -2},
   822 		{ 2, -2},
   819 		{ 0,  0}
   823 		{ 0,  0}
   820 	};
   824 	};
   821 
   825 
   822 	// Current player is a town
   826 	/* Current player is a town */
   823 	old_player = _current_player;
   827 	old_player = _current_player;
   824 	_current_player = OWNER_TOWN;
   828 	_current_player = OWNER_TOWN;
   825 
   829 
   826 	// Find a road that we can base the construction on.
   830 	/* Find a road that we can base the construction on. */
   827 	tile = t->xy;
   831 	tile = t->xy;
   828 	for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
   832 	for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
   829 		if (GetAnyRoadTrackBits(tile) != 0) {
   833 		if (GetAnyRoadTrackBits(tile) != 0) {
   830 			int r = GrowTownAtRoad(t, tile);
   834 			int r = GrowTownAtRoad(t, tile);
   831 			_current_player = old_player;
   835 			_current_player = old_player;
   832 			return r != 0;
   836 			return r != 0;
   833 		}
   837 		}
   834 		tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
   838 		tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
   835 	}
   839 	}
   836 
   840 
   837 	// No road available, try to build a random road block by
   841 	/* No road available, try to build a random road block by
   838 	// clearing some land and then building a road there.
   842 	 * clearing some land and then building a road there. */
   839 	tile = t->xy;
   843 	tile = t->xy;
   840 	for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
   844 	for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
   841 		/* Only work with plain land that not already has a house */
   845 		/* Only work with plain land that not already has a house */
   842 		if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
   846 		if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
   843 			if (!CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR))) {
   847 			if (!CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR))) {
   883 
   887 
   884 	if (t->num_houses < 92) {
   888 	if (t->num_houses < 92) {
   885 		memcpy(t->radius, _town_radius_data[t->num_houses / 4], sizeof(t->radius));
   889 		memcpy(t->radius, _town_radius_data[t->num_houses / 4], sizeof(t->radius));
   886 	} else {
   890 	} else {
   887 		int mass = t->num_houses / 8;
   891 		int mass = t->num_houses / 8;
   888 		// At least very roughly extrapolate. Empirical numbers dancing between
   892 		/* At least very roughly extrapolate. Empirical numbers dancing between
   889 		// overwhelming by cottages and skyscrapers outskirts.
   893 		 * overwhelming by cottages and skyscrapers outskirts. */
   890 		t->radius[0] = mass * mass;
   894 		t->radius[0] = mass * mass;
   891 		// Actually we are proportional to sqrt() but that's right because
   895 		/* Actually we are proportional to sqrt() but that's right because
   892 		// we are covering an area.
   896 		 * we are covering an area. */
   893 		t->radius[1] = mass * 7;
   897 		t->radius[1] = mass * 7;
   894 		t->radius[2] = 0;
   898 		t->radius[2] = 0;
   895 		t->radius[3] = mass * 4;
   899 		t->radius[3] = mass * 4;
   896 		t->radius[4] = mass * 3;
   900 		t->radius[4] = mass * 3;
   897 		//debug("%d (->%d): %d %d %d %d\n", t->num_houses, mass, t->radius[0], t->radius[1], t->radius[3], t->radius[4]);
   901 		//debug("%d (->%d): %d %d %d %d\n", t->num_houses, mass, t->radius[0], t->radius[1], t->radius[3], t->radius[4]);
   919 		r = Random();
   923 		r = Random();
   920 
   924 
   921 		SetDParam(0, r);
   925 		SetDParam(0, r);
   922 		GetString(buf1, townnametype, lastof(buf1));
   926 		GetString(buf1, townnametype, lastof(buf1));
   923 
   927 
   924 		// Check size and width
   928 		/* Check size and width */
   925 		if (strlen(buf1) >= 31 || GetStringBoundingBox(buf1).width > 130) continue;
   929 		if (strlen(buf1) >= 31 || GetStringBoundingBox(buf1).width > 130) continue;
   926 
   930 
   927 		FOR_ALL_TOWNS(t2) {
   931 		FOR_ALL_TOWNS(t2) {
   928 			// We can't just compare the numbers since
   932 			/* We can't just compare the numbers since
   929 			// several numbers may map to a single name.
   933 			 * several numbers may map to a single name. */
   930 			SetDParam(0, t2->index);
   934 			SetDParam(0, t2->index);
   931 			GetString(buf2, STR_TOWN, lastof(buf2));
   935 			GetString(buf2, STR_TOWN, lastof(buf2));
   932 			if (strcmp(buf1, buf2) == 0) {
   936 			if (strcmp(buf1, buf2) == 0) {
   933 				if (tries-- < 0) return false;
   937 				if (tries-- < 0) return false;
   934 				goto restart;
   938 				goto restart;
   947 
   951 
   948 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, uint size_mode)
   952 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, uint size_mode)
   949 {
   953 {
   950 	int x, i;
   954 	int x, i;
   951 
   955 
   952 	// clear the town struct
   956 	/* clear the town struct */
   953 	i = t->index;
   957 	i = t->index;
   954 	memset(t, 0, sizeof(Town));
   958 	memset(t, 0, sizeof(Town));
   955 	t->index = i;
   959 	t->index = i;
   956 	_total_towns++;
   960 	_total_towns++;
   957 
   961 
  1055 
  1059 
  1056 /** Create a new town.
  1060 /** Create a new town.
  1057  * This obviously only works in the scenario editor. Function not removed
  1061  * This obviously only works in the scenario editor. Function not removed
  1058  * as it might be possible in the future to fund your own town :)
  1062  * as it might be possible in the future to fund your own town :)
  1059  * @param tile coordinates where town is built
  1063  * @param tile coordinates where town is built
       
  1064  * @param flags type of operation
  1060  * @param p1 size of the town (0 = random, 1 = small, 2 = medium, 3 = large)
  1065  * @param p1 size of the town (0 = random, 1 = small, 2 = medium, 3 = large)
  1061  * @param p2 unused
  1066  * @param p2 unused
  1062  */
  1067  */
  1063 int32 CmdBuildTown(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
  1068 int32 CmdBuildTown(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
  1064 {
  1069 {
  1068 	/* Only in the scenario editor */
  1073 	/* Only in the scenario editor */
  1069 	if (_game_mode != GM_EDITOR) return CMD_ERROR;
  1074 	if (_game_mode != GM_EDITOR) return CMD_ERROR;
  1070 
  1075 
  1071 	SET_EXPENSES_TYPE(EXPENSES_OTHER);
  1076 	SET_EXPENSES_TYPE(EXPENSES_OTHER);
  1072 
  1077 
  1073 	// Check if too close to the edge of map
  1078 	/* Check if too close to the edge of map */
  1074 	if (DistanceFromEdge(tile) < 12)
  1079 	if (DistanceFromEdge(tile) < 12)
  1075 		return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
  1080 		return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
  1076 
  1081 
  1077 	// Can only build on clear flat areas, possibly with trees.
  1082 	/* Can only build on clear flat areas, possibly with trees. */
  1078 	if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
  1083 	if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
  1079 		return_cmd_error(STR_0239_SITE_UNSUITABLE);
  1084 		return_cmd_error(STR_0239_SITE_UNSUITABLE);
  1080 	}
  1085 	}
  1081 
  1086 
  1082 	// Check distance to all other towns.
  1087 	/* Check distance to all other towns. */
  1083 	if (IsCloseToTown(tile, 20))
  1088 	if (IsCloseToTown(tile, 20))
  1084 		return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
  1089 		return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
  1085 
  1090 
  1086 	// Get a unique name for the town.
  1091 	/* Get a unique name for the town. */
  1087 	if (!CreateTownName(&townnameparts))
  1092 	if (!CreateTownName(&townnameparts))
  1088 		return_cmd_error(STR_023A_TOO_MANY_TOWNS);
  1093 		return_cmd_error(STR_023A_TOO_MANY_TOWNS);
  1089 
  1094 
  1090 	// Allocate town struct
  1095 	/* Allocate town struct */
  1091 	t = AllocateTown();
  1096 	t = AllocateTown();
  1092 	if (t == NULL) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
  1097 	if (t == NULL) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
  1093 
  1098 
  1094 	// Create the town
  1099 	/* Create the town */
  1095 	if (flags & DC_EXEC) {
  1100 	if (flags & DC_EXEC) {
  1096 		_generating_world = true;
  1101 		_generating_world = true;
  1097 		DoCreateTown(t, tile, townnameparts, p1);
  1102 		DoCreateTown(t, tile, townnameparts, p1);
  1098 		_generating_world = false;
  1103 		_generating_world = false;
  1099 	}
  1104 	}
  1105 	TileIndex tile;
  1110 	TileIndex tile;
  1106 	Town *t;
  1111 	Town *t;
  1107 	uint32 townnameparts;
  1112 	uint32 townnameparts;
  1108 
  1113 
  1109 	do {
  1114 	do {
  1110 		// Generate a tile index not too close from the edge
  1115 		/* Generate a tile index not too close from the edge */
  1111 		tile = RandomTile();
  1116 		tile = RandomTile();
  1112 		if (DistanceFromEdge(tile) < 20) continue;
  1117 		if (DistanceFromEdge(tile) < 20) continue;
  1113 
  1118 
  1114 		// Make sure the tile is plain
  1119 		/* Make sure the tile is plain */
  1115 		if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
  1120 		if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
  1116 
  1121 
  1117 		// Check not too close to a town
  1122 		/* Check not too close to a town */
  1118 		if (IsCloseToTown(tile, 20)) continue;
  1123 		if (IsCloseToTown(tile, 20)) continue;
  1119 
  1124 
  1120 		// Get a unique name for the town.
  1125 		/* Get a unique name for the town. */
  1121 		if (!CreateTownName(&townnameparts)) break;
  1126 		if (!CreateTownName(&townnameparts)) break;
  1122 
  1127 
  1123 		// Allocate a town struct
  1128 		/* Allocate a town struct */
  1124 		t = AllocateTown();
  1129 		t = AllocateTown();
  1125 		if (t == NULL) break;
  1130 		if (t == NULL) break;
  1126 
  1131 
  1127 		DoCreateTown(t, tile, townnameparts, size_mode);
  1132 		DoCreateTown(t, tile, townnameparts, size_mode);
  1128 		return t;
  1133 		return t;
  1139 
  1144 
  1140 	SetGeneratingWorldProgress(GWP_TOWN, n);
  1145 	SetGeneratingWorldProgress(GWP_TOWN, n);
  1141 
  1146 
  1142 	do {
  1147 	do {
  1143 		IncreaseGeneratingWorldProgress(GWP_TOWN);
  1148 		IncreaseGeneratingWorldProgress(GWP_TOWN);
  1144 		// try 20 times to create a random-sized town for the first loop.
  1149 		/* try 20 times to create a random-sized town for the first loop. */
  1145 		if (CreateRandomTown(20, 0) != NULL) num++;
  1150 		if (CreateRandomTown(20, 0) != NULL) num++;
  1146 	} while (--n);
  1151 	} while (--n);
  1147 
  1152 
  1148 	// give it a last try, but now more aggressive
  1153 	/* give it a last try, but now more aggressive */
  1149 	if (num == 0 && CreateRandomTown(10000, 0) == NULL) {
  1154 	if (num == 0 && CreateRandomTown(10000, 0) == NULL) {
  1150 		if (GetNumTowns() == 0) {
  1155 		if (GetNumTowns() == 0) {
  1151 			/* XXX - can we handle that more gracefully? */
  1156 			/* XXX - can we handle that more gracefully? */
  1152 			if (_game_mode != GM_EDITOR) error("Could not generate any town");
  1157 			if (_game_mode != GM_EDITOR) error("Could not generate any town");
  1153 
  1158 
  1217 	Slope slope;
  1222 	Slope slope;
  1218 	uint z;
  1223 	uint z;
  1219 	uint oneof = 0;
  1224 	uint oneof = 0;
  1220 	HouseSpec *hs;
  1225 	HouseSpec *hs;
  1221 
  1226 
  1222 	// Above snow?
  1227 	/* Above snow? */
  1223 	slope = GetTileSlope(tile, &z);
  1228 	slope = GetTileSlope(tile, &z);
  1224 
  1229 
  1225 	// Get the town zone type
  1230 	/* Get the town zone type */
  1226 	{
  1231 	{
  1227 		uint rad = t->GetRadiusGroup(tile);
  1232 		uint rad = t->GetRadiusGroup(tile);
  1228 
  1233 
  1229 		int land = _opt.landscape;
  1234 		int land = _opt.landscape;
  1230 		if (land == LT_ARCTIC && z >= _opt.snow_line) land = -1;
  1235 		if (land == LT_ARCTIC && z >= _opt.snow_line) land = -1;
  1231 
  1236 
  1232 		bitmask = (1 << rad) + (1 << (land + 12));
  1237 		bitmask = (1 << rad) + (1 << (land + 12));
  1233 	}
  1238 	}
  1234 
  1239 
  1235 	// bits 0-4 are used
  1240 	/* bits 0-4 are used
  1236 	// bits 11-15 are used
  1241 	 * bits 11-15 are used
  1237 	// bits 5-10 are not used.
  1242 	 * bits 5-10 are not used. */
  1238 	{
  1243 	{
  1239 		HouseID houses[HOUSE_MAX];
  1244 		HouseID houses[HOUSE_MAX];
  1240 		int num = 0;
  1245 		int num = 0;
  1241 		uint cumulative_probs[HOUSE_MAX];
  1246 		uint cumulative_probs[HOUSE_MAX];
  1242 		uint probability_max = 0;
  1247 		uint probability_max = 0;
  1243 
  1248 
  1244 		// Generate a list of all possible houses that can be built.
  1249 		/* Generate a list of all possible houses that can be built. */
  1245 		for (i = 0; i < HOUSE_MAX; i++) {
  1250 		for (i = 0; i < HOUSE_MAX; i++) {
  1246 			hs = GetHouseSpecs(i);
  1251 			hs = GetHouseSpecs(i);
  1247 			if ((~hs->building_availability & bitmask) == 0 && hs->enabled) {
  1252 			if ((~hs->building_availability & bitmask) == 0 && hs->enabled) {
  1248 				if (_have_newhouses) {
  1253 				if (_have_newhouses) {
  1249 					probability_max += hs->probability;
  1254 					probability_max += hs->probability;
  1276 				}
  1281 				}
  1277 			}
  1282 			}
  1278 
  1283 
  1279 			if (_cur_year < hs->min_date || _cur_year > hs->max_date) continue;
  1284 			if (_cur_year < hs->min_date || _cur_year > hs->max_date) continue;
  1280 
  1285 
  1281 			// Special houses that there can be only one of.
  1286 			/* Special houses that there can be only one of. */
  1282 			if (hs->building_flags & BUILDING_IS_CHURCH) {
  1287 			if (hs->building_flags & BUILDING_IS_CHURCH) {
  1283 				SETBIT(oneof, TOWN_HAS_CHURCH);
  1288 				SETBIT(oneof, TOWN_HAS_CHURCH);
  1284 			} else if (hs->building_flags & BUILDING_IS_STADIUM) {
  1289 			} else if (hs->building_flags & BUILDING_IS_STADIUM) {
  1285 				SETBIT(oneof, TOWN_HAS_STADIUM);
  1290 				SETBIT(oneof, TOWN_HAS_STADIUM);
  1286 			} else {
  1291 			} else {
  1287 				oneof = 0;
  1292 				oneof = 0;
  1288 			}
  1293 			}
  1289 
  1294 
  1290 			if (HASBITS(t->flags12 , oneof)) continue;
  1295 			if (HASBITS(t->flags12 , oneof)) continue;
  1291 
  1296 
  1292 			// Make sure there is no slope?
  1297 			/* Make sure there is no slope? */
  1293 			if (hs->building_flags & TILE_NOT_SLOPED && slope != SLOPE_FLAT) continue;
  1298 			if (hs->building_flags & TILE_NOT_SLOPED && slope != SLOPE_FLAT) continue;
  1294 
  1299 
  1295 			if (hs->building_flags & TILE_SIZE_2x2) {
  1300 			if (hs->building_flags & TILE_SIZE_2x2) {
  1296 				if (CheckFree2x2Area(tile) ||
  1301 				if (CheckFree2x2Area(tile) ||
  1297 						CheckFree2x2Area(tile += TileDiffXY(-1,  0)) ||
  1302 						CheckFree2x2Area(tile += TileDiffXY(-1,  0)) ||
  1321 	}
  1326 	}
  1322 
  1327 
  1323 	t->num_houses++;
  1328 	t->num_houses++;
  1324 	IncreaseBuildingCount(t, house);
  1329 	IncreaseBuildingCount(t, house);
  1325 
  1330 
  1326 	// Special houses that there can be only one of.
  1331 	/* Special houses that there can be only one of. */
  1327 	t->flags12 |= oneof;
  1332 	t->flags12 |= oneof;
  1328 
  1333 
  1329 	{
  1334 	{
  1330 		byte construction_counter = 0, construction_stage = 0;
  1335 		byte construction_counter = 0, construction_stage = 0;
  1331 
  1336 
  1373 	uint eflags;
  1378 	uint eflags;
  1374 	HouseSpec *hs;
  1379 	HouseSpec *hs;
  1375 
  1380 
  1376 	assert(IsTileType(tile, MP_HOUSE));
  1381 	assert(IsTileType(tile, MP_HOUSE));
  1377 
  1382 
  1378 	// need to align the tile to point to the upper left corner of the house
  1383 	/* need to align the tile to point to the upper left corner of the house */
  1379 	if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
  1384 	if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
  1380 		if (GetHouseSpecs(house-1)->building_flags & TILE_SIZE_2x1) {
  1385 		if (GetHouseSpecs(house-1)->building_flags & TILE_SIZE_2x1) {
  1381 			house--;
  1386 			house--;
  1382 			tile += TileDiffXY(-1, 0);
  1387 			tile += TileDiffXY(-1, 0);
  1383 		} else if (GetHouseSpecs(house-1)->building_flags & BUILDING_2_TILES_Y) {
  1388 		} else if (GetHouseSpecs(house-1)->building_flags & BUILDING_2_TILES_Y) {
  1392 		}
  1397 		}
  1393 	}
  1398 	}
  1394 
  1399 
  1395 	hs = GetHouseSpecs(house);
  1400 	hs = GetHouseSpecs(house);
  1396 
  1401 
  1397 	// Remove population from the town if the house is finished.
  1402 	/* Remove population from the town if the house is finished. */
  1398 	if (IsHouseCompleted(tile)) {
  1403 	if (IsHouseCompleted(tile)) {
  1399 		ChangePopulation(t, -hs->population);
  1404 		ChangePopulation(t, -hs->population);
  1400 	}
  1405 	}
  1401 
  1406 
  1402 	t->num_houses--;
  1407 	t->num_houses--;
  1403 	DecreaseBuildingCount(t, house);
  1408 	DecreaseBuildingCount(t, house);
  1404 
  1409 
  1405 	// Clear flags for houses that only may exist once/town.
  1410 	/* Clear flags for houses that only may exist once/town. */
  1406 	if (hs->building_flags & BUILDING_IS_CHURCH) {
  1411 	if (hs->building_flags & BUILDING_IS_CHURCH) {
  1407 		CLRBIT(t->flags12, TOWN_HAS_CHURCH);
  1412 		CLRBIT(t->flags12, TOWN_HAS_CHURCH);
  1408 	} else if (hs->building_flags & BUILDING_IS_STADIUM) {
  1413 	} else if (hs->building_flags & BUILDING_IS_STADIUM) {
  1409 		CLRBIT(t->flags12, TOWN_HAS_STADIUM);
  1414 		CLRBIT(t->flags12, TOWN_HAS_STADIUM);
  1410 	}
  1415 	}
  1411 
  1416 
  1412 	// Do the actual clearing of tiles
  1417 	/* Do the actual clearing of tiles */
  1413 	eflags = hs->building_flags;
  1418 	eflags = hs->building_flags;
  1414 	DoClearTownHouseHelper(tile);
  1419 	DoClearTownHouseHelper(tile);
  1415 	if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0));
  1420 	if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0));
  1416 	if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1));
  1421 	if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1));
  1417 	if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1));
  1422 	if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1));
  1418 }
  1423 }
  1419 
  1424 
  1420 /** Rename a town (server-only).
  1425 /** Rename a town (server-only).
  1421  * @param tile unused
  1426  * @param tile unused
       
  1427  * @param flags type of operation
  1422  * @param p1 town ID to rename
  1428  * @param p1 town ID to rename
  1423  * @param p2 unused
  1429  * @param p2 unused
  1424  */
  1430  */
  1425 int32 CmdRenameTown(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
  1431 int32 CmdRenameTown(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
  1426 {
  1432 {
  1446 		DeleteName(str);
  1452 		DeleteName(str);
  1447 	}
  1453 	}
  1448 	return 0;
  1454 	return 0;
  1449 }
  1455 }
  1450 
  1456 
  1451 // Called from GUI
  1457 /** Called from GUI */
  1452 void ExpandTown(Town *t)
  1458 void ExpandTown(Town *t)
  1453 {
  1459 {
  1454 	int amount, n;
  1460 	int amount, n;
  1455 
  1461 
  1456 	_generating_world = true;
  1462 	_generating_world = true;
  1549 static void TownActionBuildStatue(Town* t)
  1555 static void TownActionBuildStatue(Town* t)
  1550 {
  1556 {
  1551 	TileIndex tile = t->xy;
  1557 	TileIndex tile = t->xy;
  1552 
  1558 
  1553 	if (CircularTileSearch(tile, 9, SearchTileForStatue, t->index))
  1559 	if (CircularTileSearch(tile, 9, SearchTileForStatue, t->index))
  1554 		SETBIT(t->statues, _current_player); ///< Once found and built, "inform" the Town
  1560 		SETBIT(t->statues, _current_player); // Once found and built, "inform" the Town
  1555 }
  1561 }
  1556 
  1562 
  1557 static void TownActionFundBuildings(Town* t)
  1563 static void TownActionFundBuildings(Town* t)
  1558 {
  1564 {
  1559 	// Build next tick
  1565 	/* Build next tick */
  1560 	t->grow_counter = 1;
  1566 	t->grow_counter = 1;
  1561 	// If we were not already growing
  1567 	/* If we were not already growing */
  1562 	SETBIT(t->flags12, TOWN_IS_FUNDED);
  1568 	SETBIT(t->flags12, TOWN_IS_FUNDED);
  1563 	// And grow for 3 months
  1569 	/* And grow for 3 months */
  1564 	t->fund_buildings_months = 3;
  1570 	t->fund_buildings_months = 3;
  1565 }
  1571 }
  1566 
  1572 
  1567 static void TownActionBuyRights(Town* t)
  1573 static void TownActionBuyRights(Town* t)
  1568 {
  1574 {
  1575 static void TownActionBribe(Town* t)
  1581 static void TownActionBribe(Town* t)
  1576 {
  1582 {
  1577 	if (!RandomRange(15)) {
  1583 	if (!RandomRange(15)) {
  1578 		Station *st;
  1584 		Station *st;
  1579 
  1585 
  1580 		// set as unwanted for 6 months
  1586 		/* set as unwanted for 6 months */
  1581 		t->unwanted[_current_player] = 6;
  1587 		t->unwanted[_current_player] = 6;
  1582 
  1588 
  1583 		// set all close by station ratings to 0
  1589 		/* set all close by station ratings to 0 */
  1584 		FOR_ALL_STATIONS(st) {
  1590 		FOR_ALL_STATIONS(st) {
  1585 			if (st->town == t && st->owner == _current_player) {
  1591 			if (st->town == t && st->owner == _current_player) {
  1586 				for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
  1592 				for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
  1587 			}
  1593 			}
  1588 		}
  1594 		}
  1589 
  1595 
  1590 		// only show errormessage to the executing player. All errors are handled command.c
  1596 		/* only show errormessage to the executing player. All errors are handled command.c
  1591 		// but this is special, because it can only 'fail' on a DC_EXEC
  1597 		 * but this is special, because it can only 'fail' on a DC_EXEC */
  1592 		if (IsLocalPlayer()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
  1598 		if (IsLocalPlayer()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
  1593 
  1599 
  1594 		/* decrease by a lot!
  1600 		/* decrease by a lot!
  1595 		 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
  1601 		 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
  1596 		 * be independent of any cheat settings
  1602 		 * be independent of any cheat settings
  1619 
  1625 
  1620 /** Do a town action.
  1626 /** Do a town action.
  1621  * This performs an action such as advertising, building a statue, funding buildings,
  1627  * This performs an action such as advertising, building a statue, funding buildings,
  1622  * but also bribing the town-council
  1628  * but also bribing the town-council
  1623  * @param tile unused
  1629  * @param tile unused
       
  1630  * @param flags type of operation
  1624  * @param p1 town to do the action at
  1631  * @param p1 town to do the action at
  1625  * @param p2 action to perform, @see _town_action_proc for the list of available actions
  1632  * @param p2 action to perform, @see _town_action_proc for the list of available actions
  1626  */
  1633  */
  1627 int32 CmdDoTownAction(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
  1634 int32 CmdDoTownAction(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
  1628 {
  1635 {
  1649 
  1656 
  1650 static void UpdateTownGrowRate(Town *t)
  1657 static void UpdateTownGrowRate(Town *t)
  1651 {
  1658 {
  1652 	int n;
  1659 	int n;
  1653 	Station *st;
  1660 	Station *st;
  1654 	byte m;
  1661 	uint16 m;
  1655 	Player *p;
  1662 	Player *p;
  1656 
  1663 
  1657 	// Reset player ratings if they're low
  1664 	/* Reset player ratings if they're low */
  1658 	FOR_ALL_PLAYERS(p) {
  1665 	FOR_ALL_PLAYERS(p) {
  1659 		if (p->is_active && t->ratings[p->index] <= 200) {
  1666 		if (p->is_active && t->ratings[p->index] <= 200) {
  1660 			t->ratings[p->index] += 5;
  1667 			t->ratings[p->index] += 5;
  1661 		}
  1668 		}
  1662 	}
  1669 	}
  1674 			}
  1681 			}
  1675 		}
  1682 		}
  1676 	}
  1683 	}
  1677 
  1684 
  1678 	CLRBIT(t->flags12, TOWN_IS_FUNDED);
  1685 	CLRBIT(t->flags12, TOWN_IS_FUNDED);
       
  1686 	if (_patches.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
       
  1687 
       
  1688 	/** Towns are processed every TOWN_GROWTH_FREQUENCY ticks, and this is the
       
  1689 	 * number of times towns are processed before a new building is built. */
       
  1690 	static const uint16 _grow_count_values[2][6] = {
       
  1691 		{ 120, 120, 120, 100,  80,  60 }, ///< Fund new buildings has been activated
       
  1692 		{ 320, 420, 300, 220, 160, 100 }  ///< Normal values
       
  1693 	};
  1679 
  1694 
  1680 	if (t->fund_buildings_months != 0) {
  1695 	if (t->fund_buildings_months != 0) {
  1681 		static const byte _grow_count_values[6] = {
  1696 		m = _grow_count_values[0][min(n, 5)];
  1682 			60, 60, 60, 50, 40, 30
       
  1683 		};
       
  1684 		m = _grow_count_values[min(n, 5)];
       
  1685 		t->fund_buildings_months--;
  1697 		t->fund_buildings_months--;
  1686 	} else if (n == 0) {
       
  1687 		m = 160;
       
  1688 		if (!CHANCE16(1, 12))
       
  1689 			return;
       
  1690 	} else {
  1698 	} else {
  1691 		static const byte _grow_count_values[5] = {
  1699 		m = _grow_count_values[1][min(n, 5)];
  1692 			210, 150, 110, 80, 50
  1700 		if (n == 0 && !CHANCE16(1, 12)) return;
  1693 		};
       
  1694 		m = _grow_count_values[min(n, 5) - 1];
       
  1695 	}
  1701 	}
  1696 
  1702 
  1697 	if (_opt.landscape == LT_ARCTIC) {
  1703 	if (_opt.landscape == LT_ARCTIC) {
  1698 		if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
  1704 		if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
  1699 			return;
  1705 			return;
  1700 	} else if (_opt.landscape == LT_TROPIC) {
  1706 	} else if (_opt.landscape == LT_TROPIC) {
  1701 		if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food==0 || t->act_water==0) && t->population > 60)
  1707 		if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food==0 || t->act_water==0) && t->population > 60)
  1702 			return;
  1708 			return;
  1703 	}
  1709 	}
  1704 
  1710 
       
  1711 	/* Use the normal growth rate values if new buildings have been funded in
       
  1712 	 * this town and the growth rate is set to none. */
       
  1713 	uint growth_multiplier = _patches.town_growth_rate != 0 ? _patches.town_growth_rate - 1 : 1;
       
  1714 
       
  1715 	m >>= growth_multiplier;
       
  1716 	if (_patches.larger_towns != 0 && (t->index % _patches.larger_towns) == 0) m /= 2;
       
  1717 
  1705 	t->growth_rate = m / (t->num_houses / 50 + 1);
  1718 	t->growth_rate = m / (t->num_houses / 50 + 1);
  1706 	if (m <= t->grow_counter)
  1719 	if (m <= t->grow_counter)
  1707 		t->grow_counter = m;
  1720 		t->grow_counter = m;
  1708 
  1721 
  1709 	SETBIT(t->flags12, TOWN_IS_FUNDED);
  1722 	SETBIT(t->flags12, TOWN_IS_FUNDED);
  1710 }
  1723 }
  1711 
  1724 
  1712 static void UpdateTownAmounts(Town *t)
  1725 static void UpdateTownAmounts(Town *t)
  1713 {
  1726 {
  1714 	// Using +1 here to prevent overflow and division by zero
  1727 	/* Using +1 here to prevent overflow and division by zero */
  1715 	t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
  1728 	t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
  1716 
  1729 
  1717 	t->max_pass = t->new_max_pass; t->new_max_pass = 0;
  1730 	t->max_pass = t->new_max_pass; t->new_max_pass = 0;
  1718 	t->act_pass = t->new_act_pass; t->new_act_pass = 0;
  1731 	t->act_pass = t->new_act_pass; t->new_act_pass = 0;
  1719 	t->act_food = t->new_act_food; t->new_act_food = 0;
  1732 	t->act_food = t->new_act_food; t->new_act_food = 0;
  1720 	t->act_water = t->new_act_water; t->new_act_water = 0;
  1733 	t->act_water = t->new_act_water; t->new_act_water = 0;
  1721 
  1734 
  1722 	// Using +1 here to prevent overflow and division by zero
  1735 	/* Using +1 here to prevent overflow and division by zero */
  1723 	t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
  1736 	t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
  1724 	t->max_mail = t->new_max_mail; t->new_max_mail = 0;
  1737 	t->max_mail = t->new_max_mail; t->new_max_mail = 0;
  1725 	t->act_mail = t->new_act_mail; t->new_act_mail = 0;
  1738 	t->act_mail = t->new_act_mail; t->new_act_mail = 0;
  1726 
  1739 
  1727 	InvalidateWindow(WC_TOWN_VIEW, t->index);
  1740 	InvalidateWindow(WC_TOWN_VIEW, t->index);
  1787 
  1800 
  1788 void ChangeTownRating(Town *t, int add, int max)
  1801 void ChangeTownRating(Town *t, int add, int max)
  1789 {
  1802 {
  1790 	int rating;
  1803 	int rating;
  1791 
  1804 
  1792 	// if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff
  1805 	/* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
  1793 	if (t == NULL ||
  1806 	if (t == NULL ||
  1794 			!IsValidPlayer(_current_player) ||
  1807 			!IsValidPlayer(_current_player) ||
  1795 			(_cheats.magic_bulldozer.value && add < 0)) {
  1808 			(_cheats.magic_bulldozer.value && add < 0)) {
  1796 		return;
  1809 		return;
  1797 	}
  1810 	}
  1814 	t->ratings[_current_player] = rating;
  1827 	t->ratings[_current_player] = rating;
  1815 }
  1828 }
  1816 
  1829 
  1817 /* penalty for removing town-owned stuff */
  1830 /* penalty for removing town-owned stuff */
  1818 static const int _default_rating_settings [3][3] = {
  1831 static const int _default_rating_settings [3][3] = {
  1819 	// ROAD_REMOVE, TUNNELBRIDGE_REMOVE, INDUSTRY_REMOVE
  1832 	/* ROAD_REMOVE, TUNNELBRIDGE_REMOVE, INDUSTRY_REMOVE */
  1820 	{  0, 128, 384}, // Permissive
  1833 	{  0, 128, 384}, ///< Permissive
  1821 	{ 48, 192, 480}, // Neutral
  1834 	{ 48, 192, 480}, ///< Neutral
  1822 	{ 96, 384, 768}, // Hostile
  1835 	{ 96, 384, 768}, ///< Hostile
  1823 };
  1836 };
  1824 
  1837 
  1825 bool CheckforTownRating(uint32 flags, Town *t, byte type)
  1838 bool CheckforTownRating(uint32 flags, Town *t, byte type)
  1826 {
  1839 {
  1827 	int modemod;
  1840 	int modemod;
  1828 
  1841 
  1829 	// if magic_bulldozer cheat is active, town doesn't restrict your destructive actions
  1842 	/* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
  1830 	if (t == NULL || !IsValidPlayer(_current_player) || _cheats.magic_bulldozer.value)
  1843 	if (t == NULL || !IsValidPlayer(_current_player) || _cheats.magic_bulldozer.value)
  1831 		return true;
  1844 		return true;
  1832 
  1845 
  1833 	/* check if you're allowed to remove the street/bridge/tunnel/industry
  1846 	/* check if you're allowed to remove the street/bridge/tunnel/industry
  1834 	 * owned by a town no removal if rating is lower than ... depends now on
  1847 	 * owned by a town no removal if rating is lower than ... depends now on
  1910 	    SLE_VAR(Town, townnameparts,         SLE_UINT32),
  1923 	    SLE_VAR(Town, townnameparts,         SLE_UINT32),
  1911 
  1924 
  1912 	    SLE_VAR(Town, flags12,               SLE_UINT8),
  1925 	    SLE_VAR(Town, flags12,               SLE_UINT8),
  1913 	    SLE_VAR(Town, statues,               SLE_UINT8),
  1926 	    SLE_VAR(Town, statues,               SLE_UINT8),
  1914 
  1927 
  1915 	// sort_index_obsolete was stored here in savegame format 0 - 1
  1928 	/* sort_index_obsolete was stored here in savegame format 0 - 1 */
  1916 	SLE_CONDNULL(1, 0, 1),
  1929 	SLE_CONDNULL(1, 0, 1),
  1917 
  1930 
  1918 	    SLE_VAR(Town, have_ratings,          SLE_UINT8),
  1931 	    SLE_VAR(Town, have_ratings,          SLE_UINT8),
  1919 	    SLE_ARR(Town, ratings,               SLE_INT16, 8),
  1932 	    SLE_ARR(Town, ratings,               SLE_INT16, 8),
  1920 	// failed bribe attempts are stored since savegame format 4
  1933 	/* failed bribe attempts are stored since savegame format 4 */
  1921 	SLE_CONDARR(Town, unwanted,              SLE_INT8, 8, 4,SL_MAX_VERSION),
  1934 	SLE_CONDARR(Town, unwanted,              SLE_INT8, 8, 4,SL_MAX_VERSION),
  1922 
  1935 
  1923 	SLE_CONDVAR(Town, max_pass,              SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
  1936 	SLE_CONDVAR(Town, max_pass,              SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
  1924 	SLE_CONDVAR(Town, max_mail,              SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
  1937 	SLE_CONDVAR(Town, max_mail,              SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
  1925 	SLE_CONDVAR(Town, new_max_pass,          SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
  1938 	SLE_CONDVAR(Town, new_max_pass,          SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
  1945 	    SLE_VAR(Town, act_food,              SLE_UINT16),
  1958 	    SLE_VAR(Town, act_food,              SLE_UINT16),
  1946 	    SLE_VAR(Town, act_water,             SLE_UINT16),
  1959 	    SLE_VAR(Town, act_water,             SLE_UINT16),
  1947 	    SLE_VAR(Town, new_act_food,          SLE_UINT16),
  1960 	    SLE_VAR(Town, new_act_food,          SLE_UINT16),
  1948 	    SLE_VAR(Town, new_act_water,         SLE_UINT16),
  1961 	    SLE_VAR(Town, new_act_water,         SLE_UINT16),
  1949 
  1962 
  1950 	    SLE_VAR(Town, time_until_rebuild,    SLE_UINT8),
  1963 	SLE_CONDVAR(Town, time_until_rebuild,    SLE_UINT8,                  0, 53),
  1951 	    SLE_VAR(Town, grow_counter,          SLE_UINT8),
  1964 	SLE_CONDVAR(Town, grow_counter,          SLE_UINT8,                  0, 53),
  1952 	    SLE_VAR(Town, growth_rate,           SLE_UINT8),
  1965 	SLE_CONDVAR(Town, growth_rate,           SLE_UINT8,                  0, 53),
       
  1966 
       
  1967 	SLE_CONDVAR(Town, time_until_rebuild,    SLE_UINT16,                 54, SL_MAX_VERSION),
       
  1968 	SLE_CONDVAR(Town, grow_counter,          SLE_UINT16,                 54, SL_MAX_VERSION),
       
  1969 	SLE_CONDVAR(Town, growth_rate,           SLE_INT16,                  54, SL_MAX_VERSION),
       
  1970 
  1953 	    SLE_VAR(Town, fund_buildings_months, SLE_UINT8),
  1971 	    SLE_VAR(Town, fund_buildings_months, SLE_UINT8),
  1954 	    SLE_VAR(Town, road_build_months,     SLE_UINT8),
  1972 	    SLE_VAR(Town, road_build_months,     SLE_UINT8),
  1955 
  1973 
  1956 	    SLE_VAR(Town, exclusivity,           SLE_UINT8),
  1974 	    SLE_VAR(Town, exclusivity,           SLE_UINT8),
  1957 	    SLE_VAR(Town, exclusive_counter,     SLE_UINT8),
  1975 	    SLE_VAR(Town, exclusive_counter,     SLE_UINT8),
  1958 	// reserve extra space in savegame here. (currently 30 bytes)
  1976 	/* reserve extra space in savegame here. (currently 30 bytes) */
  1959 	SLE_CONDNULL(30, 2, SL_MAX_VERSION),
  1977 	SLE_CONDNULL(30, 2, SL_MAX_VERSION),
  1960 
  1978 
  1961 	SLE_END()
  1979 	SLE_END()
  1962 };
  1980 };
  1963 
  1981