Changeset - r7922:d7c3cc15726d
[Not reviewed]
src/aircraft_cmd.cpp
Show inline comments
 
@@ -824,30 +824,30 @@ static void SetAircraftPosition(Vehicle 
 
	v->y_pos = y;
 
	v->z_pos = z;
 

	
 
	v->cur_image = v->GetImage(v->direction);
 
	if (v->subtype == AIR_HELICOPTER) v->Next()->Next()->cur_image = GetRotorImage(v);
 

	
 
	BeginVehicleMove(v);
 
	VehiclePositionChanged(v);
 
	EndVehicleMove(v);
 

	
 
	Vehicle *u = v->Next();
 

	
 
	int safe_x = clamp(x, 0, MapMaxX() * TILE_SIZE);
 
	int safe_y = clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
 
	int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
 
	int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
 
	u->x_pos = x;
 
	u->y_pos = y - ((v->z_pos-GetSlopeZ(safe_x, safe_y)) >> 3);;
 

	
 
	safe_y = clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
 
	safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
 
	u->z_pos = GetSlopeZ(safe_x, safe_y);
 
	u->cur_image = v->cur_image;
 

	
 
	BeginVehicleMove(u);
 
	VehiclePositionChanged(u);
 
	EndVehicleMove(u);
 

	
 
	u = u->Next();
 
	if (u != NULL) {
 
		u->x_pos = x;
 
		u->y_pos = y;
 
		u->z_pos = z + 5;
src/depot.h
Show inline comments
 
@@ -42,25 +42,25 @@ void ShowDepotWindow(TileIndex tile, Veh
 
#define MIN_SERVINT_DAYS    30
 
#define MAX_SERVINT_DAYS   800
 

	
 
/**
 
 * Get the service interval domain.
 
 * Get the new proposed service interval for the vehicle is indeed, clamped
 
 * within the given bounds. @see MIN_SERVINT_PERCENT ,etc.
 
 * @param index proposed service interval
 
 * @return service interval
 
 */
 
static inline Date GetServiceIntervalClamped(uint index)
 
{
 
	return (_patches.servint_ispercent) ? clamp(index, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : clamp(index, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
 
	return (_patches.servint_ispercent) ? Clamp(index, MIN_SERVINT_PERCENT, MAX_SERVINT_PERCENT) : Clamp(index, MIN_SERVINT_DAYS, MAX_SERVINT_DAYS);
 
}
 

	
 
/**
 
 * Check if a tile is a depot of the given type.
 
 */
 
static inline bool IsTileDepotType(TileIndex tile, TransportType type)
 
{
 
	switch (type) {
 
		case TRANSPORT_RAIL:
 
			return IsTileType(tile, MP_RAILWAY) && GetRailTileType(tile)  == RAIL_TILE_DEPOT;
 

	
 
		case TRANSPORT_ROAD:
src/disaster_cmd.cpp
Show inline comments
 
@@ -150,31 +150,31 @@ static void SetDisasterVehiclePos(Vehicl
 

	
 
	BeginVehicleMove(v);
 
	v->x_pos = x;
 
	v->y_pos = y;
 
	v->z_pos = z;
 
	v->tile = TileVirtXY(x, y);
 

	
 
	DisasterVehicleUpdateImage(v);
 
	VehiclePositionChanged(v);
 
	EndVehicleMove(v);
 

	
 
	if ((u = v->Next()) != NULL) {
 
		int safe_x = clamp(x, 0, MapMaxX() * TILE_SIZE);
 
		int safe_y = clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
 
		int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
 
		int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
 
		BeginVehicleMove(u);
 

	
 
		u->x_pos = x;
 
		u->y_pos = y - 1 - (max(z - GetSlopeZ(safe_x, safe_y), 0U) >> 3);
 
		safe_y = clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
 
		safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
 
		u->z_pos = GetSlopeZ(safe_x, safe_y);
 
		u->direction = v->direction;
 

	
 
		DisasterVehicleUpdateImage(u);
 
		VehiclePositionChanged(u);
 
		EndVehicleMove(u);
 

	
 
		if ((u = u->Next()) != NULL) {
 
			BeginVehicleMove(u);
 
			u->x_pos = x;
 
			u->y_pos = y;
 
			u->z_pos = z + 5;
src/economy.cpp
Show inline comments
 
@@ -203,25 +203,25 @@ int UpdateCompanyRatingAndValue(Player *
 
		_score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - p->current_loan);
 
	}
 

	
 
	/* Now we calculate the score for each item.. */
 
	{
 
		int total_score = 0;
 
		int s;
 
		score = 0;
 
		for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
 
			/* Skip the total */
 
			if (i == SCORE_TOTAL) continue;
 
			/*  Check the score */
 
			s = clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
 
			s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
 
			score += s;
 
			total_score += _score_info[i].score;
 
		}
 

	
 
		_score_part[owner][SCORE_TOTAL] = score;
 

	
 
		/*  We always want the score scaled to SCORE_MAX (1000) */
 
		if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
 
	}
 

	
 
	if (update) {
 
		p->old_economy[0].performance_history = score;
src/genworld_gui.cpp
Show inline comments
 
@@ -378,40 +378,40 @@ static void GenerateLandscapeWndProc(Win
 
					LandscapeGenerationCallback);
 

	
 
			} else {
 
				StartGeneratingLandscape(mode);
 
			}
 
			break;
 
		case GLAND_START_DATE_DOWN: case GLAND_START_DATE_UP: // Year buttons
 
			/* Don't allow too fast scrolling */
 
			if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
				HandleButtonClick(w, e->we.click.widget);
 
				SetWindowDirty(w);
 

	
 
				_patches_newgame.starting_year = clamp(_patches_newgame.starting_year + e->we.click.widget - GLAND_START_DATE_TEXT, MIN_YEAR, MAX_YEAR);
 
				_patches_newgame.starting_year = Clamp(_patches_newgame.starting_year + e->we.click.widget - GLAND_START_DATE_TEXT, MIN_YEAR, MAX_YEAR);
 
			}
 
			_left_button_clicked = false;
 
			break;
 
		case GLAND_START_DATE_TEXT: // Year text
 
			WP(w, generate_d).widget_id = GLAND_START_DATE_TEXT;
 
			SetDParam(0, _patches_newgame.starting_year);
 
			ShowQueryString(STR_CONFIG_PATCHES_INT32, STR_START_DATE_QUERY_CAPT, 8, 100, w, CS_NUMERAL);
 
			break;
 
		case GLAND_SNOW_LEVEL_DOWN: case GLAND_SNOW_LEVEL_UP: // Snow line buttons
 
			/* Don't allow too fast scrolling */
 
			if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
				HandleButtonClick(w, e->we.click.widget);
 
				SetWindowDirty(w);
 

	
 
				_patches_newgame.snow_line_height = clamp(_patches_newgame.snow_line_height + e->we.click.widget - GLAND_SNOW_LEVEL_TEXT, 2, MAX_SNOWLINE_HEIGHT);
 
				_patches_newgame.snow_line_height = Clamp(_patches_newgame.snow_line_height + e->we.click.widget - GLAND_SNOW_LEVEL_TEXT, 2, MAX_SNOWLINE_HEIGHT);
 
			}
 
			_left_button_clicked = false;
 
			break;
 
		case GLAND_SNOW_LEVEL_TEXT: // Snow line text
 
			WP(w, generate_d).widget_id = GLAND_SNOW_LEVEL_TEXT;
 
			SetDParam(0, _patches_newgame.snow_line_height);
 
			ShowQueryString(STR_CONFIG_PATCHES_INT32, STR_SNOW_LINE_QUERY_CAPT, 3, 100, w, CS_NUMERAL);
 
			break;
 
		case GLAND_TREE_TEXT: case GLAND_TREE_PULLDOWN: // Tree placer
 
			ShowDropDownMenu(w, tree_placer, _patches_newgame.tree_placer, GLAND_TREE_PULLDOWN, 0, 0);
 
			break;
 
		case GLAND_LANDSCAPE_TEXT: case GLAND_LANDSCAPE_PULLDOWN: // Landscape generator OR Heightmap rotation
 
@@ -485,29 +485,29 @@ static void GenerateLandscapeWndProc(Win
 
				break;
 
		}
 
		SetWindowDirty(w);
 
		break;
 

	
 
	case WE_ON_EDIT_TEXT: {
 
		if (e->we.edittext.str != NULL) {
 
			int32 value = atoi(e->we.edittext.str);
 

	
 
			switch (WP(w, generate_d).widget_id) {
 
			case GLAND_START_DATE_TEXT:
 
				InvalidateWidget(w, GLAND_START_DATE_TEXT);
 
				_patches_newgame.starting_year = clamp(value, MIN_YEAR, MAX_YEAR);
 
				_patches_newgame.starting_year = Clamp(value, MIN_YEAR, MAX_YEAR);
 
				break;
 
			case GLAND_SNOW_LEVEL_TEXT:
 
				InvalidateWidget(w, GLAND_SNOW_LEVEL_TEXT);
 
				_patches_newgame.snow_line_height = clamp(value, 2, MAX_SNOWLINE_HEIGHT);
 
				_patches_newgame.snow_line_height = Clamp(value, 2, MAX_SNOWLINE_HEIGHT);
 
				break;
 
			}
 

	
 
			SetWindowDirty(w);
 
		}
 
		break;
 
	}
 
	}
 
}
 

	
 
static const WindowDesc _generate_landscape_desc = {
 
	WDP_CENTER, WDP_CENTER, 338, 268, 338, 268,
 
@@ -648,40 +648,40 @@ static void CreateScenarioWndProc(Window
 
		case CSCEN_EMPTY_WORLD: // Empty world / flat world
 
			StartGeneratingLandscape(GLWP_SCENARIO);
 
			break;
 
		case CSCEN_RANDOM_WORLD: // Generate
 
			ShowGenerateLandscape();
 
			break;
 
		case CSCEN_START_DATE_DOWN: case CSCEN_START_DATE_UP: // Year buttons
 
			/* Don't allow too fast scrolling */
 
			if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
				HandleButtonClick(w, e->we.click.widget);
 
				SetWindowDirty(w);
 

	
 
				_patches_newgame.starting_year = clamp(_patches_newgame.starting_year + e->we.click.widget - CSCEN_START_DATE_TEXT, MIN_YEAR, MAX_YEAR);
 
				_patches_newgame.starting_year = Clamp(_patches_newgame.starting_year + e->we.click.widget - CSCEN_START_DATE_TEXT, MIN_YEAR, MAX_YEAR);
 
			}
 
			_left_button_clicked = false;
 
			break;
 
		case CSCEN_START_DATE_TEXT: // Year text
 
			WP(w, generate_d).widget_id = CSCEN_START_DATE_TEXT;
 
			SetDParam(0, _patches_newgame.starting_year);
 
			ShowQueryString(STR_CONFIG_PATCHES_INT32, STR_START_DATE_QUERY_CAPT, 8, 100, w, CS_NUMERAL);
 
			break;
 
		case CSCEN_FLAT_LAND_HEIGHT_DOWN: case CSCEN_FLAT_LAND_HEIGHT_UP: // Height level buttons
 
			/* Don't allow too fast scrolling */
 
			if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
				HandleButtonClick(w, e->we.click.widget);
 
				SetWindowDirty(w);
 

	
 
				_patches_newgame.se_flat_world_height = clamp(_patches_newgame.se_flat_world_height + e->we.click.widget - CSCEN_FLAT_LAND_HEIGHT_TEXT, 0, MAX_TILE_HEIGHT);
 
				_patches_newgame.se_flat_world_height = Clamp(_patches_newgame.se_flat_world_height + e->we.click.widget - CSCEN_FLAT_LAND_HEIGHT_TEXT, 0, MAX_TILE_HEIGHT);
 
			}
 
			_left_button_clicked = false;
 
			break;
 
		case CSCEN_FLAT_LAND_HEIGHT_TEXT: // Height level text
 
			WP(w, generate_d).widget_id = CSCEN_FLAT_LAND_HEIGHT_TEXT;
 
			SetDParam(0, _patches_newgame.se_flat_world_height);
 
			ShowQueryString(STR_CONFIG_PATCHES_INT32, STR_FLAT_WORLD_HEIGHT_QUERY_CAPT, 3, 100, w, CS_NUMERAL);
 
			break;
 
		}
 
		break;
 

	
 
	case WE_DROPDOWN_SELECT:
 
@@ -690,29 +690,29 @@ static void CreateScenarioWndProc(Window
 
			case CSCEN_MAPSIZE_Y_PULLDOWN: _patches_newgame.map_y = e->we.dropdown.index + 6; break;
 
		}
 
		SetWindowDirty(w);
 
		break;
 

	
 
	case WE_ON_EDIT_TEXT: {
 
		if (e->we.edittext.str != NULL) {
 
			int32 value = atoi(e->we.edittext.str);
 

	
 
			switch (WP(w, generate_d).widget_id) {
 
			case CSCEN_START_DATE_TEXT:
 
				InvalidateWidget(w, CSCEN_START_DATE_TEXT);
 
				_patches_newgame.starting_year = clamp(value, MIN_YEAR, MAX_YEAR);
 
				_patches_newgame.starting_year = Clamp(value, MIN_YEAR, MAX_YEAR);
 
				break;
 
			case CSCEN_FLAT_LAND_HEIGHT_TEXT:
 
				InvalidateWidget(w, CSCEN_FLAT_LAND_HEIGHT_TEXT);
 
				_patches_newgame.se_flat_world_height = clamp(value, 0, MAX_TILE_HEIGHT);
 
				_patches_newgame.se_flat_world_height = Clamp(value, 0, MAX_TILE_HEIGHT);
 
				break;
 
			}
 

	
 
			SetWindowDirty(w);
 
		}
 
		break;
 
	}
 
	}
 
}
 

	
 
static const Widget _create_scenario_widgets[] = {
 
{   WWT_CLOSEBOX, RESIZE_NONE, 13,   0,  10,   0,  13, STR_00C5,                STR_018B_CLOSE_WINDOW},
src/graph_gui.cpp
Show inline comments
 
@@ -997,35 +997,35 @@ static void PerformanceRatingDetailWndPr
 
					score = SCORE_MAX;
 
				} else {
 
					total_score += score;
 
				}
 

	
 
				DrawString(7, y, STR_PERFORMANCE_DETAIL_VEHICLES + i, TC_FROMSTRING);
 

	
 
				/* Draw the score */
 
				SetDParam(0, score);
 
				DrawStringRightAligned(107, y, SET_PERFORMANCE_DETAIL_INT, TC_FROMSTRING);
 

	
 
				/* Calculate the %-bar */
 
				x = clamp(val, 0, needed) * 50 / needed;
 
				x = Clamp(val, 0, needed) * 50 / needed;
 

	
 
				/* SCORE_LOAN is inversed */
 
				if (val < 0 && i == SCORE_LOAN) x = 0;
 

	
 
				/* Draw the bar */
 
				if (x !=  0) GfxFillRect(112,     y - 2, 112 + x,  y + 10, color_done);
 
				if (x != 50) GfxFillRect(112 + x, y - 2, 112 + 50, y + 10, color_notdone);
 

	
 
				/* Calculate the % */
 
				x = clamp(val, 0, needed) * 100 / needed;
 
				x = Clamp(val, 0, needed) * 100 / needed;
 

	
 
				/* SCORE_LOAN is inversed */
 
				if (val < 0 && i == SCORE_LOAN) x = 0;
 

	
 
				/* Draw it */
 
				SetDParam(0, x);
 
				DrawStringCentered(137, y, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING);
 

	
 
				/* SCORE_LOAN is inversed */
 
				if (i == SCORE_LOAN) val = needed - val;
 

	
 
				/* Draw the amount we have against what is needed
src/industry_cmd.cpp
Show inline comments
 
@@ -1619,25 +1619,25 @@ CommandCost CmdBuildIndustry(TileIndex t
 
							SetDParam(1, ind->town->index);
 
						}
 
						AddNewsItem(indspec->new_industry_text,
 
								NEWS_FLAGS(NM_THIN, NF_VIEWPORT | NF_TILE, NT_OPENCLOSE, 0), ind->xy, 0);
 
						break;
 
					}
 
				}
 
			}
 
		}
 
	} else {
 
		int count = indspec->num_table;
 
		const IndustryTileTable * const *itt = indspec->table;
 
		int num = clamp(p2, 0, count - 1);
 
		int num = Clamp(p2, 0, count - 1);
 

	
 
		_error_message = STR_0239_SITE_UNSUITABLE;
 
		do {
 
			if (--count < 0) return CMD_ERROR;
 
			if (--num < 0) num = indspec->num_table - 1;
 
		} while (!CheckIfIndustryTilesAreFree(tile, itt[num], num, p1));
 

	
 
		if (CreateNewIndustryHelper(tile, p1, flags, indspec, num) == NULL) return CMD_ERROR;
 
	}
 

	
 
	return CommandCost(indspec->GetConstructionCost());
 
}
 
@@ -2038,25 +2038,25 @@ static void ChangeIndustryProduction(Ind
 
			for (byte j = 0; j < 2 && i->produced_cargo[j] != CT_INVALID; j++){
 
				uint32 r = Random();
 
				int old_prod, new_prod, percent;
 

	
 
				new_prod = old_prod = i->production_rate[j];
 

	
 
				if (CHANCE16I(20, 1024, r)) new_prod -= max(((RandomRange(50) + 10) * old_prod) >> 8, 1U);
 
				/* Chance of increasing becomes better when more is transported */
 
				if (CHANCE16I(20 + (i->last_month_pct_transported[j] * 20 >> 8), 1024, r >> 16) && !only_decrease) {
 
					new_prod += max(((RandomRange(50) + 10) * old_prod) >> 8, 1U);
 
				}
 

	
 
				new_prod = clamp(new_prod, 1, 255);
 
				new_prod = Clamp(new_prod, 1, 255);
 
				/* Do not stop closing the industry when it has the lowest possible production rate */
 
				if (new_prod == old_prod && old_prod > 1) {
 
					closeit = false;
 
					continue;
 
				}
 

	
 
				percent = (old_prod == 0) ? 100 : (new_prod * 100 / old_prod - 100);
 
				i->production_rate[j] = new_prod;
 

	
 
				/* Close the industry when it has the lowest possible production rate */
 
				if (new_prod > 1) closeit = false;
 

	
src/industry_gui.cpp
Show inline comments
 
@@ -574,25 +574,25 @@ static void IndustryViewWndProc(Window *
 
		break;
 
	case WE_TIMEOUT:
 
		WP(w, indview_d).clicked_line = 0;
 
		WP(w, indview_d).clicked_button = 0;
 
		SetWindowDirty(w);
 
		break;
 

	
 
	case WE_ON_EDIT_TEXT:
 
		if (e->we.edittext.str[0] != '\0') {
 
			Industry* i = GetIndustry(w->window_number);
 
			int line = WP(w, indview_d).editbox_line;
 

	
 
			i->production_rate[line] = clampu(atoi(e->we.edittext.str), 0, 255);
 
			i->production_rate[line] = ClampU(atoi(e->we.edittext.str), 0, 255);
 
			UpdateIndustryProduction(i);
 
			SetWindowDirty(w);
 
		}
 
	}
 
}
 

	
 
static void UpdateIndustryProduction(Industry *i)
 
{
 
	for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
 
		if (i->produced_cargo[j] != CT_INVALID) {
 
			i->last_month_production[j] = 8 * i->production_rate[j];
 
		}
src/macros.h
Show inline comments
 
@@ -142,69 +142,69 @@ static inline uint minu(const uint a, co
 
 *
 
 * This function returns a value which is between the given interval of
 
 * min and max. If the given value is in this interval the value itself
 
 * is returned otherwise the border of the interval is returned, according
 
 * which side of the interval was 'left'.
 
 *
 
 * @note The min value must be less or equal of max or you get some
 
 *       unexpected results.
 
 * @param a The value to clamp/truncate.
 
 * @param min The minimum of the interval.
 
 * @param max the maximum of the interval.
 
 * @returns A value between min and max which is closest to a.
 
 * @see clampu(uint, uint, uint)
 
 * @see ClampU(uint, uint, uint)
 
 */
 
static inline int clamp(const int a, const int min, const int max)
 
static inline int Clamp(const int a, const int min, const int max)
 
{
 
	if (a <= min) return min;
 
	if (a >= max) return max;
 
	return a;
 
}
 

	
 
/**
 
 * Clamp an unsigned integer between an interval.
 
 *
 
 * This function returns a value which is between the given interval of
 
 * min and max. If the given value is in this interval the value itself
 
 * is returned otherwise the border of the interval is returned, according
 
 * which side of the interval was 'left'.
 
 *
 
 * @note The min value must be less or equal of max or you get some
 
 *       unexpected results.
 
 * @param a The value to clamp/truncate.
 
 * @param min The minimum of the interval.
 
 * @param max the maximum of the interval.
 
 * @returns A value between min and max which is closest to a.
 
 * @see clamp(int, int, int)
 
 * @see Clamp(int, int, int)
 
 */
 
static inline uint clampu(const uint a, const uint min, const uint max)
 
static inline uint ClampU(const uint a, const uint min, const uint max)
 
{
 
	if (a <= min) return min;
 
	if (a >= max) return max;
 
	return a;
 
}
 

	
 
/**
 
 * Reduce a signed 64-bit int to a signed 32-bit one
 
 *
 
 * This function clamps a 64-bit integer to a 32-bit integer.
 
 * If the 64-bit value is smaller than the smallest 32-bit integer
 
 * value 0x80000000 this value is returned (the left one bit is the sign bit).
 
 * If the 64-bit value is greater than the greatest 32-bit integer value 0x7FFFFFFF
 
 * this value is returned. In all other cases the 64-bit value 'fits' in a
 
 * 32-bits integer field and so the value is casted to int32 and returned.
 
 *
 
 * @param a The 64-bit value to clamps
 
 * @return The 64-bit value reduced to a 32-bit value
 
 * @see clamp(int, int, int)
 
 * @see Clamp(int, int, int)
 
 */
 
static inline int32 ClampToI32(const int64 a)
 
{
 
	if (a <= (int32)0x80000000) return 0x80000000;
 
	if (a >= (int32)0x7FFFFFFF) return 0x7FFFFFFF;
 
	return (int32)a;
 
}
 

	
 
/**
 
 * Multiply two integer values and shift the results to right.
 
 *
 
 * This function multiplies two integer values. The result is
src/main_gui.cpp
Show inline comments
 
@@ -87,25 +87,25 @@ void HandleOnEditText(const char *str)
 
	_cmd_text = str;
 

	
 
	switch (_rename_what) {
 
	case 1: // Rename a waypoint
 
		if (*str == '\0') return;
 
		DoCommandP(0, id, 0, NULL, CMD_RENAME_WAYPOINT | CMD_MSG(STR_CANT_CHANGE_WAYPOINT_NAME));
 
		break;
 
#ifdef ENABLE_NETWORK
 
	case 3: { // Give money, you can only give money in excess of loan
 
		const Player *p = GetPlayer(_current_player);
 
		Money money = min(p->player_money - p->current_loan, (Money)(atoi(str) / _currency->rate));
 

	
 
		uint32 money_c = clamp(ClampToI32(money), 0, 20000000); // Clamp between 20 million and 0
 
		uint32 money_c = Clamp(ClampToI32(money), 0, 20000000); // Clamp between 20 million and 0
 

	
 
		/* Give 'id' the money, and substract it from ourself */
 
		DoCommandP(0, money_c, id, CcGiveMoney, CMD_GIVE_MONEY | CMD_MSG(STR_INSUFFICIENT_FUNDS));
 
	} break;
 
#endif /* ENABLE_NETWORK */
 
		default: NOT_REACHED();
 
	}
 

	
 
	_rename_id = _rename_what = -1;
 
}
 

	
 
/**
 
@@ -707,25 +707,25 @@ static Window *PopupMainToolbMenu(Window
 
	assert(disabled_mask == 0 || item_count <= 8);
 
	LowerWindowWidget(w, parent_button);
 
	InvalidateWidget(w, parent_button);
 

	
 
	DeleteWindowById(WC_TOOLBAR_MENU, 0);
 

	
 
	/* Extend the dropdown toolbar to the longest string in the list and
 
	 * also make sure the dropdown is fully visible within the window.
 
	 * x + w->left because x is supposed to be the offset of the toolbar-button
 
	 * we clicked on and w->left the toolbar window itself. So meaning that
 
	 * the default position is aligned with the left side of the clicked button */
 
	width = max(GetStringListMaxWidth(base_string, item_count) + 6, 140);
 
	x = w->left + clamp(x, 0, w->width - width); // or alternatively '_screen.width - width'
 
	x = w->left + Clamp(x, 0, w->width - width); // or alternatively '_screen.width - width'
 

	
 
	w = AllocateWindow(x, 22, width, item_count * 10 + 2, MenuWndProc, WC_TOOLBAR_MENU, _menu_widgets);
 
	w->widget[0].bottom = item_count * 10 + 1;
 
	w->flags4 &= ~WF_WHITE_BORDER_MASK;
 

	
 
	WP(w,menu_d).item_count = item_count;
 
	WP(w,menu_d).sel_index = 0;
 
	WP(w,menu_d).main_button = GB(parent_button, 0, 8);
 
	WP(w,menu_d).action_id = (GB(parent_button, 8, 8) != 0) ? GB(parent_button, 8, 8) : parent_button;
 
	WP(w,menu_d).string_id = base_string;
 
	WP(w,menu_d).checked_items = 0;
 
	WP(w,menu_d).disabled_items = disabled_mask;
 
@@ -986,38 +986,38 @@ static void ToolbarOptionsClick(Window *
 
static void ToolbarScenSaveOrLoad(Window *w)
 
{
 
	PopupMainToolbMenu(w, 3, STR_0292_SAVE_SCENARIO, 6, 0);
 
}
 

	
 
static void ToolbarScenDateBackward(Window *w)
 
{
 
	/* don't allow too fast scrolling */
 
	if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
		HandleButtonClick(w, 6);
 
		SetWindowDirty(w);
 

	
 
		_patches_newgame.starting_year = clamp(_patches_newgame.starting_year - 1, MIN_YEAR, MAX_YEAR);
 
		_patches_newgame.starting_year = Clamp(_patches_newgame.starting_year - 1, MIN_YEAR, MAX_YEAR);
 
		SetDate(ConvertYMDToDate(_patches_newgame.starting_year, 0, 1));
 
	}
 
	_left_button_clicked = false;
 
}
 

	
 
static void ToolbarScenDateForward(Window *w)
 
{
 
	/* don't allow too fast scrolling */
 
	if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
		HandleButtonClick(w, 7);
 
		SetWindowDirty(w);
 

	
 
		_patches_newgame.starting_year = clamp(_patches_newgame.starting_year + 1, MIN_YEAR, MAX_YEAR);
 
		_patches_newgame.starting_year = Clamp(_patches_newgame.starting_year + 1, MIN_YEAR, MAX_YEAR);
 
		SetDate(ConvertYMDToDate(_patches_newgame.starting_year, 0, 1));
 
	}
 
	_left_button_clicked = false;
 
}
 

	
 
static void ToolbarScenMapTownDir(Window *w)
 
{
 
	/* Scenario editor button, *hack*hack* use different button to activate */
 
	PopupMainToolbMenu(w, 8 | (17 << 8), STR_02DE_MAP_OF_WORLD, 4, 0);
 
}
 

	
 
static void ToolbarScenZoomIn(Window *w)
src/misc_gui.cpp
Show inline comments
 
@@ -600,26 +600,26 @@ void ShowErrorMessage(StringID msg_1, St
 
			pt.y = UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top;
 
			pt.y = (pt.y < (_screen.height >> 1)) ? _screen.height - 80 : 100;
 

	
 
		} else {
 
			pt.x = (_screen.width - 240) >> 1;
 
			pt.y = (_screen.height - 46) >> 1;
 
		}
 
		w = AllocateWindow(pt.x, pt.y, 240, 46, ErrmsgWndProc, WC_ERRMSG, _errmsg_widgets);
 
	} else {
 
		if ( (x|y) != 0) {
 
			pt = RemapCoords2(x, y);
 
			vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
 
			pt.x = clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (334/2), 0, _screen.width - 334);
 
			pt.y = clamp(UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top - (137/2), 22, _screen.height - 137);
 
			pt.x = Clamp(UnScaleByZoom(pt.x - vp->virtual_left, vp->zoom) + vp->left - (334/2), 0, _screen.width - 334);
 
			pt.y = Clamp(UnScaleByZoom(pt.y - vp->virtual_top, vp->zoom) + vp->top - (137/2), 22, _screen.height - 137);
 
		} else {
 
			pt.x = (_screen.width - 334) >> 1;
 
			pt.y = (_screen.height - 137) >> 1;
 
		}
 
		w = AllocateWindow(pt.x, pt.y, 334, 137, ErrmsgWndProc, WC_ERRMSG, _errmsg_face_widgets);
 
	}
 

	
 
	w->desc_flags = WDF_STD_BTN | WDF_DEF_WIDGET;
 
}
 

	
 

	
 
void ShowEstimatedCostOrIncome(Money cost, int x, int y)
 
@@ -737,27 +737,27 @@ void GuiShowTooltipsWithArgs(StringID st
 
	br = GetStringBoundingBox(buffer);
 
	br.width += 6; br.height += 4; // increase slightly to have some space around the box
 

	
 
	/* Cut tooltip length to 200 pixels max, wrap to new line if longer */
 
	if (br.width > 200) {
 
		br.height += ((br.width - 4) / 176) * 10;
 
		br.width = 200;
 
	}
 

	
 
	/* Correctly position the tooltip position, watch out for window and cursor size
 
	 * Clamp value to below main toolbar and above statusbar. If tooltip would
 
	 * go below window, flip it so it is shown above the cursor */
 
	y = clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, 22, _screen.height - 12);
 
	y = Clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, 22, _screen.height - 12);
 
	if (y + br.height > _screen.height - 12) y = _cursor.pos.y + _cursor.offs.y - br.height - 5;
 
	x = clamp(_cursor.pos.x - (br.width >> 1), 0, _screen.width - br.width);
 
	x = Clamp(_cursor.pos.x - (br.width >> 1), 0, _screen.width - br.width);
 

	
 
	w = AllocateWindow(x, y, br.width, br.height, TooltipsWndProc, WC_TOOLTIPS, _tooltips_widgets);
 

	
 
	WP(w, tooltips_d).string_id = str;
 
	assert(sizeof(WP(w, tooltips_d).params[0]) == sizeof(params[0]));
 
	memcpy(WP(w, tooltips_d).params, params, sizeof(WP(w, tooltips_d).params[0]) * paramcount);
 
	WP(w, tooltips_d).paramcount = paramcount;
 

	
 
	w->flags4 &= ~WF_WHITE_BORDER_MASK; // remove white-border from tooltip
 
	w->widget[0].right = br.width;
 
	w->widget[0].bottom = br.height;
 
}
 
@@ -1929,25 +1929,25 @@ static void CheatsWndProc(Window *w, Win
 
				if (ce->flags & CE_CLICK) WP(w,def_d).data_1 = btn * 2 + 1;
 
				value ^= 1;
 
				if (ce->proc != NULL) ce->proc(value, 0);
 
				break;
 
			default: {
 
				/* Add a dynamic step-size to the scroller. In a maximum of
 
				 * 50-steps you should be able to get from min to max */
 
				uint16 step = ((ce->max - ce->min) / 20);
 
				if (step == 0) step = 1;
 

	
 
				/* Increase or decrease the value and clamp it to extremes */
 
				value += (x >= 30) ? step : -step;
 
				value = clamp(value, ce->min, ce->max);
 
				value = Clamp(value, ce->min, ce->max);
 

	
 
				/* take whatever the function returns */
 
				value = ce->proc(value, (x >= 30) ? 1 : -1);
 

	
 
				if (value != oldvalue) {
 
					WP(w,def_d).data_1 = btn * 2 + 1 + ((x >= 30) ? 1 : 0);
 
				}
 
			} break;
 
			}
 

	
 
			if (value != oldvalue) {
 
				WriteValue(ce->variable, ce->type, (int64)value);
src/network/core/udp.cpp
Show inline comments
 
@@ -221,26 +221,26 @@ void NetworkUDPSocketHandler::Recv_Netwo
 

	
 
			for (i = 0; i < num_grfs; i++) {
 
				GRFConfig *c = CallocT<GRFConfig>(1);
 
				this->Recv_GRFIdentifier(p, c);
 
				this->HandleIncomingNetworkGameInfoGRFConfig(c);
 

	
 
				/* Append GRFConfig to the list */
 
				*dst = c;
 
				dst = &c->next;
 
			}
 
		} /* Fallthrough */
 
		case 3:
 
			info->game_date      = clamp(p->Recv_uint32(), 0, MAX_DATE);
 
			info->start_date     = clamp(p->Recv_uint32(), 0, MAX_DATE);
 
			info->game_date      = Clamp(p->Recv_uint32(), 0, MAX_DATE);
 
			info->start_date     = Clamp(p->Recv_uint32(), 0, MAX_DATE);
 
			/* Fallthrough */
 
		case 2:
 
			info->companies_max  = p->Recv_uint8 ();
 
			info->companies_on   = p->Recv_uint8 ();
 
			info->spectators_max = p->Recv_uint8 ();
 
			/* Fallthrough */
 
		case 1:
 
			p->Recv_string(info->server_name,     sizeof(info->server_name));
 
			p->Recv_string(info->server_revision, sizeof(info->server_revision));
 
			info->server_lang    = p->Recv_uint8 ();
 
			info->use_password   = p->Recv_bool  ();
 
			info->clients_max    = p->Recv_uint8 ();
src/network/network_gui.cpp
Show inline comments
 
@@ -683,27 +683,27 @@ static void NetworkStartServerWindowWndP
 
		case 7: case 8: /* Connection type */
 
			ShowDropDownMenu(w, _connection_types_dropdown, _network_advertise, 8, 0, 0); // do it for widget 8
 
			break;
 
		case  9: case 11: // Click on up/down button for number of players
 
		case 12: case 14: // Click on up/down button for number of companies
 
		case 15: case 17: // Click on up/down button for number of spectators
 
			/* Don't allow too fast scrolling */
 
			if ((w->flags4 & WF_TIMEOUT_MASK) <= 2 << WF_TIMEOUT_SHL) {
 
				HandleButtonClick(w, e->we.click.widget);
 
				SetWindowDirty(w);
 
				switch (e->we.click.widget) {
 
					default: NOT_REACHED();
 
					case  9: case 11: _network_game_info.clients_max    = clamp(_network_game_info.clients_max    + e->we.click.widget - 10, 2, MAX_CLIENTS); break;
 
					case 12: case 14: _network_game_info.companies_max  = clamp(_network_game_info.companies_max  + e->we.click.widget - 13, 1, MAX_PLAYERS); break;
 
					case 15: case 17: _network_game_info.spectators_max = clamp(_network_game_info.spectators_max + e->we.click.widget - 16, 0, MAX_CLIENTS); break;
 
					case  9: case 11: _network_game_info.clients_max    = Clamp(_network_game_info.clients_max    + e->we.click.widget - 10, 2, MAX_CLIENTS); break;
 
					case 12: case 14: _network_game_info.companies_max  = Clamp(_network_game_info.companies_max  + e->we.click.widget - 13, 1, MAX_PLAYERS); break;
 
					case 15: case 17: _network_game_info.spectators_max = Clamp(_network_game_info.spectators_max + e->we.click.widget - 16, 0, MAX_CLIENTS); break;
 
				}
 
			}
 
			_left_button_clicked = false;
 
			break;
 
		case 10: // Click on number of players
 
			nd->widget_id = 10;
 
			SetDParam(0, _network_game_info.clients_max);
 
			ShowQueryString(STR_CONFIG_PATCHES_INT32, STR_NETWORK_NUMBER_OF_CLIENTS, 3, 50, w, CS_NUMERAL);
 
			break;
 
		case 13: // Click on number of companies
 
			nd->widget_id = 13;
 
			SetDParam(0, _network_game_info.companies_max);
 
@@ -780,27 +780,27 @@ static void NetworkStartServerWindowWndP
 

	
 
	case WE_ON_EDIT_TEXT:
 
		if (e->we.edittext.str == NULL) break;
 

	
 
		if (nd->widget_id == 4) {
 
			ttd_strlcpy(_network_server_password, e->we.edittext.str, lengthof(_network_server_password));
 
			_network_game_info.use_password = (_network_server_password[0] != '\0');
 
		} else {
 
			int32 value = atoi(e->we.edittext.str);
 
			InvalidateWidget(w, nd->widget_id);
 
			switch (nd->widget_id) {
 
				default: NOT_REACHED();
 
				case 10: _network_game_info.clients_max    = clamp(value, 2, MAX_CLIENTS); break;
 
				case 13: _network_game_info.companies_max  = clamp(value, 1, MAX_PLAYERS); break;
 
				case 16: _network_game_info.spectators_max = clamp(value, 0, MAX_CLIENTS); break;
 
				case 10: _network_game_info.clients_max    = Clamp(value, 2, MAX_CLIENTS); break;
 
				case 13: _network_game_info.companies_max  = Clamp(value, 1, MAX_PLAYERS); break;
 
				case 16: _network_game_info.spectators_max = Clamp(value, 0, MAX_CLIENTS); break;
 
			}
 
		}
 

	
 
		SetWindowDirty(w);
 
		break;
 
	}
 
}
 

	
 
static const Widget _network_start_server_window_widgets[] = {
 
{   WWT_CLOSEBOX,   RESIZE_NONE,   BGC,     0,    10,     0,    13, STR_00C5,                       STR_018B_CLOSE_WINDOW },
 
{    WWT_CAPTION,   RESIZE_NONE,   BGC,    11,   419,     0,    13, STR_NETWORK_START_GAME_WINDOW,  STR_NULL},
 
{      WWT_PANEL,   RESIZE_NONE,   BGC,     0,   419,    14,   243, 0x0,                            STR_NULL},
src/newgrf.cpp
Show inline comments
 
@@ -1184,25 +1184,25 @@ static bool BridgeChangeInfo(uint brid, 
 

	
 
						bridge->sprite_table[tableid][sprite].sprite = image;
 
						bridge->sprite_table[tableid][sprite].pal    = pal;
 
					}
 
				}
 
			} break;
 

	
 
			case 0x0E: // Flags; bit 0 - disable far pillars
 
				bridge->flags = grf_load_byte(&buf);
 
				break;
 

	
 
			case 0x0F: // Long format year of availability (year since year 0)
 
				bridge->avail_year = clamp(grf_load_dword(&buf), MIN_YEAR, MAX_YEAR);
 
				bridge->avail_year = Clamp(grf_load_dword(&buf), MIN_YEAR, MAX_YEAR);
 
				break;
 

	
 
			default:
 
				ret = true;
 
				break;
 
		}
 
	}
 

	
 
	*bufp = buf;
 
	return ret;
 
}
 

	
 
@@ -1361,25 +1361,25 @@ static bool TownHouseChangeInfo(uint hid
 
				housespec->probability = grf_load_byte(&buf);
 
				break;
 

	
 
			case 0x19: // Extra flags
 
				housespec->extra_flags = (HouseExtraFlags)grf_load_byte(&buf);
 
				break;
 

	
 
			case 0x1A: // Animation frames
 
				housespec->animation_frames = grf_load_byte(&buf);
 
				break;
 

	
 
			case 0x1B: // Animation speed
 
				housespec->animation_speed = clamp(grf_load_byte(&buf), 2, 16);
 
				housespec->animation_speed = Clamp(grf_load_byte(&buf), 2, 16);
 
				break;
 

	
 
			case 0x1C: // Class of the building type
 
				housespec->class_id = AllocateHouseClassID(grf_load_byte(&buf), _cur_grffile->grfid);
 
				break;
 

	
 
			case 0x1D: // Callback flags 2
 
				housespec->callback_mask |= (grf_load_byte(&buf) << 8);
 
				break;
 

	
 
			case 0x1E: { // Accepted cargo types
 
				uint32 cargotypes = grf_load_dword(&buf);
 
@@ -3400,25 +3400,25 @@ static void SkipAct5(byte *buf, int len)
 
	grf_load_byte(&buf);
 

	
 
	/* Skip the sprites of this action */
 
	_skip_sprites = grf_load_extended(&buf);
 

	
 
	grfmsg(3, "SkipAct5: Skipping %d sprites", _skip_sprites);
 
}
 

	
 
static uint32 GetParamVal(byte param, uint32 *cond_val)
 
{
 
	switch (param) {
 
		case 0x81: // current year
 
			return clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
			return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 

	
 
		case 0x83: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
 
			return _opt.landscape;
 

	
 
		case 0x84: { // GRF loading stage
 
			uint32 res = 0;
 

	
 
			if (_cur_stage > GLS_INIT) SETBIT(res, 0);
 
			if (_cur_stage == GLS_RESERVE) SETBIT(res, 8);
 
			if (_cur_stage == GLS_ACTIVATION) SETBIT(res, 9);
 
			return res;
 
		}
src/newgrf_engine.cpp
Show inline comments
 
@@ -487,25 +487,25 @@ static uint8 LiveryHelper(EngineID engin
 

	
 

	
 
static uint32 VehicleGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
 
{
 
	const Vehicle *v = GRV(object);
 

	
 
	if (v == NULL) {
 
		/* Vehicle does not exist, so we're in a purchase list */
 
		switch (variable) {
 
			case 0x43: return _current_player | (LiveryHelper(object->u.vehicle.self_type, NULL) << 24); // Owner information
 
			case 0x46: return 0;               // Motion counter
 
			case 0x48: return GetEngine(object->u.vehicle.self_type)->flags; // Vehicle Type Info
 
			case 0xC4: return clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
 
			case 0xC4: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR; // Build year
 
			case 0xDA: return INVALID_VEHICLE; // Next vehicle
 
			case 0x7F: return GetGRFParameter(object->u.vehicle.self_type, parameter); // Read GRF parameter
 
		}
 

	
 
		*available = false;
 
		return UINT_MAX;
 
	}
 

	
 
	/* Calculated vehicle parameters */
 
	switch (variable) {
 
		case 0x40: // Get length of consist
 
		case 0x41: // Get length of same consecutive wagons
 
@@ -702,25 +702,25 @@ static uint32 VehicleGetVariable(const R
 
		case 0x37: return v->acceleration;
 
		case 0x39: return v->cargo_type;
 
		case 0x3A: return v->cargo_cap;
 
		case 0x3B: return GB(v->cargo_cap, 8, 8);
 
		case 0x3C: return v->cargo.Count();
 
		case 0x3D: return GB(v->cargo.Count(), 8, 8);
 
		case 0x3E: return v->cargo.Source();
 
		case 0x3F: return v->cargo.DaysInTransit();
 
		case 0x40: return v->age;
 
		case 0x41: return GB(v->age, 8, 8);
 
		case 0x42: return v->max_age;
 
		case 0x43: return GB(v->max_age, 8, 8);
 
		case 0x44: return clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
		case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
		case 0x45: return v->unitnumber;
 
		case 0x46: return v->engine_type;
 
		case 0x47: return GB(v->engine_type, 8, 8);
 
		case 0x48: return v->spritenum;
 
		case 0x49: return v->day_counter;
 
		case 0x4A: return v->breakdowns_since_last_service;
 
		case 0x4B: return v->breakdown_ctr;
 
		case 0x4C: return v->breakdown_delay;
 
		case 0x4D: return v->breakdown_chance;
 
		case 0x4E: return v->reliability;
 
		case 0x4F: return GB(v->reliability, 8, 8);
 
		case 0x50: return v->reliability_spd_dec;
src/newgrf_house.cpp
Show inline comments
 
@@ -202,25 +202,25 @@ static uint32 HouseGetVariable(const Res
 
	TileIndex tile   = object->u.house.tile;
 
	HouseID house_id = object->u.house.house_id;
 

	
 
	if (object->scope == VSG_SCOPE_PARENT) {
 
		return TownGetVariable(variable, parameter, available, town);
 
	}
 

	
 
	switch (variable) {
 
		/* Construction stage. */
 
		case 0x40: return (IsTileType(tile, MP_HOUSE) ? GetHouseBuildingStage(tile) : 0) | OriginalTileRandomiser(TileX(tile), TileY(tile)) << 2;
 

	
 
		/* Building age. */
 
		case 0x41: return clamp(_cur_year - GetHouseConstructionYear(tile), 0, 0xFF);
 
		case 0x41: return Clamp(_cur_year - GetHouseConstructionYear(tile), 0, 0xFF);
 

	
 
		/* Town zone */
 
		case 0x42: return GetTownRadiusGroup(town, tile);
 

	
 
		/* Terrain type */
 
		case 0x43: return GetTerrainType(tile);
 

	
 
		/* Number of this type of building on the map. */
 
		case 0x44: return GetNumHouses(house_id, town);
 

	
 
		/* Whether the town is being created or just expanded. */
 
		case 0x45: return _generating_world ? 1 : 0;
 
@@ -360,38 +360,38 @@ void DrawNewHouseTile(TileInfo *ti, Hous
 

	
 
	if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 

	
 
	NewHouseResolver(&object, house_id, ti->tile, GetTownByTile(ti->tile));
 

	
 
	group = Resolve(hs->spritegroup, &object);
 
	if (group == NULL || group->type != SGT_TILELAYOUT) {
 
		/* XXX: This is for debugging purposes really, and shouldn't stay. */
 
		DrawGroundSprite(SPR_SHADOW_CELL, PAL_NONE);
 
	} else {
 
		/* Limit the building stage to the number of stages supplied. */
 
		byte stage = GetHouseBuildingStage(ti->tile);
 
		stage = clamp(stage - 4 + group->g.layout.num_sprites, 0, group->g.layout.num_sprites - 1);
 
		stage = Clamp(stage - 4 + group->g.layout.num_sprites, 0, group->g.layout.num_sprites - 1);
 
		DrawTileLayout(ti, group, stage, house_id);
 
	}
 
}
 

	
 
void AnimateNewHouseTile(TileIndex tile)
 
{
 
	const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
 
	byte animation_speed = hs->animation_speed;
 
	bool frame_set_by_callback = false;
 

	
 
	if (HASBIT(hs->callback_mask, CBM_HOUSE_ANIMATION_SPEED)) {
 
		uint16 callback_res = GetHouseCallback(CBID_HOUSE_ANIMATION_SPEED, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
 
		if (callback_res != CALLBACK_FAILED) animation_speed = clamp(callback_res & 0xFF, 2, 16);
 
		if (callback_res != CALLBACK_FAILED) animation_speed = Clamp(callback_res & 0xFF, 2, 16);
 
	}
 

	
 
	/* An animation speed of 2 means the animation frame changes 4 ticks, and
 
	 * increasing this value by one doubles the wait. 2 is the minimum value
 
	 * allowed for animation_speed, which corresponds to 120ms, and 16 is the
 
	 * maximum, corresponding to around 33 minutes. */
 
	if (_tick_counter % (1 << animation_speed) != 0) return;
 

	
 
	byte frame      = GetHouseAnimationFrame(tile);
 
	byte num_frames = GB(hs->animation_frames, 0, 7);
 

	
 
	if (HASBIT(hs->callback_mask, CBM_HOUSE_ANIMATION_NEXT_FRAME)) {
src/newgrf_industries.cpp
Show inline comments
 
@@ -306,32 +306,32 @@ uint32 IndustryGetVariable(const Resolve
 
		case 0x9F: return GB(industry->last_month_production[0], 8, 8);
 
		case 0xA0: return industry->last_month_production[1];
 
		case 0xA1: return GB(industry->last_month_production[1], 8, 8);
 
		/* amount of cargo transported last month. */
 
		case 0xA2: return industry->last_month_transported[0];
 
		case 0xA3: return GB(industry->last_month_transported[0], 8, 8);
 
		case 0xA4: return industry->last_month_transported[1];
 
		case 0xA5: return GB(industry->last_month_transported[0], 8, 8);
 

	
 
		case 0xA6: return industry->type;
 
		case 0xA7: return industry->founder;
 
		case 0xA8: return industry->random_color;
 
		case 0xA9: return clamp(0, industry->last_prod_year - 1920, 255);
 
		case 0xA9: return Clamp(0, industry->last_prod_year - 1920, 255);
 
		case 0xAA: return industry->counter;
 
		case 0xAB: return GB(industry->counter, 8, 8);
 
		case 0xAC: return industry->was_cargo_delivered;
 

	
 
		case 0xB0: return clamp(0, industry->construction_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 65535); // Date when built since 1920 (in days)
 
		case 0xB0: return Clamp(0, industry->construction_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 65535); // Date when built since 1920 (in days)
 
		case 0xB3: return industry->construction_type; // Construction type
 
		case 0xB4: return clamp(0, industry->last_cargo_accepted_at - DAYS_TILL_ORIGINAL_BASE_YEAR, 65535); // Date last cargo accepted since 1920 (in days)
 
		case 0xB4: return Clamp(0, industry->last_cargo_accepted_at - DAYS_TILL_ORIGINAL_BASE_YEAR, 65535); // Date last cargo accepted since 1920 (in days)
 
	}
 

	
 
	DEBUG(grf, 1, "Unhandled industry property 0x%X", variable);
 

	
 
	*available = false;
 
	return (uint32)-1;
 
}
 

	
 
static const SpriteGroup *IndustryResolveReal(const ResolverObject *object, const SpriteGroup *group)
 
{
 
	/* IndustryTile do not have 'real' groups */
 
	return NULL;
 
@@ -506,28 +506,28 @@ void IndustryProductionCallback(Industry
 
	NewIndustryResolver(&object, ind->xy, ind);
 
	if ((spec->behaviour & INDUSTRYBEH_PRODCALLBACK_RANDOM) != 0) object.callback_param1 = Random();
 
	object.callback_param2 = reason;
 

	
 
	for (uint loop = 0;; loop++) {
 
		SB(object.callback_param2, 8, 16, loop);
 
		const SpriteGroup *group = Resolve(spec->grf_prop.spritegroup, &object);
 
		if (group == NULL || group->type != SGT_INDUSTRY_PRODUCTION) break;
 

	
 
		bool deref = (group->g.indprod.version == 1);
 

	
 
		for (uint i = 0; i < 3; i++) {
 
			ind->incoming_cargo_waiting[i] = clamp(ind->incoming_cargo_waiting[i] - DerefIndProd(group->g.indprod.substract_input[i], deref), 0, 0xFFFF);
 
			ind->incoming_cargo_waiting[i] = Clamp(ind->incoming_cargo_waiting[i] - DerefIndProd(group->g.indprod.substract_input[i], deref), 0, 0xFFFF);
 
		}
 
		for (uint i = 0; i < 2; i++) {
 
			ind->produced_cargo_waiting[i] = clamp(ind->produced_cargo_waiting[i] + DerefIndProd(group->g.indprod.add_output[i], deref), 0, 0xFFFF);
 
			ind->produced_cargo_waiting[i] = Clamp(ind->produced_cargo_waiting[i] + DerefIndProd(group->g.indprod.add_output[i], deref), 0, 0xFFFF);
 
		}
 

	
 
		int32 again = DerefIndProd(group->g.indprod.again, deref);
 
		if (again == 0) break;
 

	
 
		SB(object.callback_param2, 24, 8, again);
 
	}
 

	
 
	InvalidateWindow(WC_INDUSTRY_VIEW, ind->index);
 
}
 

	
 
void DoTriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
src/newgrf_industrytiles.cpp
Show inline comments
 
@@ -235,25 +235,25 @@ bool DrawNewIndustryTile(TileInfo *ti, I
 

	
 
		if (draw_old_one) DrawFoundation(ti, FOUNDATION_LEVELED);
 
	}
 

	
 
	NewIndustryTileResolver(&object, gfx, ti->tile, i);
 

	
 
	group = Resolve(inds->grf_prop.spritegroup, &object);
 
	if (group == NULL || group->type != SGT_TILELAYOUT) {
 
		return false;
 
	} else {
 
		/* Limit the building stage to the number of stages supplied. */
 
		byte stage = GetIndustryConstructionStage(ti->tile);
 
		stage = clamp(stage - 4 + group->g.layout.num_sprites, 0, group->g.layout.num_sprites - 1);
 
		stage = Clamp(stage - 4 + group->g.layout.num_sprites, 0, group->g.layout.num_sprites - 1);
 
		IndustryDrawTileLayout(ti, group, i->random_color, stage, gfx);
 
		return true;
 
	}
 
}
 

	
 
extern bool IsSlopeRefused(Slope current, Slope refused);
 

	
 
bool PerformIndustryTileSlopeCheck(TileIndex ind_base_tile, TileIndex ind_tile, const IndustryTileSpec *its, IndustryType type, IndustryGfx gfx, uint itspec_index)
 
{
 
	Industry ind;
 
	ind.index = INVALID_INDUSTRY;
 
	ind.xy = ind_base_tile;
 
@@ -282,25 +282,25 @@ bool PerformIndustryTileSlopeCheck(TileI
 
	}
 
}
 

	
 
void AnimateNewIndustryTile(TileIndex tile)
 
{
 
	Industry *ind = GetIndustryByTile(tile);
 
	IndustryGfx gfx = GetIndustryGfx(tile);
 
	const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
 
	byte animation_speed = itspec->animation_speed;
 

	
 
	if (HASBIT(itspec->callback_flags, CBM_INDT_ANIM_SPEED)) {
 
		uint16 callback_res = GetIndustryTileCallback(CBID_INDTILE_ANIMATION_SPEED, 0, 0, gfx, ind, tile);
 
		if (callback_res != CALLBACK_FAILED) animation_speed = clamp(callback_res & 0xFF, 0, 16);
 
		if (callback_res != CALLBACK_FAILED) animation_speed = Clamp(callback_res & 0xFF, 0, 16);
 
	}
 

	
 
	/* An animation speed of 2 means the animation frame changes 4 ticks, and
 
	 * increasing this value by one doubles the wait. 0 is the minimum value
 
	 * allowed for animation_speed, which corresponds to 30ms, and 16 is the
 
	 * maximum, corresponding to around 33 minutes. */
 
	if ((_tick_counter % (1 << animation_speed)) != 0) return;
 

	
 
	bool frame_set_by_callback = false;
 
	byte frame = GetIndustryAnimationState(tile);
 
	uint16 num_frames = GB(itspec->animation_info, 0, 8);
 

	
src/newgrf_spritegroup.cpp
Show inline comments
 
@@ -75,25 +75,25 @@ void InitializeSpriteGroupPool()
 

	
 
	_spritegroup_count = 0;
 
}
 

	
 
TemporaryStorageArray<uint32, 0x110> _temp_store;
 

	
 

	
 
static inline uint32 GetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
 
{
 
	/* Return common variables */
 
	switch (variable) {
 
		case 0x00: return max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
 
		case 0x01: return clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
		case 0x01: return Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
		case 0x02: return _cur_month;
 
		case 0x03: return _opt.landscape;
 
		case 0x09: return _date_fract;
 
		case 0x0A: return _tick_counter;
 
		case 0x0C: return object->callback;
 
		case 0x10: return object->callback_param1;
 
		case 0x11: return 0;
 
		case 0x18: return object->callback_param2;
 
		case 0x1A: return UINT_MAX;
 
		case 0x1B: return GB(_display_opt, 0, 6);
 
		case 0x1C: return object->last_value;
 
		case 0x20: return _opt.landscape == LT_ARCTIC ? GetSnowLine() : 0xFF;
src/newgrf_station.cpp
Show inline comments
 
@@ -383,25 +383,25 @@ static uint32 StationGetVariable(const R
 

	
 
	if (st == NULL) {
 
		/* Station does not exist, so we're in a purchase list */
 
		switch (variable) {
 
			case 0x40:
 
			case 0x41:
 
			case 0x46:
 
			case 0x47:
 
			case 0x49: return 0x2110000;       // Platforms, tracks & position
 
			case 0x42: return 0;               // Rail type (XXX Get current type from GUI?)
 
			case 0x43: return _current_player; // Station owner
 
			case 0x44: return 2;               // PBS status
 
			case 0xFA: return clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
 
			case 0xFA: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
 
		}
 

	
 
		*available = false;
 
		return UINT_MAX;
 
	}
 

	
 
	switch (variable) {
 
		/* Calculated station variables */
 
		case 0x40:
 
			if (!HASBIT(_svc.valid, 0)) { _svc.v40 = GetPlatformInfoHelper(tile, false, false, false); SETBIT(_svc.valid, 0); }
 
			return _svc.v40;
 

	
 
@@ -442,25 +442,25 @@ static uint32 StationGetVariable(const R
 

	
 
		/* General station properties */
 
		case 0x82: return 50;
 
		case 0x84: return st->string_id;
 
		case 0x86: return 0;
 
		case 0x8A: return st->had_vehicle_of_type;
 
		case 0xF0: return st->facilities;
 
		case 0xF1: return st->airport_type;
 
		case 0xF2: return st->truck_stops->status;
 
		case 0xF3: return st->bus_stops->status;
 
		case 0xF6: return st->airport_flags;
 
		case 0xF7: return GB(st->airport_flags, 8, 8);
 
		case 0xFA: return clamp(st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
 
		case 0xFA: return Clamp(st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
 
	}
 

	
 
	/* Handle cargo variables with parameter, 0x60 to 0x65 */
 
	if (variable >= 0x60 && variable <= 0x65) {
 
		CargoID c = GetCargoTranslation(parameter, object->u.station.statspec->grffile);
 

	
 
		if (c == CT_INVALID) return 0;
 
		const GoodsEntry *ge = &st->goods[c];
 

	
 
		switch (variable) {
 
			case 0x60: return min(ge->cargo.Count(), 4095);
 
			case 0x61: return ge->days_since_pickup;
src/npf.cpp
Show inline comments
 
@@ -95,28 +95,28 @@ static TileIndex CalcClosestStationTile(
 
{
 
	const Station* st = GetStation(station);
 

	
 
	uint minx = TileX(st->train_tile);  // topmost corner of station
 
	uint miny = TileY(st->train_tile);
 
	uint maxx = minx + st->trainst_w - 1; // lowermost corner of station
 
	uint maxy = miny + st->trainst_h - 1;
 
	uint x;
 
	uint y;
 

	
 
	/* we are going the aim for the x coordinate of the closest corner
 
	 * but if we are between those coordinates, we will aim for our own x coordinate */
 
	x = clamp(TileX(tile), minx, maxx);
 
	x = Clamp(TileX(tile), minx, maxx);
 

	
 
	/* same for y coordinate, see above comment */
 
	y = clamp(TileY(tile), miny, maxy);
 
	y = Clamp(TileY(tile), miny, maxy);
 

	
 
	/* return the tile of our target coordinates */
 
	return TileXY(x, y);
 
}
 

	
 
/* Calcs the heuristic to the target station or tile. For train stations, it
 
 * takes into account the direction of approach.
 
 */
 
static int32 NPFCalcStationOrTileHeuristic(AyStar* as, AyStarNode* current, OpenListNode* parent)
 
{
 
	NPFFindStationOrTileData* fstd = (NPFFindStationOrTileData*)as->user_target;
 
	NPFFoundTargetData* ftd = (NPFFoundTargetData*)as->user_path;
src/oldloader.cpp
Show inline comments
 
@@ -1626,25 +1626,25 @@ static bool LoadOldMain(LoadgameState *l
 
			e->player_avail = (byte)-1;
 
		}
 
	}
 

	
 
	/* Fix the game to be compatible with OpenTTD */
 
	FixOldTowns();
 
	FixOldStations();
 
	FixOldVehicles();
 

	
 
	AddTypeToEngines();
 

	
 
	/* We have a new difficulty setting */
 
	_opt.diff.town_council_tolerance = clamp(_opt.diff_level, 0, 2);
 
	_opt.diff.town_council_tolerance = Clamp(_opt.diff_level, 0, 2);
 

	
 
	DEBUG(oldloader, 3, "Finished converting game data");
 
	DEBUG(oldloader, 1, "TTD(Patch) savegame successfully converted");
 

	
 
	return true;
 
}
 

	
 
bool LoadOldSaveGame(const char *file)
 
{
 
	LoadgameState ls;
 

	
 
	DEBUG(oldloader, 3, "Trying to load a TTD(Patch) savegame");
src/openttd.cpp
Show inline comments
 
@@ -271,26 +271,26 @@ md_continue_here:;
 
	}
 
}
 

	
 

	
 
static void ParseResolution(int res[2], const char *s)
 
{
 
	const char *t = strchr(s, 'x');
 
	if (t == NULL) {
 
		ShowInfoF("Invalid resolution '%s'", s);
 
		return;
 
	}
 

	
 
	res[0] = clamp(strtoul(s, NULL, 0), 64, MAX_SCREEN_WIDTH);
 
	res[1] = clamp(strtoul(t + 1, NULL, 0), 64, MAX_SCREEN_HEIGHT);
 
	res[0] = Clamp(strtoul(s, NULL, 0), 64, MAX_SCREEN_WIDTH);
 
	res[1] = Clamp(strtoul(t + 1, NULL, 0), 64, MAX_SCREEN_HEIGHT);
 
}
 

	
 
static void InitializeDynamicVariables()
 
{
 
	/* Dynamic stuff needs to be initialized somewhere... */
 
	_town_sort     = NULL;
 
	_industry_sort = NULL;
 
	_industry_mngr.ResetMapping();
 
	_industile_mngr.ResetMapping();
 
}
 

	
 

	
src/players.cpp
Show inline comments
 
@@ -86,25 +86,25 @@ void DrawPlayerIcon(PlayerID p, int x, i
 
 * @return the face in the new format
 
 */
 
PlayerFace ConvertFromOldPlayerFace(uint32 face)
 
{
 
	PlayerFace pf = 0;
 
	GenderEthnicity ge = GE_WM;
 

	
 
	if (HASBIT(face, 31)) SetBitT(ge, GENDER_FEMALE);
 
	if (HASBIT(face, 27) && (HASBIT(face, 26) == HASBIT(face, 19))) SetBitT(ge, ETHNICITY_BLACK);
 

	
 
	SetPlayerFaceBits(pf, PFV_GEN_ETHN,    ge, ge);
 
	SetPlayerFaceBits(pf, PFV_HAS_GLASSES, ge, GB(face, 28, 3) <= 1);
 
	SetPlayerFaceBits(pf, PFV_EYE_COLOUR,  ge, HASBIT(ge, ETHNICITY_BLACK) ? 0 : clampu(GB(face, 20, 3), 5, 7) - 5);
 
	SetPlayerFaceBits(pf, PFV_EYE_COLOUR,  ge, HASBIT(ge, ETHNICITY_BLACK) ? 0 : ClampU(GB(face, 20, 3), 5, 7) - 5);
 
	SetPlayerFaceBits(pf, PFV_CHIN,        ge, ScalePlayerFaceValue(PFV_CHIN,     ge, GB(face,  4, 2)));
 
	SetPlayerFaceBits(pf, PFV_EYEBROWS,    ge, ScalePlayerFaceValue(PFV_EYEBROWS, ge, GB(face,  6, 4)));
 
	SetPlayerFaceBits(pf, PFV_HAIR,        ge, ScalePlayerFaceValue(PFV_HAIR,     ge, GB(face, 16, 4)));
 
	SetPlayerFaceBits(pf, PFV_JACKET,      ge, ScalePlayerFaceValue(PFV_JACKET,   ge, GB(face, 20, 2)));
 
	SetPlayerFaceBits(pf, PFV_COLLAR,      ge, ScalePlayerFaceValue(PFV_COLLAR,   ge, GB(face, 22, 2)));
 
	SetPlayerFaceBits(pf, PFV_GLASSES,     ge, GB(face, 28, 1));
 

	
 
	uint lips = GB(face, 10, 4);
 
	if (!HASBIT(ge, GENDER_FEMALE) && lips < 4) {
 
		SetPlayerFaceBits(pf, PFV_HAS_MOUSTACHE, ge, true);
 
		SetPlayerFaceBits(pf, PFV_MOUSTACHE,     ge, max(lips, 1U) - 1);
 
	} else {
src/rail_gui.cpp
Show inline comments
 
@@ -1100,25 +1100,25 @@ static void ShowStationBuilder()
 
{
 
	Window *w;
 
	if (GetNumStationClasses() <= 2 && GetNumCustomStations(STAT_CLASS_DFLT) == 1) {
 
		w = AllocateWindowDesc(&_station_builder_desc);
 
		_railstation.newstations = false;
 
	} else {
 
		w = AllocateWindowDesc(&_newstation_builder_desc);
 
		_railstation.newstations = true;
 
		_railstation.station_count = GetNumCustomStations(_railstation.station_class);
 

	
 
		w->vscroll.count = _railstation.station_count;
 
		w->vscroll.cap   = 5;
 
		w->vscroll.pos   = clamp(_railstation.station_type - 2, 0, w->vscroll.count - w->vscroll.cap);
 
		w->vscroll.pos   = Clamp(_railstation.station_type - 2, 0, w->vscroll.count - w->vscroll.cap);
 
	}
 
}
 

	
 
/** Enum referring to the widgets of the build rail depot window */
 
enum BuildRailDepotWidgets {
 
	BRDW_CLOSEBOX = 0,
 
	BRDW_CAPTION,
 
	BRDW_BACKGROUND,
 
	BRDW_DEPOT_NE,
 
	BRDW_DEPOT_SE,
 
	BRDW_DEPOT_SW,
 
	BRDW_DEPOT_NW,
src/roadveh_cmd.cpp
Show inline comments
 
@@ -120,25 +120,25 @@ void DrawRoadVehEngine(int x, int y, Eng
 

	
 
static CommandCost EstimateRoadVehCost(EngineID engine_type)
 
{
 
	return CommandCost(((_price.roadveh_base >> 3) * GetEngineProperty(engine_type, 0x11, RoadVehInfo(engine_type)->base_cost)) >> 5);
 
}
 

	
 
byte GetRoadVehLength(const Vehicle *v)
 
{
 
	byte length = 8;
 

	
 
	uint16 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
 
	if (veh_len != CALLBACK_FAILED) {
 
		length -= clamp(veh_len, 0, 7);
 
		length -= Clamp(veh_len, 0, 7);
 
	}
 

	
 
	return length;
 
}
 

	
 
void RoadVehUpdateCache(Vehicle *v)
 
{
 
	assert(v->type == VEH_ROAD);
 
	assert(IsRoadVehFront(v));
 

	
 
	for (Vehicle *u = v; u != NULL; u = u->Next()) {
 
		/* Check the v->first cache. */
src/screenshot.cpp
Show inline comments
 
@@ -114,25 +114,25 @@ static bool MakeBmpImage(const char *nam
 
			rq[i].green = palette[i].g;
 
			rq[i].blue  = palette[i].b;
 
			rq[i].reserved = 0;
 
		}
 
	}
 

	
 
	/* write file header and info header and palette */
 
	if (fwrite(&bfh, sizeof(bfh), 1, f) != 1) return false;
 
	if (fwrite(&bih, sizeof(bih), 1, f) != 1) return false;
 
	if (pixelformat == 8) if (fwrite(rq, sizeof(rq), 1, f) != 1) return false;
 

	
 
	/* use by default 64k temp memory */
 
	maxlines = clamp(65536 / padw, 16, 128);
 
	maxlines = Clamp(65536 / padw, 16, 128);
 

	
 
	/* now generate the bitmap bits */
 
	void *buff = MallocT<uint8>(padw * maxlines * bpp); // by default generate 128 lines at a time.
 
	if (buff == NULL) {
 
		fclose(f);
 
		return false;
 
	}
 
	memset(buff, 0, padw * maxlines); // zero the buffer to have the padding bytes set to 0
 

	
 
	/* start at the bottom, since bitmaps are stored bottom up. */
 
	do {
 
		/* determine # lines */
 
@@ -242,25 +242,25 @@ static bool MakePNGImage(const char *nam
 
		sig_bit.gray  = 8;
 
		png_set_sBIT(png_ptr, info_ptr, &sig_bit);
 

	
 
#ifdef TTD_LITTLE_ENDIAN
 
		png_set_bgr(png_ptr);
 
		png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
 
#else
 
		png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
 
#endif
 
	}
 

	
 
	/* use by default 64k temp memory */
 
	maxlines = clamp(65536 / w, 16, 128);
 
	maxlines = Clamp(65536 / w, 16, 128);
 

	
 
	/* now generate the bitmap bits */
 
	void *buff = MallocT<uint8>(w * maxlines * bpp); // by default generate 128 lines at a time.
 
	if (buff == NULL) {
 
		png_destroy_write_struct(&png_ptr, &info_ptr);
 
		fclose(f);
 
		return false;
 
	}
 
	memset(buff, 0, w * maxlines * bpp);
 

	
 
	y = 0;
 
	do {
 
@@ -342,25 +342,25 @@ static bool MakePCXImage(const char *nam
 
	pcx.planes = 1;
 
	pcx.cpal = TO_LE16(1);
 
	pcx.width = pcx.pitch = TO_LE16(w);
 
	pcx.height = TO_LE16(h);
 

	
 
	/* write pcx header */
 
	if (fwrite(&pcx, sizeof(pcx), 1, f) != 1) {
 
		fclose(f);
 
		return false;
 
	}
 

	
 
	/* use by default 64k temp memory */
 
	maxlines = clamp(65536 / w, 16, 128);
 
	maxlines = Clamp(65536 / w, 16, 128);
 

	
 
	/* now generate the bitmap bits */
 
	uint8 *buff = MallocT<uint8>(w * maxlines); // by default generate 128 lines at a time.
 
	if (buff == NULL) {
 
		fclose(f);
 
		return false;
 
	}
 
	memset(buff, 0, w * maxlines); // zero the buffer to have the padding bytes set to 0
 

	
 
	y = 0;
 
	do {
 
		/* determine # lines to write */
src/settings.cpp
Show inline comments
 
@@ -656,30 +656,30 @@ static void Write_ValidateSetting(void *
 
		 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
 
		 * 32-bit variable
 
		 * TODO: Support 64-bit settings/variables */
 
		switch (GetVarMemType(sd->save.conv)) {
 
			case SLE_VAR_BL:
 
			case SLE_VAR_I8:
 
			case SLE_VAR_U8:
 
			case SLE_VAR_I16:
 
			case SLE_VAR_U16:
 
			case SLE_VAR_I32: {
 
				/* Override the minimum value. No value below sdb->min, except special value 0 */
 
				int32 min = ((sdb->flags & SGF_0ISDISABLED) && val <= sdb->min) ? 0 : sdb->min;
 
				val = clamp(val, min, sdb->max);
 
				val = Clamp(val, min, sdb->max);
 
			} break;
 
			case SLE_VAR_U32: {
 
				/* Override the minimum value. No value below sdb->min, except special value 0 */
 
				uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
 
				WriteValue(ptr, SLE_VAR_U32, (int64)clampu(val, min, sdb->max));
 
				WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
 
				return;
 
			}
 
			case SLE_VAR_I64:
 
			case SLE_VAR_U64:
 
			default: NOT_REACHED(); break;
 
		}
 
	}
 

	
 
	WriteValue(ptr, sd->save.conv, (int64)val);
 
}
 

	
 
/** Load values from a group of an IniFile structure into the internal representation
src/settings_gui.cpp
Show inline comments
 
@@ -420,25 +420,25 @@ void SetDifficultyLevel(int mode, GameOp
 

	
 
/**
 
 * Checks the difficulty levels read from the configuration and
 
 * forces them to be correct when invalid.
 
 */
 
void CheckDifficultyLevels()
 
{
 
	if (_opt_newgame.diff_level != 3) {
 
		SetDifficultyLevel(_opt_newgame.diff_level, &_opt_newgame);
 
	} else {
 
		for (uint i = 0; i < GAME_DIFFICULTY_NUM; i++) {
 
			GDType *diff = ((GDType*)&_opt_newgame.diff) + i;
 
			*diff = clamp(*diff, _game_setting_info[i].min, _game_setting_info[i].max);
 
			*diff = Clamp(*diff, _game_setting_info[i].min, _game_setting_info[i].max);
 
			*diff -= *diff % _game_setting_info[i].step;
 
		}
 
	}
 
}
 

	
 
extern void StartupEconomy();
 

	
 
enum {
 
	GAMEDIFF_WND_TOP_OFFSET = 45,
 
	GAMEDIFF_WND_ROWSIZE    = 9
 
};
 

	
 
@@ -1140,25 +1140,25 @@ static void CustCurrencyWndProc(Window *
 
					str = BindCString(_custom_currency.suffix);
 
					len = 12;
 
					break;
 

	
 
				case 4: // to euro
 
					if (IS_INT_INSIDE(x, 10, 30)) { // clicked buttons
 
						if (x < 20) {
 
							_custom_currency.to_euro = (_custom_currency.to_euro <= 2000) ?
 
								CF_NOEURO : _custom_currency.to_euro - 1;
 
							WP(w,def_d).data_1 = 1 << (line * 2 + 0);
 
						} else {
 
							_custom_currency.to_euro =
 
								clamp(_custom_currency.to_euro + 1, 2000, MAX_YEAR);
 
								Clamp(_custom_currency.to_euro + 1, 2000, MAX_YEAR);
 
							WP(w,def_d).data_1 = 1 << (line * 2 + 1);
 
						}
 
					} else { // enter text
 
						SetDParam(0, _custom_currency.to_euro);
 
						str = STR_CONFIG_PATCHES_INT32;
 
						len = 4;
 
						afilter = CS_NUMERAL;
 
					}
 
					break;
 
			}
 

	
 
			if (len != 0) {
 
@@ -1167,25 +1167,25 @@ static void CustCurrencyWndProc(Window *
 
			}
 

	
 
			w->flags4 |= 5 << WF_TIMEOUT_SHL;
 
			SetWindowDirty(w);
 
			break;
 
		}
 

	
 
		case WE_ON_EDIT_TEXT: {
 
				const char *b = e->we.edittext.str;
 

	
 
				switch (WP(w,def_d).data_2) {
 
					case 0: /* Exchange rate */
 
						_custom_currency.rate = clamp(atoi(b), 1, 5000);
 
						_custom_currency.rate = Clamp(atoi(b), 1, 5000);
 
						break;
 

	
 
					case 1: /* Thousands seperator */
 
						_custom_currency.separator = (b[0] == '\0') ? ' ' : b[0];
 
						ttd_strlcpy(_str_separator, b, lengthof(_str_separator));
 
						break;
 

	
 
					case 2: /* Currency prefix */
 
						ttd_strlcpy(_custom_currency.prefix, b, lengthof(_custom_currency.prefix));
 
						break;
 

	
 
					case 3: /* Currency suffix */
src/sound.cpp
Show inline comments
 
@@ -139,25 +139,25 @@ bool SoundInitialize(const char *filenam
 

	
 
/* Low level sound player */
 
static void StartSound(uint sound, int panning, uint volume)
 
{
 
	MixerChannel *mc;
 
	uint left_vol, right_vol;
 

	
 
	if (volume == 0) return;
 
	mc = MxAllocateChannel();
 
	if (mc == NULL) return;
 
	if (!SetBankSource(mc, sound)) return;
 

	
 
	panning = clamp(panning, -PANNING_LEVELS, PANNING_LEVELS);
 
	panning = Clamp(panning, -PANNING_LEVELS, PANNING_LEVELS);
 
	left_vol = (volume * PANNING_LEVELS) - (volume * panning);
 
	right_vol = (volume * PANNING_LEVELS) + (volume * panning);
 
	MxSetChannelVolume(mc, left_vol * 128 / PANNING_LEVELS, right_vol * 128 / PANNING_LEVELS);
 
	MxActivateChannel(mc);
 
}
 

	
 

	
 
static const byte _vol_factor_by_zoom[] = {255, 190, 134, 87};
 
assert_compile(lengthof(_vol_factor_by_zoom) == ZOOM_LVL_END);
 

	
 
static const byte _sound_base_vol[] = {
 
	128,  90, 128, 128, 128, 128, 128, 128,
src/station_cmd.cpp
Show inline comments
 
@@ -662,25 +662,25 @@ static void UpdateStationAcceptance(Stat
 

	
 
	/* redraw the station view since acceptance changed */
 
	InvalidateWindowWidget(WC_STATION_VIEW, st->index, 4);
 
}
 

	
 
static void UpdateStationSignCoord(Station *st)
 
{
 
	const StationRect *r = &st->rect;
 

	
 
	if (r->IsEmpty()) return; /* no tiles belong to this station */
 

	
 
	/* clamp sign coord to be inside the station rect */
 
	st->xy = TileXY(clampu(TileX(st->xy), r->left, r->right), clampu(TileY(st->xy), r->top, r->bottom));
 
	st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
 
	UpdateStationVirtCoordDirty(st);
 
}
 

	
 
/** This is called right after a station was deleted.
 
 * It checks if the whole station is free of substations, and if so, the station will be
 
 * deleted after a little while.
 
 * @param st Station
 
 */
 
static void DeleteStationIfEmpty(Station *st)
 
{
 
	if (st->facilities == 0) {
 
		st->delete_ctr = 0;
 
@@ -2478,25 +2478,25 @@ static void UpdateStationRating(Station 
 
			uint waiting = ge->cargo.Count();
 
			(rating -= 90, waiting > 1500) ||
 
			(rating += 55, waiting > 1000) ||
 
			(rating += 35, waiting > 600) ||
 
			(rating += 10, waiting > 300) ||
 
			(rating += 20, waiting > 100) ||
 
			(rating += 10, true);
 

	
 
			{
 
				int or_ = ge->rating; // old rating
 

	
 
				/* only modify rating in steps of -2, -1, 0, 1 or 2 */
 
				ge->rating = rating = or_ + clamp(clamp(rating, 0, 255) - or_, -2, 2);
 
				ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
 

	
 
				/* if rating is <= 64 and more than 200 items waiting,
 
				 * remove some random amount of goods from the station */
 
				if (rating <= 64 && waiting >= 200) {
 
					int dec = Random() & 0x1F;
 
					if (waiting < 400) dec &= 7;
 
					waiting -= dec + 1;
 
					waiting_changed = true;
 
				}
 

	
 
				/* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
 
				if (rating <= 127 && waiting != 0) {
 
@@ -2568,25 +2568,25 @@ void StationMonthlyLoop()
 

	
 
void ModifyStationRatingAround(TileIndex tile, PlayerID owner, int amount, uint radius)
 
{
 
	Station *st;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->owner == owner &&
 
				DistanceManhattan(tile, st->xy) <= radius) {
 
			for (CargoID i = 0; i < NUM_CARGO; i++) {
 
				GoodsEntry* ge = &st->goods[i];
 

	
 
				if (ge->acceptance_pickup != 0) {
 
					ge->rating = clamp(ge->rating + amount, 0, 255);
 
					ge->rating = Clamp(ge->rating + amount, 0, 255);
 
				}
 
			}
 
		}
 
	}
 
}
 

	
 
static void UpdateStationWaiting(Station *st, CargoID type, uint amount)
 
{
 
	st->goods[type].cargo.Append(new CargoPacket(st->index, amount));
 
	SETBIT(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);
 

	
 
	InvalidateWindow(WC_STATION_VIEW, st->index);
src/town_map.h
Show inline comments
 
@@ -274,25 +274,25 @@ static inline byte GetHouseConstructionT
 
 * @param t the tile of the house to increment the construction stage of
 
 * @pre IsTileType(t, MP_HOUSE)
 
 */
 
static inline void IncHouseConstructionTick(TileIndex t)
 
{
 
	assert(IsTileType(t, MP_HOUSE));
 
	AB(_m[t].m5, 0, 5, 1);
 

	
 
	if (GB(_m[t].m5, 3, 2) == TOWN_HOUSE_COMPLETED) {
 
		/* House is now completed.
 
		 * Store the year of construction as well, for newgrf house purpose */
 
		SetHouseCompleted(t, true);
 
		_m[t].m5 = clamp(_cur_year - ORIGINAL_BASE_YEAR, 0, 0xFF);
 
		_m[t].m5 = Clamp(_cur_year - ORIGINAL_BASE_YEAR, 0, 0xFF);
 
	}
 
}
 

	
 
/**
 
 * Get the year that this house was constructed (between 1920 and 2175).
 
 * @param t the tile of this house
 
 * @pre IsTileType(t, MP_HOUSE)
 
 * @return year
 
 */
 
static inline Year GetHouseConstructionYear(TileIndex t)
 
{
 
	assert(IsTileType(t, MP_HOUSE));
src/train_cmd.cpp
Show inline comments
 
@@ -235,25 +235,25 @@ void TrainConsistChanged(Vehicle* v)
 
			/* Set cargo capacity if we've not been refitted */
 
			u->cargo_cap = GetVehicleProperty(u, 0x14, rvi_u->capacity);
 
		}
 

	
 
		u->u.rail.user_def_data = GetVehicleProperty(u, 0x25, rvi_u->user_def_data);
 

	
 
		/* check the vehicle length (callback) */
 
		uint16 veh_len = CALLBACK_FAILED;
 
		if (HASBIT(EngInfo(u->engine_type)->callbackmask, CBM_VEHICLE_LENGTH)) {
 
			veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
 
		}
 
		if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
 
		veh_len = clamp(veh_len, 0, u->Next() == NULL ? 7 : 5); // the clamp on vehicles not the last in chain is stricter, as too short wagons can break the 'follow next vehicle' code
 
		veh_len = Clamp(veh_len, 0, u->Next() == NULL ? 7 : 5); // the clamp on vehicles not the last in chain is stricter, as too short wagons can break the 'follow next vehicle' code
 
		u->u.rail.cached_veh_length = 8 - veh_len;
 
		v->u.rail.cached_total_length += u->u.rail.cached_veh_length;
 
	}
 

	
 
	/* store consist weight/max speed in cache */
 
	v->u.rail.cached_max_speed = max_speed;
 

	
 
	/* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
 
	TrainCargoChanged(v);
 
}
 

	
 
/* These two arrays are used for realistic acceleration. XXX: How should they
 
@@ -343,25 +343,25 @@ static int GetTrainAcceleration(Vehicle 
 
			max_speed = 61;
 
		}
 
	}
 

	
 
	if (numcurve > 0) sum /= numcurve;
 

	
 
	if ((curvecount[0] != 0 || curvecount[1] != 0) && max_speed > 88) {
 
		int total = curvecount[0] + curvecount[1];
 

	
 
		if (curvecount[0] == 1 && curvecount[1] == 1) {
 
			max_speed = 0xFFFF;
 
		} else if (total > 1) {
 
			max_speed = 232 - (13 - clamp(sum, 1, 12)) * (13 - clamp(sum, 1, 12));
 
			max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
 
		}
 
	}
 

	
 
	max_speed += (max_speed / 2) * v->u.rail.railtype;
 

	
 
	if (IsTileType(v->tile, MP_STATION) && IsFrontEngine(v)) {
 
		if (TrainShouldStop(v, v->tile)) {
 
			int station_length = GetStationByTile(v->tile)->GetPlatformLength(v->tile, DirToDiagDir(v->direction));
 
			int delta_v;
 

	
 
			max_speed = 120;
 

	
 
@@ -446,25 +446,25 @@ static int GetTrainAcceleration(Vehicle 
 
	}
 
}
 

	
 
static void UpdateTrainAcceleration(Vehicle* v)
 
{
 
	assert(IsFrontEngine(v));
 

	
 
	v->max_speed = v->u.rail.cached_max_speed;
 

	
 
	uint power = v->u.rail.cached_power;
 
	uint weight = v->u.rail.cached_weight;
 
	assert(weight != 0);
 
	v->acceleration = clamp(power / weight * 4, 1, 255);
 
	v->acceleration = Clamp(power / weight * 4, 1, 255);
 
}
 

	
 
int Train::GetImage(Direction direction) const
 
{
 
	int img = this->spritenum;
 
	int base;
 

	
 
	if (HASBIT(this->u.rail.flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
 

	
 
	if (is_custom_sprite(img)) {
 
		base = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(img)));
 
		if (base != 0) return base;
 
@@ -2504,25 +2504,25 @@ static int UpdateTrainSpeed(Vehicle *v)
 
			accel = GetTrainAcceleration(v, AM_ACCEL);
 
		} else {
 
			accel = v->acceleration;
 
		}
 
	}
 

	
 
	uint spd = v->subspeed + accel * 2;
 
	v->subspeed = (byte)spd;
 
	{
 
		int tempmax = v->max_speed;
 
		if (v->cur_speed > v->max_speed)
 
			tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
 
		v->cur_speed = spd = clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
 
		v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
 
	}
 

	
 
	if (!(v->direction & 1)) spd = spd * 3 >> 2;
 

	
 
	spd += v->progress;
 
	v->progress = (byte)spd;
 
	return (spd >> 8);
 
}
 

	
 
static void TrainEnterStation(Vehicle *v, StationID station)
 
{
 
	v->last_station_visited = station;
src/vehicle.cpp
Show inline comments
 
@@ -1343,26 +1343,26 @@ Vehicle *CreateEffectVehicle(int x, int 
 

	
 
		_effect_init_procs[type](v);
 

	
 
		VehiclePositionChanged(v);
 
		BeginVehicleMove(v);
 
		EndVehicleMove(v);
 
	}
 
	return v;
 
}
 

	
 
Vehicle *CreateEffectVehicleAbove(int x, int y, int z, EffectVehicle type)
 
{
 
	int safe_x = clamp(x, 0, MapMaxX() * TILE_SIZE);
 
	int safe_y = clamp(y, 0, MapMaxY() * TILE_SIZE);
 
	int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
 
	int safe_y = Clamp(y, 0, MapMaxY() * TILE_SIZE);
 
	return CreateEffectVehicle(x, y, GetSlopeZ(safe_x, safe_y) + z, type);
 
}
 

	
 
Vehicle *CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicle type)
 
{
 
	return CreateEffectVehicle(v->x_pos + x, v->y_pos + y, v->z_pos + z, type);
 
}
 

	
 
void SpecialVehicle::Tick()
 
{
 
	_effect_tick_procs[this->subtype](this);
 
}
src/video/cocoa_v.mm
Show inline comments
 
@@ -1235,25 +1235,25 @@ static const char* QZ_SetVideoWindowed(u
 
		[ _cocoa_video_data.window setMiniwindowTitle:nsscaption ];
 
		[ nsscaption release ];
 

	
 
		[ _cocoa_video_data.window setAcceptsMouseMovedEvents:YES ];
 
		[ _cocoa_video_data.window setViewsNeedDisplay:NO ];
 

	
 
		[ _cocoa_video_data.window setDelegate: [ [ [ OTTD_QuartzWindowDelegate alloc ] init ] autorelease ] ];
 
	} else {
 
		/* We already have a window, just change its size */
 
		if (!isCustom) {
 
			[ _cocoa_video_data.window setContentSize:contentRect.size ];
 
			// Ensure frame height - title bar height >= view height
 
			contentRect.size.height = clamp(height, 0, [ _cocoa_video_data.window frame ].size.height - 22 /* 22 is the height of title bar of window*/);
 
			contentRect.size.height = Clamp(height, 0, [ _cocoa_video_data.window frame ].size.height - 22 /* 22 is the height of title bar of window*/);
 
			height = contentRect.size.height;
 
			[ _cocoa_video_data.qdview setFrameSize:contentRect.size ];
 
		}
 
	}
 

	
 
	// Update again
 
	_cocoa_video_data.width = width;
 
	_cocoa_video_data.height = height;
 

	
 
	[ _cocoa_video_data.window center ];
 

	
 
	/* Only recreate the view if it doesn't already exist */
src/video/sdl_v.cpp
Show inline comments
 
@@ -411,26 +411,26 @@ static int PollEvent()
 
		case SDL_QUIT: HandleExitGameRequest(); break;
 

	
 
		case SDL_KEYDOWN: /* Toggle full-screen on ALT + ENTER/F */
 
			if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
 
					(ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
 
				ToggleFullScreen(!_fullscreen);
 
			} else {
 
				HandleKeypress(ConvertSdlKeyIntoMy(&ev.key.keysym));
 
			}
 
			break;
 

	
 
		case SDL_VIDEORESIZE: {
 
			int w = clamp(ev.resize.w, 64, MAX_SCREEN_WIDTH);
 
			int h = clamp(ev.resize.h, 64, MAX_SCREEN_HEIGHT);
 
			int w = Clamp(ev.resize.w, 64, MAX_SCREEN_WIDTH);
 
			int h = Clamp(ev.resize.h, 64, MAX_SCREEN_HEIGHT);
 
			ChangeResInGame(w, h);
 
			break;
 
		}
 
	}
 
	return -1;
 
}
 

	
 
const char *VideoDriver_SDL::Start(const char * const *parm)
 
{
 
	char buf[30];
 

	
 
	const char *s = SdlOpen(SDL_INIT_VIDEO);
src/video/win32_v.cpp
Show inline comments
 
@@ -536,26 +536,26 @@ static LRESULT CALLBACK WndProcGdi(HWND 
 

	
 
#if !defined(WINCE)
 
		case WM_SIZING: {
 
			RECT* r = (RECT*)lParam;
 
			RECT r2;
 
			int w, h;
 

	
 
			SetRect(&r2, 0, 0, 0, 0);
 
			AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
 

	
 
			w = r->right - r->left - (r2.right - r2.left);
 
			h = r->bottom - r->top - (r2.bottom - r2.top);
 
			w = clamp(w, 64, MAX_SCREEN_WIDTH);
 
			h = clamp(h, 64, MAX_SCREEN_HEIGHT);
 
			w = Clamp(w, 64, MAX_SCREEN_WIDTH);
 
			h = Clamp(h, 64, MAX_SCREEN_HEIGHT);
 
			SetRect(&r2, 0, 0, w, h);
 

	
 
			AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
 
			w = r2.right - r2.left;
 
			h = r2.bottom - r2.top;
 

	
 
			switch (wParam) {
 
				case WMSZ_BOTTOM:
 
					r->bottom = r->top + h;
 
					break;
 

	
 
				case WMSZ_BOTTOMLEFT:
 
@@ -668,26 +668,26 @@ static void RegisterWndClass()
 

	
 
		registered = true;
 
		if (!RegisterClass(&wnd)) error("RegisterClass failed");
 
	}
 
}
 

	
 
static bool AllocateDibSection(int w, int h)
 
{
 
	BITMAPINFO *bi;
 
	HDC dc;
 
	int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
 

	
 
	w = clamp(w, 64, MAX_SCREEN_WIDTH);
 
	h = clamp(h, 64, MAX_SCREEN_HEIGHT);
 
	w = Clamp(w, 64, MAX_SCREEN_WIDTH);
 
	h = Clamp(h, 64, MAX_SCREEN_HEIGHT);
 

	
 
	if (bpp == 0) error("Can't use a blitter that blits 0 bpp for normal visuals");
 

	
 
	if (w == _screen.width && h == _screen.height)
 
		return false;
 

	
 
	_screen.width = w;
 
	_screen.pitch = (bpp == 8) ? ALIGN(w, 4) : w;
 
	_screen.height = h;
 
	bi = (BITMAPINFO*)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
 
	memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
 
	bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
src/viewport.cpp
Show inline comments
 
@@ -363,26 +363,26 @@ static Point TranslateXYToTileCoord(cons
 
				return pt;
 
	}
 

	
 
	x = (ScaleByZoom(x, vp->zoom) + vp->virtual_left) >> 2;
 
	y = (ScaleByZoom(y, vp->zoom) + vp->virtual_top) >> 1;
 

	
 
	a = y-x;
 
	b = y+x;
 

	
 
	/* we need to move variables in to the valid range, as the
 
	 * GetTileZoomCenterWindow() function can call here with invalid x and/or y,
 
	 * when the user tries to zoom out along the sides of the map */
 
	a = clamp(a, 0, (int)(MapMaxX() * TILE_SIZE) - 1);
 
	b = clamp(b, 0, (int)(MapMaxY() * TILE_SIZE) - 1);
 
	a = Clamp(a, 0, (int)(MapMaxX() * TILE_SIZE) - 1);
 
	b = Clamp(b, 0, (int)(MapMaxY() * TILE_SIZE) - 1);
 

	
 
	/* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
 
	 * Now find the Z-world coordinate by fix point iteration.
 
	 * This is a bit tricky because the tile height is non-continuous at foundations.
 
	 * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
 
	 * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
 
	 * So give it a z-malus of 4 in the first iterations.
 
	 */
 
	z = 0;
 
	for (int i = 0; i < 5; i++) z = GetSlopeZ(a + max(z, 4u) - 4, b + max(z, 4u) - 4) / 2;
 
	for (uint malus = 3; malus > 0; malus--) z = GetSlopeZ(a + max(z, malus) - malus, b + max(z, malus) - malus) / 2;
 
	for (int i = 0; i < 5; i++) z = GetSlopeZ(a + z, b + z) / 2;
 
@@ -1640,26 +1640,26 @@ void DrawWindowViewport(const Window *w)
 
static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
 
{
 
	/* Centre of the viewport is hot spot */
 
	x += vp->virtual_width / 2;
 
	y += vp->virtual_height / 2;
 

	
 
	/* Convert viewport coordinates to map coordinates
 
	 * Calculation is scaled by 4 to avoid rounding errors */
 
	int vx = -x + y * 2;
 
	int vy =  x + y * 2;
 

	
 
	/* clamp to size of map */
 
	vx = clamp(vx, 0, MapMaxX() * TILE_SIZE * 4);
 
	vy = clamp(vy, 0, MapMaxY() * TILE_SIZE * 4);
 
	vx = Clamp(vx, 0, MapMaxX() * TILE_SIZE * 4);
 
	vy = Clamp(vy, 0, MapMaxY() * TILE_SIZE * 4);
 

	
 
	/* Convert map coordinates to viewport coordinates */
 
	x = (-vx + vy) / 2;
 
	y = ( vx + vy) / 4;
 

	
 
	/* Remove centreing */
 
	x -= vp->virtual_width / 2;
 
	y -= vp->virtual_height / 2;
 
}
 

	
 
void UpdateViewportPosition(Window *w)
 
{
 
@@ -1672,26 +1672,26 @@ void UpdateViewportPosition(Window *w)
 
		SetViewportPosition(w, pt.x, pt.y);
 
	} else {
 
		/* Ensure the destination location is within the map */
 
		ClampViewportToMap(vp, WP(w, vp_d).dest_scrollpos_x, WP(w, vp_d).dest_scrollpos_y);
 

	
 
		int delta_x = WP(w, vp_d).dest_scrollpos_x - WP(w, vp_d).scrollpos_x;
 
		int delta_y = WP(w, vp_d).dest_scrollpos_y - WP(w, vp_d).scrollpos_y;
 

	
 
		if (delta_x != 0 || delta_y != 0) {
 
			if (_patches.smooth_scroll) {
 
				int max_scroll = ScaleByMapSize1D(512);
 
				/* Not at our desired positon yet... */
 
				WP(w, vp_d).scrollpos_x += clamp(delta_x / 4, -max_scroll, max_scroll);
 
				WP(w, vp_d).scrollpos_y += clamp(delta_y / 4, -max_scroll, max_scroll);
 
				WP(w, vp_d).scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
 
				WP(w, vp_d).scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
 
			} else {
 
				WP(w, vp_d).scrollpos_x = WP(w, vp_d).dest_scrollpos_x;
 
				WP(w, vp_d).scrollpos_y = WP(w, vp_d).dest_scrollpos_y;
 
			}
 
		}
 

	
 
		ClampViewportToMap(vp, WP(w, vp_d).scrollpos_x, WP(w, vp_d).scrollpos_y);
 
		SetViewportPosition(w, WP(w, vp_d).scrollpos_x, WP(w, vp_d).scrollpos_y);
 
	}
 
}
 

	
 
/**
 
@@ -2710,26 +2710,26 @@ calc_heightdiff_single_direction:;
 
					 * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
 
					int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
 

	
 
					params[index++] = distance;
 
					if (heightdiff != 0) params[index++] = heightdiff;
 
				}
 

	
 
				GuiShowTooltipsWithArgs(measure_strings_length[index], index, params);
 
			} break;
 

	
 
		case VPM_X_AND_Y_LIMITED: { /* drag an X by Y constrained rect area */
 
			int limit = (_thd.sizelimit - 1) * TILE_SIZE;
 
			x = sx + clamp(x - sx, -limit, limit);
 
			y = sy + clamp(y - sy, -limit, limit);
 
			x = sx + Clamp(x - sx, -limit, limit);
 
			y = sy + Clamp(y - sy, -limit, limit);
 
			} /* Fallthrough */
 
		case VPM_X_AND_Y: { /* drag an X by Y area */
 
			if (_patches.measure_tooltip) {
 
				static const StringID measure_strings_area[] = {
 
					STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
 
				};
 

	
 
				TileIndex t0 = TileVirtXY(sx, sy);
 
				TileIndex t1 = TileVirtXY(x, y);
 
				uint dx = delta(TileX(t0), TileX(t1)) + 1;
 
				uint dy = delta(TileY(t0), TileY(t1)) + 1;
 
				byte index = 0;
src/window.cpp
Show inline comments
 
@@ -187,25 +187,25 @@ static void DispatchMouseWheelEvent(Wind
 

	
 
	wi1 = &w->widget[widget];
 
	wi2 = &w->widget[widget + 1];
 

	
 
	/* The listbox can only scroll if scrolling was done on the scrollbar itself,
 
	 * or on the listbox (and the next item is (must be) the scrollbar)
 
	 * XXX - should be rewritten as a widget-dependent scroller but that's
 
	 * not happening until someone rewrites the whole widget-code */
 
	if ((sb = &w->vscroll,  wi1->type == WWT_SCROLLBAR)  || (sb = &w->vscroll2, wi1->type == WWT_SCROLL2BAR)  ||
 
			(sb = &w->vscroll2, wi2->type == WWT_SCROLL2BAR) || (sb = &w->vscroll, wi2->type == WWT_SCROLLBAR) ) {
 

	
 
		if (sb->count > sb->cap) {
 
			int pos = clamp(sb->pos + wheel, 0, sb->count - sb->cap);
 
			int pos = Clamp(sb->pos + wheel, 0, sb->count - sb->cap);
 
			if (pos != sb->pos) {
 
				sb->pos = pos;
 
				SetWindowDirty(w);
 
			}
 
		}
 
	}
 
}
 

	
 
static void DrawOverlappedWindow(Window* const *wz, int left, int top, int right, int bottom);
 

	
 
void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
 
{
 
@@ -1286,26 +1286,26 @@ static bool HandleWindowDragging()
 
						/* Your bottom border <-> other bottom border */
 
						delta = abs(v->top + v->height - y - w->height);
 
						if (delta <= vsnap) {
 
							ny = v->top + v->height - w->height;
 
							vsnap = delta;
 
						}
 
					}
 
				}
 
			}
 

	
 
			/* Make sure the window doesn't leave the screen
 
			 * 13 is the height of the title bar */
 
			nx = clamp(nx, 13 - t->right, _screen.width - 13 - t->left);
 
			ny = clamp(ny, 0, _screen.height - 13);
 
			nx = Clamp(nx, 13 - t->right, _screen.width - 13 - t->left);
 
			ny = Clamp(ny, 0, _screen.height - 13);
 

	
 
			/* Make sure the title bar isn't hidden by behind the main tool bar */
 
			v = FindWindowById(WC_MAIN_TOOLBAR, 0);
 
			if (v != NULL) {
 
				int v_bottom = v->top + v->height;
 
				int v_right = v->left + v->width;
 
				if (ny + t->top >= v->top && ny + t->top < v_bottom) {
 
					if ((v->left < 13 && nx + t->left < v->left) ||
 
							(v_right > _screen.width - 13 && nx + t->right > v_right)) {
 
						ny = v_bottom;
 
					} else {
 
						if (nx + t->left > v->left - 13 &&
 
@@ -2104,31 +2104,31 @@ void RelocateAllWindows(int neww, int ne
 
			case WC_GAME_OPTIONS:
 
			case WC_NETWORK_WINDOW:
 
				top = (newh - w->height) >> 1;
 
				left = (neww - w->width) >> 1;
 
				break;
 

	
 
			case WC_NEWS_WINDOW:
 
				top = newh - w->height;
 
				left = (neww - w->width) >> 1;
 
				break;
 

	
 
			case WC_STATUS_BAR:
 
				ResizeWindow(w, clamp(neww, 320, 640) - w->width, 0);
 
				ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
 
				top = newh - w->height;
 
				left = (neww - w->width) >> 1;
 
				break;
 

	
 
			case WC_SEND_NETWORK_MSG:
 
				ResizeWindow(w, clamp(neww, 320, 640) - w->width, 0);
 
				ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0);
 
				top = (newh - 26); // 26 = height of status bar + height of chat bar
 
				left = (neww - w->width) >> 1;
 
				break;
 

	
 
			case WC_CONSOLE:
 
				IConsoleResize(w);
 
				continue;
 

	
 
			default:
 
				left = w->left;
 
				if (left + (w->width >> 1) >= neww) left = neww - w->width;
 
				top = w->top;
0 comments (0 inline, 0 general)