Changeset - r24597:afde5721a3b6
[Not reviewed]
master
! ! !
Charles Pigott - 4 years ago 2021-01-08 10:16:18
charlespigott@googlemail.com
Codechange: Remove min/max functions in favour of STL variants (#8502)
101 files changed:
Changeset was too big and was cut off... Show full diff anyway
0 comments (0 inline, 0 general)
src/3rdparty/squirrel/squirrel/sqbaselib.cpp
Show inline comments
 
/*
 
 * see copyright notice in squirrel.h
 
 */
 
/*
 
 * Needs to be first due to a squirrel header defining type() and type()
 
 * being used in some versions of the headers included by algorithm.
 
 */
 

	
 
#include "../../../stdafx.h"
 

	
 
#include <algorithm>
 
#include "sqpcheader.h"
 
#include "sqvm.h"
 
#include "sqstring.h"
 
#include "sqtable.h"
 
#include "sqarray.h"
 
#include "sqfuncproto.h"
src/ai/ai_config.cpp
Show inline comments
 
@@ -36,13 +36,13 @@ ScriptConfigItem _start_date_config = {
 
AIConfig::AIConfig(const AIConfig *config) : ScriptConfig(config)
 
{
 
	/* Override start_date as per AIConfig::AddRandomDeviation().
 
	 * This is necessary because the ScriptConfig constructor will instead call
 
	 * ScriptConfig::AddRandomDeviation(). */
 
	int start_date = config->GetSetting("start_date");
 
	this->SetSetting("start_date", start_date != 0 ? max(1, this->GetSetting("start_date")) : 0);
 
	this->SetSetting("start_date", start_date != 0 ? std::max(1, this->GetSetting("start_date")) : 0);
 
}
 

	
 
/* static */ AIConfig *AIConfig::GetConfig(CompanyID company, ScriptSettingSource source)
 
{
 
	AIConfig **config;
 
	if (source == SSS_FORCE_NEWGAME || (source == SSS_DEFAULT && _game_mode == GM_MENU)) {
 
@@ -131,8 +131,8 @@ void AIConfig::AddRandomDeviation()
 
	int start_date = this->GetSetting("start_date");
 

	
 
	ScriptConfig::AddRandomDeviation();
 

	
 
	/* start_date = 0 is a special case, where random deviation does not occur.
 
	 * If start_date was not already 0, then a minimum value of 1 must apply. */
 
	this->SetSetting("start_date", start_date != 0 ? max(1, this->GetSetting("start_date")) : 0);
 
	this->SetSetting("start_date", start_date != 0 ? std::max(1, this->GetSetting("start_date")) : 0);
 
}
src/ai/ai_gui.cpp
Show inline comments
 
@@ -233,13 +233,13 @@ struct AIListWindow : public Window {
 

	
 
		if (!gui_scope) return;
 

	
 
		this->vscroll->SetCount((int)this->info_list->size() + 1);
 

	
 
		/* selected goes from -1 .. length of ai list - 1. */
 
		this->selected = min(this->selected, this->vscroll->GetCount() - 2);
 
		this->selected = std::min(this->selected, this->vscroll->GetCount() - 2);
 
	}
 
};
 

	
 
/** Widgets for the AI list window. */
 
static const NWidgetPart _nested_ai_list_widgets[] = {
 
	NWidget(NWID_HORIZONTAL),
 
@@ -346,13 +346,13 @@ struct AISettingsWindow : public Window 
 
		this->vscroll->SetCount((int)this->visible_settings.size());
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		if (widget == WID_AIS_BACKGROUND) {
 
			this->line_height = max(SETTING_BUTTON_HEIGHT, FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 
			this->line_height = std::max(SETTING_BUTTON_HEIGHT, FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 

	
 
			resize->width = 1;
 
			resize->height = this->line_height;
 
			size->height = 5 * this->line_height;
 
		}
 
	}
 
@@ -876,15 +876,15 @@ struct AIConfigWindow : public Window {
 

	
 
		switch (widget) {
 
			case WID_AIC_DECREASE:
 
			case WID_AIC_INCREASE: {
 
				int new_value;
 
				if (widget == WID_AIC_DECREASE) {
 
					new_value = max(0, GetGameSettings().difficulty.max_no_competitors - 1);
 
					new_value = std::max(0, GetGameSettings().difficulty.max_no_competitors - 1);
 
				} else {
 
					new_value = min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1);
 
					new_value = std::min(MAX_COMPANIES - 1, GetGameSettings().difficulty.max_no_competitors + 1);
 
				}
 
				IConsoleSetSetting("difficulty.max_no_competitors", new_value);
 
				break;
 
			}
 

	
 
			case WID_AIC_GAMELIST: {
 
@@ -1173,13 +1173,13 @@ struct AIDebugWindow : public Window {
 
		/* Detect when the user scrolls the window. Enable autoscroll when the
 
		 * bottom-most line becomes visible. */
 
		if (this->last_vscroll_pos != this->vscroll->GetPosition()) {
 
			this->autoscroll = this->vscroll->GetPosition() >= log->used - this->vscroll->GetCapacity();
 
		}
 
		if (this->autoscroll) {
 
			int scroll_pos = max(0, log->used - this->vscroll->GetCapacity());
 
			int scroll_pos = std::max(0, log->used - this->vscroll->GetCapacity());
 
			if (scroll_pos != this->vscroll->GetPosition()) {
 
				this->vscroll->SetPosition(scroll_pos);
 

	
 
				/* We need a repaint */
 
				this->SetWidgetDirty(WID_AID_SCROLLBAR);
 
				this->SetWidgetDirty(WID_AID_LOG_PANEL);
src/aircraft_cmd.cpp
Show inline comments
 
@@ -649,13 +649,13 @@ static int UpdateAircraftSpeed(Aircraft 
 
	 * and take-off speeds being too low. */
 
	speed_limit *= _settings_game.vehicle.plane_speed;
 

	
 
	/* adjust speed for broken vehicles */
 
	if (v->vehstatus & VS_AIRCRAFT_BROKEN) {
 
		if (SPEED_LIMIT_BROKEN < speed_limit) hard_limit = false;
 
		speed_limit = min(speed_limit, SPEED_LIMIT_BROKEN);
 
		speed_limit = std::min<uint>(speed_limit, SPEED_LIMIT_BROKEN);
 
	}
 

	
 
	if (v->vcache.cached_max_speed < speed_limit) {
 
		if (v->cur_speed < speed_limit) hard_limit = false;
 
		speed_limit = v->vcache.cached_max_speed;
 
	}
 
@@ -666,16 +666,16 @@ static int UpdateAircraftSpeed(Aircraft 
 
	 * forced to slow down rapidly in the short distance needed. The magic
 
	 * value 16384 was determined to give similar results to the old speed/48
 
	 * method at slower speeds. This also results in less reduction at slow
 
	 * speeds to that aircraft do not get to taxi speed straight after
 
	 * touchdown. */
 
	if (!hard_limit && v->cur_speed > speed_limit) {
 
		speed_limit = v->cur_speed - max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
 
		speed_limit = v->cur_speed - std::max(1, ((v->cur_speed * v->cur_speed) / 16384) / _settings_game.vehicle.plane_speed);
 
	}
 

	
 
	spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
 
	spd = std::min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
 

	
 
	/* updates statusbar only if speed have changed to save CPU time */
 
	if (spd != v->cur_speed) {
 
		v->cur_speed = spd;
 
		SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
 
	}
 
@@ -734,13 +734,13 @@ void GetAircraftFlightLevelBounds(const 
 
			break;
 

	
 
		default: break;
 
	}
 

	
 
	/* Make faster planes fly higher so that they can overtake slower ones */
 
	base_altitude += min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
 
	base_altitude += std::min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
 

	
 
	if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
 
	if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
 
}
 

	
 
/**
 
@@ -926,13 +926,13 @@ static bool AircraftController(Aircraft 
 

	
 
				/* Reached altitude? */
 
				if (v->z_pos >= z_dest) {
 
					v->cur_speed = 0;
 
					return true;
 
				}
 
				SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z_dest));
 
				SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z_dest));
 
			}
 
		}
 
		return false;
 
	}
 

	
 
	/* Helicopter landing. */
 
@@ -972,15 +972,15 @@ static bool AircraftController(Aircraft 
 
			}
 
			u->cur_speed += 4;
 
		} else {
 
			count = UpdateAircraftSpeed(v);
 
			if (count > 0) {
 
				if (v->z_pos > z) {
 
					SetAircraftPosition(v, v->x_pos, v->y_pos, max(v->z_pos - count, z));
 
					SetAircraftPosition(v, v->x_pos, v->y_pos, std::max(v->z_pos - count, z));
 
				} else {
 
					SetAircraftPosition(v, v->x_pos, v->y_pos, min(v->z_pos + count, z));
 
					SetAircraftPosition(v, v->x_pos, v->y_pos, std::min(v->z_pos + count, z));
 
				}
 
			}
 
		}
 
		return false;
 
	}
 

	
 
@@ -1122,13 +1122,13 @@ static bool AircraftController(Aircraft 
 
				SetAircraftPosition(v, gp.x, gp.y, GetAircraftFlightLevel(v));
 
				continue;
 
			}
 

	
 
			/* We're not flying below our destination, right? */
 
			assert(airport_z <= z);
 
			int t = max(1U, dist - 4);
 
			int t = std::max(1U, dist - 4);
 
			int delta = z - airport_z;
 

	
 
			/* Only start lowering when we're sufficiently close for a 1:1 glide */
 
			if (delta >= t) {
 
				z -= CeilDiv(z - airport_z, t);
 
			}
src/airport_gui.cpp
Show inline comments
 
@@ -311,13 +311,13 @@ public:
 

	
 
			case WID_AP_AIRPORT_LIST: {
 
				for (int i = 0; i < NUM_AIRPORTS; i++) {
 
					const AirportSpec *as = AirportSpec::Get(i);
 
					if (!as->enabled) continue;
 

	
 
					size->width = max(size->width, GetStringBoundingBox(as->name).width);
 
					size->width = std::max(size->width, GetStringBoundingBox(as->name).width);
 
				}
 

	
 
				this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 
				size->height = 5 * this->line_height;
 
				break;
 
			}
src/autoreplace_cmd.cpp
Show inline comments
 
@@ -112,13 +112,13 @@ void CheckCargoCapacity(Vehicle *v)
 
		/* We need to move a particular amount. Try that on the other vehicles. */
 
		uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
 
		for (Vehicle *dest = v; dest != nullptr && to_spread != 0; dest = dest->Next()) {
 
			assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
 
			if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
 

	
 
			uint amount = min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
 
			uint amount = std::min(to_spread, dest->cargo_cap - dest->cargo.TotalCount());
 
			src->cargo.Shift(amount, &dest->cargo);
 
			to_spread -= amount;
 
		}
 

	
 
		/* Any left-overs will be thrown away, but not their feeder share. */
 
		if (src->cargo_cap < src->cargo.TotalCount()) src->cargo.Truncate(src->cargo.TotalCount() - src->cargo_cap);
 
@@ -154,13 +154,13 @@ static void TransferCargo(Vehicle *old_v
 
				/* Skip vehicles, which do not belong to new_head */
 
				dest = dest->GetLastEnginePart();
 
				continue;
 
			}
 
			if (dest->cargo_type != src->cargo_type) continue;
 

	
 
			uint amount = min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
 
			uint amount = std::min(src->cargo.TotalCount(), dest->cargo_cap - dest->cargo.TotalCount());
 
			if (amount <= 0) continue;
 

	
 
			src->cargo.Shift(amount, &dest->cargo);
 
		}
 
	}
 

	
src/autoreplace_gui.cpp
Show inline comments
 
@@ -413,14 +413,14 @@ public:
 
				break;
 
			}
 

	
 
			case WID_RV_LEFT_MATRIX:
 
			case WID_RV_RIGHT_MATRIX: {
 
				int side = (widget == WID_RV_LEFT_MATRIX) ? 0 : 1;
 
				EngineID start  = this->vscroll[side]->GetPosition(); // what is the offset for the start (scrolling)
 
				EngineID end    = min(this->vscroll[side]->GetCapacity() + start, (uint)this->engines[side].size());
 
				EngineID start  = static_cast<EngineID>(this->vscroll[side]->GetPosition()); // what is the offset for the start (scrolling)
 
				EngineID end    = static_cast<EngineID>(std::min<size_t>(this->vscroll[side]->GetCapacity() + start, this->engines[side].size()));
 

	
 
				/* Do the actual drawing */
 
				DrawEngineList((VehicleType)this->window_number, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP,
 
						&this->engines[side], start, end, this->sel_engine[side], side == 0, this->sel_group);
 
				break;
 
			}
 
@@ -472,13 +472,13 @@ public:
 
					ted.cargo = e->GetDefaultCargoType();
 
					ted.capacity = e->GetDisplayDefaultCapacity(&ted.mail_capacity);
 

	
 
					NWidgetBase *nwi = this->GetWidget<NWidgetBase>(side == 0 ? WID_RV_LEFT_DETAILS : WID_RV_RIGHT_DETAILS);
 
					int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT,
 
							nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine[side], ted);
 
					needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
 
					needed_height = std::max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
 
				}
 
			}
 
			if (needed_height != this->details_height) { // Details window are not high enough, enlarge them.
 
				this->details_height = needed_height;
 
				this->ReInit();
 
				return;
src/blitter/32bpp_anim.cpp
Show inline comments
 
@@ -71,13 +71,13 @@ inline void Blitter_32bppAnim::Draw(cons
 
					src_px += d;
 
					src_n += d;
 

	
 
					dst = dst_end - bp->skip_left;
 
					dst_end = dst + bp->width;
 

	
 
					n = min<uint>(n - d, (uint)bp->width);
 
					n = std::min(n - d, (uint)bp->width);
 
					goto draw;
 
				}
 
				dst += n;
 
				src_px += n;
 
				src_n += n;
 
			}
 
@@ -86,13 +86,13 @@ inline void Blitter_32bppAnim::Draw(cons
 
		dst -= bp->skip_left;
 
		dst_end -= bp->skip_left;
 

	
 
		dst_end += bp->width;
 

	
 
		while (dst < dst_end) {
 
			n = min<uint>(*src_n++, (uint)(dst_end - dst));
 
			n = std::min<uint>(*src_n++, dst_end - dst);
 

	
 
			if (src_px->a == 0) {
 
				anim += n;
 
				dst += n;
 
				src_px++;
 
				src_n++;
src/blitter/32bpp_anim_sse2.cpp
Show inline comments
 
@@ -55,13 +55,13 @@ void Blitter_32bppSSE2_Anim::PaletteAnim
 
			int colour_cmp_result = _mm_movemask_epi8(_mm_cmpgt_epi16(colour_data, anim_cmp));
 
			if (colour_cmp_result) {
 
				/* test if any brightness is unexpected */
 
				if (x < 8 || colour_cmp_result != 0xFFFF ||
 
						_mm_movemask_epi8(_mm_cmpeq_epi16(_mm_srli_epi16(data, 8), brightness_cmp)) != 0xFFFF) {
 
					/* slow path: < 8 pixels left or unexpected brightnesses */
 
					for (int z = min<int>(x, 8); z != 0 ; z--) {
 
					for (int z = std::min<int>(x, 8); z != 0 ; z--) {
 
						int value = _mm_extract_epi16(data, 0);
 
						uint8 colour = GB(value, 0, 8);
 
						if (colour >= PALETTE_ANIM_START) {
 
							/* Update this pixel */
 
							*dst = AdjustBrightneSSE(LookupColourInPalette(colour), GB(value, 8, 8));
 
							screen_dirty = true;
src/blitter/32bpp_base.cpp
Show inline comments
 
@@ -171,15 +171,15 @@ Colour Blitter_32bppBase::ReallyAdjustBr
 
	if (g > 255) ob += g - 255;
 
	if (b > 255) ob += b - 255;
 

	
 
	/* Reduce overbright strength */
 
	ob /= 2;
 
	return Colour(
 
		r >= 255 ? 255 : min(r + ob * (255 - r) / 256, 255),
 
		g >= 255 ? 255 : min(g + ob * (255 - g) / 256, 255),
 
		b >= 255 ? 255 : min(b + ob * (255 - b) / 256, 255),
 
		r >= 255 ? 255 : std::min(r + ob * (255 - r) / 256, 255),
 
		g >= 255 ? 255 : std::min(g + ob * (255 - g) / 256, 255),
 
		b >= 255 ? 255 : std::min(b + ob * (255 - b) / 256, 255),
 
		colour.a);
 
}
 

	
 
Blitter::PaletteAnimation Blitter_32bppBase::UsePaletteAnimation()
 
{
 
	return Blitter::PALETTE_ANIMATION_NONE;
src/blitter/32bpp_optimized.cpp
Show inline comments
 
@@ -80,13 +80,13 @@ inline void Blitter_32bppOptimized::Draw
 
					src_px += d;
 
					src_n += d;
 

	
 
					dst = dst_end - bp->skip_left;
 
					dst_end = dst + bp->width;
 

	
 
					n = min<uint>(n - d, (uint)bp->width);
 
					n = std::min(n - d, (uint)bp->width);
 
					goto draw;
 
				}
 
				dst += n;
 
				src_px += n;
 
				src_n += n;
 
			}
 
@@ -95,13 +95,13 @@ inline void Blitter_32bppOptimized::Draw
 
		dst -= bp->skip_left;
 
		dst_end -= bp->skip_left;
 

	
 
		dst_end += bp->width;
 

	
 
		while (dst < dst_end) {
 
			n = min<uint>(*src_n++, (uint)(dst_end - dst));
 
			n = std::min<uint>(*src_n++, dst_end - dst);
 

	
 
			if (src_px->a == 0) {
 
				dst += n;
 
				src_px++;
 
				src_n++;
 
				continue;
 
@@ -321,13 +321,13 @@ Sprite *Blitter_32bppOptimized::Encode(c
 

	
 
				if (a != 0) {
 
					dst_px->a = a;
 
					*dst_n = src->m;
 
					if (src->m != 0) {
 
						/* Get brightest value */
 
						uint8 rgb_max = max(src->r, max(src->g, src->b));
 
						uint8 rgb_max = std::max({src->r, src->g, src->b});
 

	
 
						/* Black pixel (8bpp or old 32bpp image), so use default value */
 
						if (rgb_max == 0) rgb_max = DEFAULT_BRIGHTNESS;
 
						*dst_n |= rgb_max << 8;
 

	
 
						/* Pre-convert the mapping channel to a RGB value */
src/blitter/32bpp_simple.cpp
Show inline comments
 
@@ -129,13 +129,13 @@ Sprite *Blitter_32bppSimple::Encode(cons
 
			dst[i].b = src->b;
 
			dst[i].a = src->a;
 
			dst[i].m = 0;
 
			dst[i].v = 0;
 
		} else {
 
			/* Get brightest value */
 
			uint8 rgb_max = max(src->r, max(src->g, src->b));
 
			uint8 rgb_max = std::max({src->r, src->g, src->b});
 

	
 
			/* Black pixel (8bpp or old 32bpp image), so use default value */
 
			if (rgb_max == 0) rgb_max = DEFAULT_BRIGHTNESS;
 
			dst[i].v = rgb_max;
 

	
 
			/* Pre-convert the mapping channel to a RGB value */
src/blitter/32bpp_sse2.cpp
Show inline comments
 
@@ -77,13 +77,13 @@ Sprite *Blitter_32bppSSE_Base::Encode(co
 
					if (src->m != 0) {
 
						/* Do some accounting for flags. */
 
						has_remap = true;
 
						if (src->m >= PALETTE_ANIM_START) has_anim = true;
 

	
 
						/* Get brightest value (or default brightness if it's a black pixel). */
 
						const uint8 rgb_max = max(src->r, max(src->g, src->b));
 
						const uint8 rgb_max = std::max({src->r, src->g, src->b});
 
						dst_mv->v = (rgb_max == 0) ? Blitter_32bppBase::DEFAULT_BRIGHTNESS : rgb_max;
 

	
 
						/* Pre-convert the mapping channel to a RGB value. */
 
						const Colour colour = AdjustBrightneSSE(Blitter_32bppBase::LookupColourInPalette(src->m), dst_mv->v);
 
						dst_rgba->r = colour.r;
 
						dst_rgba->g = colour.g;
src/blitter/8bpp_optimized.cpp
Show inline comments
 
@@ -77,13 +77,13 @@ void Blitter_8bppOptimized::Draw(Blitter
 
			if (skip_left != 0) continue;
 

	
 
			/* Skip transparent pixels */
 
			dst += trans;
 
			width -= trans;
 
			if (width <= 0 || pixels == 0) continue;
 
			pixels = min<uint>(pixels, (uint)width);
 
			pixels = std::min<uint>(pixels, width);
 
			width -= pixels;
 

	
 
			switch (mode) {
 
				case BM_COLOUR_REMAP:
 
				case BM_CRASH_REMAP: {
 
					const uint8 *remap = bp->remap;
src/blitter/common.hpp
Show inline comments
 
@@ -42,13 +42,13 @@ void Blitter::DrawLineGeneric(int x, int
 
	if (dx == 0 && dy == 0) {
 
		/* The algorithm below cannot handle this special case; make it work at least for line width 1 */
 
		if (x >= 0 && x < screen_width && y >= 0 && y < screen_height) set_pixel(x, y);
 
		return;
 
	}
 

	
 
	int frac_diff = width * max(dx, dy);
 
	int frac_diff = width * std::max(dx, dy);
 
	if (width > 1) {
 
		/* compute frac_diff = width * sqrt(dx*dx + dy*dy)
 
		 * Start interval:
 
		 *    max(dx, dy) <= sqrt(dx*dx + dy*dy) <= sqrt(2) * max(dx, dy) <= 3/2 * max(dx, dy) */
 
		int64 frac_sq = ((int64) width) * ((int64) width) * (((int64) dx) * ((int64) dx) + ((int64) dy) * ((int64) dy));
 
		int frac_max = 3 * frac_diff / 2;
src/bridge_gui.cpp
Show inline comments
 
@@ -194,13 +194,13 @@ public:
 
					SetDParam(1, b->speed);
 
					SetDParam(0, b->material);
 
					text_dim = maxdim(text_dim, GetStringBoundingBox(_game_mode == GM_EDITOR ? STR_SELECT_BRIDGE_SCENEDIT_INFO : STR_SELECT_BRIDGE_INFO));
 
				}
 
				sprite_dim.height++; // Sprite is rendered one pixel down in the matrix field.
 
				text_dim.height++; // Allowing the bottom row pixels to be rendered on the edge of the matrix field.
 
				resize->height = max(sprite_dim.height, text_dim.height) + 2; // Max of both sizes + account for matrix edges.
 
				resize->height = std::max(sprite_dim.height, text_dim.height) + 2; // Max of both sizes + account for matrix edges.
 

	
 
				this->bridgetext_offset = WD_MATRIX_LEFT + sprite_dim.width + 1; // Left edge of text, 1 pixel distance from the sprite.
 
				size->width = this->bridgetext_offset + text_dim.width + WD_MATRIX_RIGHT;
 
				size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
 
				break;
 
			}
src/build_vehicle_gui.cpp
Show inline comments
 
@@ -41,13 +41,13 @@
 
 * Get the height of a single 'entry' in the engine lists.
 
 * @param type the vehicle type to get the height of
 
 * @return the height for the entry
 
 */
 
uint GetEngineListHeight(VehicleType type)
 
{
 
	return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleImageCellSize(type, EIT_PURCHASE).height);
 
	return std::max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleImageCellSize(type, EIT_PURCHASE).height);
 
}
 

	
 
static const NWidgetPart _nested_build_vehicle_widgets[] = {
 
	NWidget(NWID_HORIZONTAL),
 
		NWidget(WWT_CLOSEBOX, COLOUR_GREY),
 
		NWidget(WWT_CAPTION, COLOUR_GREY, WID_BV_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
 
@@ -1534,13 +1534,13 @@ struct BuildVehicleWindow : Window {
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_BV_LIST:
 
				resize->height = GetEngineListHeight(this->vehicle_type);
 
				size->height = 3 * resize->height;
 
				size->width = max(size->width, GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_left + GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_right + 165);
 
				size->width = std::max(size->width, GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_left + GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_right + 165);
 
				break;
 

	
 
			case WID_BV_PANEL:
 
				size->height = this->details_height;
 
				break;
 

	
 
@@ -1569,13 +1569,24 @@ struct BuildVehicleWindow : Window {
 
	}
 

	
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
		switch (widget) {
 
			case WID_BV_LIST:
 
				DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (uint)this->eng_list.size()), this->sel_engine, false, DEFAULT_GROUP);
 
				DrawEngineList(
 
					this->vehicle_type,
 
					r.left + WD_FRAMERECT_LEFT,
 
					r.right - WD_FRAMERECT_RIGHT,
 
					r.top + WD_FRAMERECT_TOP,
 
					&this->eng_list,
 
					this->vscroll->GetPosition(),
 
					static_cast<uint16>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.size())),
 
					this->sel_engine,
 
					false,
 
					DEFAULT_GROUP
 
				);
 
				break;
 

	
 
			case WID_BV_SORT_ASCENDING_DESCENDING:
 
				this->DrawSortButtonState(WID_BV_SORT_ASCENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP);
 
				break;
 
		}
 
@@ -1594,13 +1605,13 @@ struct BuildVehicleWindow : Window {
 
			int needed_height = this->details_height;
 
			/* Draw details panels. */
 
			if (this->sel_engine != INVALID_ENGINE) {
 
				NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_BV_PANEL);
 
				int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT,
 
						nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine, this->te);
 
				needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
 
				needed_height = std::max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
 
			}
 
			if (needed_height != this->details_height) { // Details window are not high enough, enlarge them.
 
				int resize = needed_height - this->details_height;
 
				this->details_height = needed_height;
 
				this->ReInit(0, resize);
 
				return;
src/cargopacket.cpp
Show inline comments
 
@@ -555,13 +555,13 @@ void VehicleCargoList::InvalidateCache()
 
 */
 
template<VehicleCargoList::MoveToAction Tfrom, VehicleCargoList::MoveToAction Tto>
 
uint VehicleCargoList::Reassign(uint max_move, TileOrStationID)
 
{
 
	static_assert(Tfrom != MTA_TRANSFER && Tto != MTA_TRANSFER);
 
	static_assert(Tfrom - Tto == 1 || Tto - Tfrom == 1);
 
	max_move = min(this->action_counts[Tfrom], max_move);
 
	max_move = std::min(this->action_counts[Tfrom], max_move);
 
	this->action_counts[Tfrom] -= max_move;
 
	this->action_counts[Tto] += max_move;
 
	return max_move;
 
}
 

	
 
/**
 
@@ -571,13 +571,13 @@ uint VehicleCargoList::Reassign(uint max
 
 * @param next_station Station to record as next hop in the reassigned packets.
 
 * @return Amount of cargo actually reassigned.
 
 */
 
template<>
 
uint VehicleCargoList::Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(uint max_move, TileOrStationID next_station)
 
{
 
	max_move = min(this->action_counts[MTA_DELIVER], max_move);
 
	max_move = std::min(this->action_counts[MTA_DELIVER], max_move);
 

	
 
	uint sum = 0;
 
	for (Iterator it(this->packets.begin()); sum < this->action_counts[MTA_TRANSFER] + max_move;) {
 
		CargoPacket *cp = *it++;
 
		sum += cp->Count();
 
		if (sum <= this->action_counts[MTA_TRANSFER]) continue;
 
@@ -600,26 +600,26 @@ uint VehicleCargoList::Reassign<VehicleC
 
 * @param dest Station the cargo is returned to.
 
 * @param next ID of the next station the cargo wants to go to.
 
 * @return Amount of cargo actually returned.
 
 */
 
uint VehicleCargoList::Return(uint max_move, StationCargoList *dest, StationID next)
 
{
 
	max_move = min(this->action_counts[MTA_LOAD], max_move);
 
	max_move = std::min(this->action_counts[MTA_LOAD], max_move);
 
	this->PopCargo(CargoReturn(this, dest, max_move, next));
 
	return max_move;
 
}
 

	
 
/**
 
 * Shifts cargo between two vehicles.
 
 * @param dest Other vehicle's cargo list.
 
 * @param max_move Maximum amount of cargo to be moved.
 
 * @return Amount of cargo actually moved.
 
 */
 
uint VehicleCargoList::Shift(uint max_move, VehicleCargoList *dest)
 
{
 
	max_move = min(this->count, max_move);
 
	max_move = std::min(this->count, max_move);
 
	this->PopCargo(CargoShift(this, dest, max_move));
 
	return max_move;
 
}
 

	
 
/**
 
 * Unloads cargo at the given station. Deliver or transfer, depending on the
 
@@ -630,18 +630,18 @@ uint VehicleCargoList::Shift(uint max_mo
 
 * @return Amount of cargo actually unloaded.
 
 */
 
uint VehicleCargoList::Unload(uint max_move, StationCargoList *dest, CargoPayment *payment)
 
{
 
	uint moved = 0;
 
	if (this->action_counts[MTA_TRANSFER] > 0) {
 
		uint move = min(this->action_counts[MTA_TRANSFER], max_move);
 
		uint move = std::min(this->action_counts[MTA_TRANSFER], max_move);
 
		this->ShiftCargo(CargoTransfer(this, dest, move));
 
		moved += move;
 
	}
 
	if (this->action_counts[MTA_TRANSFER] == 0 && this->action_counts[MTA_DELIVER] > 0 && moved < max_move) {
 
		uint move = min(this->action_counts[MTA_DELIVER], max_move - moved);
 
		uint move = std::min(this->action_counts[MTA_DELIVER], max_move - moved);
 
		this->ShiftCargo(CargoDelivery(this, move, payment));
 
		moved += move;
 
	}
 
	return moved;
 
}
 

	
 
@@ -650,13 +650,13 @@ uint VehicleCargoList::Unload(uint max_m
 
 * first cargo entities and removes max_move from the back of the list.
 
 * @param max_move Maximum amount of entities to be removed from the list.
 
 * @return Amount of entities actually moved.
 
 */
 
uint VehicleCargoList::Truncate(uint max_move)
 
{
 
	max_move = min(this->count, max_move);
 
	max_move = std::min(this->count, max_move);
 
	this->PopCargo(CargoRemoval<VehicleCargoList>(this, max_move));
 
	return max_move;
 
}
 

	
 
/**
 
 * Routes packets with station "avoid" as next hop to a different place.
 
@@ -665,13 +665,13 @@ uint VehicleCargoList::Truncate(uint max
 
 * @param avoid Station to exclude from routing and current next hop of packets to reroute.
 
 * @param avoid2 Additional station to exclude from routing.
 
 * @param ge GoodsEntry to get the routing info from.
 
 */
 
uint VehicleCargoList::Reroute(uint max_move, VehicleCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge)
 
{
 
	max_move = min(this->action_counts[MTA_TRANSFER], max_move);
 
	max_move = std::min(this->action_counts[MTA_TRANSFER], max_move);
 
	this->ShiftCargo(VehicleCargoReroute(this, dest, max_move, avoid, avoid2, ge));
 
	return max_move;
 
}
 

	
 
/*
 
 *
 
@@ -765,13 +765,13 @@ uint StationCargoList::ShiftCargo(Tactio
 
 * @param max_move Maximum amount of cargo to remove.
 
 * @param cargo_per_source Container for counting the cargo by origin.
 
 * @return Amount of cargo actually moved.
 
 */
 
uint StationCargoList::Truncate(uint max_move, StationCargoAmountMap *cargo_per_source)
 
{
 
	max_move = min(max_move, this->count);
 
	max_move = std::min(max_move, this->count);
 
	uint prev_count = this->count;
 
	uint moved = 0;
 
	uint loop = 0;
 
	bool do_count = cargo_per_source != nullptr;
 
	while (max_move > moved) {
 
		for (Iterator it(this->packets.begin()); it != this->packets.end();) {
 
@@ -836,13 +836,13 @@ uint StationCargoList::Reserve(uint max_
 
 * @note Vehicles may or may not reserve, depending on their orders. The two
 
 *       modes of loading are exclusive, though. If cargo is reserved we don't
 
 *       need to load unreserved cargo.
 
 */
 
uint StationCargoList::Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next_station)
 
{
 
	uint move = min(dest->ActionCount(VehicleCargoList::MTA_LOAD), max_move);
 
	uint move = std::min(dest->ActionCount(VehicleCargoList::MTA_LOAD), max_move);
 
	if (move > 0) {
 
		this->reserved_count -= move;
 
		dest->Reassign<VehicleCargoList::MTA_LOAD, VehicleCargoList::MTA_KEEP>(move);
 
		return move;
 
	} else {
 
		return this->ShiftCargo(CargoLoad(this, dest, max_move, load_place), next_station, true);
src/cargotype.cpp
Show inline comments
 
@@ -9,13 +9,12 @@
 

	
 
#include "stdafx.h"
 
#include "cargotype.h"
 
#include "newgrf_cargo.h"
 
#include "string_func.h"
 
#include "strings_func.h"
 
#include <algorithm>
 

	
 
#include "table/sprites.h"
 
#include "table/strings.h"
 
#include "table/cargo_const.h"
 

	
 
#include "safeguards.h"
src/cheat_gui.cpp
Show inline comments
 
@@ -288,43 +288,43 @@ struct CheatWindow : Window {
 
		uint width = 0;
 
		for (int i = 0; i != lengthof(_cheats_ui); i++) {
 
			const CheatEntry *ce = &_cheats_ui[i];
 
			switch (ce->type) {
 
				case SLE_BOOL:
 
					SetDParam(0, STR_CONFIG_SETTING_ON);
 
					width = max(width, GetStringBoundingBox(ce->str).width);
 
					width = std::max(width, GetStringBoundingBox(ce->str).width);
 
					SetDParam(0, STR_CONFIG_SETTING_OFF);
 
					width = max(width, GetStringBoundingBox(ce->str).width);
 
					width = std::max(width, GetStringBoundingBox(ce->str).width);
 
					break;
 

	
 
				default:
 
					switch (ce->str) {
 
						/* Display date for change date cheat */
 
						case STR_CHEAT_CHANGE_DATE:
 
							SetDParam(0, ConvertYMDToDate(MAX_YEAR, 11, 31));
 
							width = max(width, GetStringBoundingBox(ce->str).width);
 
							width = std::max(width, GetStringBoundingBox(ce->str).width);
 
							break;
 

	
 
						/* Draw coloured flag for change company cheat */
 
						case STR_CHEAT_CHANGE_COMPANY:
 
							SetDParamMaxValue(0, MAX_COMPANIES);
 
							width = max(width, GetStringBoundingBox(ce->str).width + 10 + 10);
 
							width = std::max(width, GetStringBoundingBox(ce->str).width + 10 + 10);
 
							break;
 

	
 
						default:
 
							SetDParam(0, INT64_MAX);
 
							width = max(width, GetStringBoundingBox(ce->str).width);
 
							width = std::max(width, GetStringBoundingBox(ce->str).width);
 
							break;
 
					}
 
					break;
 
			}
 
		}
 

	
 
		this->line_height = max(GetSpriteSize(SPR_BOX_CHECKED).height, GetSpriteSize(SPR_BOX_EMPTY).height);
 
		this->line_height = max<uint>(this->line_height, SETTING_BUTTON_HEIGHT);
 
		this->line_height = max<uint>(this->line_height, FONT_HEIGHT_NORMAL) + WD_PAR_VSEP_NORMAL;
 
		this->line_height = std::max(GetSpriteSize(SPR_BOX_CHECKED).height, GetSpriteSize(SPR_BOX_EMPTY).height);
 
		this->line_height = std::max<uint>(this->line_height, SETTING_BUTTON_HEIGHT);
 
		this->line_height = std::max<uint>(this->line_height, FONT_HEIGHT_NORMAL) + WD_PAR_VSEP_NORMAL;
 

	
 
		size->width = width + 20 + this->box_width + SETTING_BUTTON_WIDTH /* stuff on the left */ + 10 /* extra spacing on right */;
 
		this->header_height = GetStringHeight(STR_CHEATS_WARNING, size->width - WD_FRAMERECT_LEFT - WD_FRAMERECT_RIGHT) + WD_PAR_VSEP_WIDE;
 
		size->height = this->header_height + WD_FRAMERECT_TOP + WD_PAR_VSEP_NORMAL + WD_FRAMERECT_BOTTOM + this->line_height * lengthof(_cheats_ui);
 
	}
 

	
src/clear_cmd.cpp
Show inline comments
 
@@ -188,13 +188,13 @@ static void TileLoopClearAlps(TileIndex 
 
			MarkTileDirtyByTile(tile);
 
			return;
 
		}
 
	}
 
	/* Update snow density. */
 
	uint current_density = GetClearDensity(tile);
 
	uint req_density = (k < 0) ? 0u : min((uint)k, 3);
 
	uint req_density = (k < 0) ? 0u : std::min<uint>(k, 3u);
 

	
 
	if (current_density < req_density) {
 
		AddClearDensity(tile, 1);
 
	} else if (current_density > req_density) {
 
		AddClearDensity(tile, -1);
 
	} else {
src/company_cmd.cpp
Show inline comments
 
@@ -262,15 +262,15 @@ void SubtractMoneyFromCompanyFract(Compa
 
}
 

	
 
/** Update the landscaping limits per company. */
 
void UpdateLandscapingLimits()
 
{
 
	for (Company *c : Company::Iterate()) {
 
		c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
 
		c->clear_limit     = min(c->clear_limit     + _settings_game.construction.clear_per_64k_frames,     (uint32)_settings_game.construction.clear_frame_burst << 16);
 
		c->tree_limit      = min(c->tree_limit      + _settings_game.construction.tree_per_64k_frames,      (uint32)_settings_game.construction.tree_frame_burst << 16);
 
		c->terraform_limit = std::min<uint32>(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, _settings_game.construction.terraform_frame_burst << 16);
 
		c->clear_limit     = std::min<uint32>(c->clear_limit     + _settings_game.construction.clear_per_64k_frames,     _settings_game.construction.clear_frame_burst << 16);
 
		c->tree_limit      = std::min<uint32>(c->tree_limit      + _settings_game.construction.tree_per_64k_frames,      _settings_game.construction.tree_frame_burst << 16);
 
	}
 
}
 

	
 
/**
 
 * Set the right DParams to get the name of an owner.
 
 * @param owner the owner to get the name of.
 
@@ -551,13 +551,13 @@ Company *DoStartupNewCompany(bool is_ai,
 

	
 
	c->colour = colour;
 

	
 
	ResetCompanyLivery(c);
 
	_company_colours[c->index] = (Colours)c->colour;
 

	
 
	c->money = c->current_loan = (min(INITIAL_LOAN, _economy.max_loan) * _economy.inflation_prices >> 16) / 50000 * 50000;
 
	c->money = c->current_loan = (std::min<int64>(INITIAL_LOAN, _economy.max_loan) * _economy.inflation_prices >> 16) / 50000 * 50000;
 

	
 
	c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
 

	
 
	c->avail_railtypes = GetCompanyRailtypes(c->index);
 
	c->avail_roadtypes = GetCompanyRoadTypes(c->index);
 
	c->inaugurated_year = _cur_year;
 
@@ -705,13 +705,13 @@ void OnTick_Companies()
 
		if (c->name_1 != 0) GenerateCompanyName(c);
 
		if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
 
	}
 

	
 
	if (_next_competitor_start == 0) {
 
		/* AI::GetStartNextTime() can return 0. */
 
		_next_competitor_start = max(1, AI::GetStartNextTime() * DAY_TICKS);
 
		_next_competitor_start = std::max(1, AI::GetStartNextTime() * DAY_TICKS);
 
	}
 

	
 
	if (_game_mode != GM_MENU && AI::CanStartNew() && --_next_competitor_start == 0) {
 
		/* Allow multiple AIs to possibly start in the same tick. */
 
		do {
 
			if (!MaybeStartNewCompany()) break;
 
@@ -1195,13 +1195,13 @@ uint32 CompanyInfrastructure::GetTramTot
 
 */
 
CommandCost CmdGiveMoney(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	if (!_settings_game.economy.give_money) return CMD_ERROR;
 

	
 
	const Company *c = Company::Get(_current_company);
 
	CommandCost amount(EXPENSES_OTHER, min((Money)p1, (Money)20000000LL));
 
	CommandCost amount(EXPENSES_OTHER, std::min<Money>(p1, 20000000LL));
 
	CompanyID dest_company = (CompanyID)p2;
 

	
 
	/* You can only transfer funds that is in excess of your loan */
 
	if (c->money - c->current_loan < amount.GetCost() || amount.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS);
 
	if (!Company::IsValidID(dest_company)) return CMD_ERROR;
 

	
src/company_gui.cpp
Show inline comments
 
@@ -109,17 +109,17 @@ struct ExpensesList {
 
		uint width = 0;
 
		bool invalid_expenses_measured = false; // Measure 'Total' width only once.
 
		for (uint i = 0; i < this->length; i++) {
 
			ExpensesType et = this->et[i];
 
			if (et == INVALID_EXPENSES) {
 
				if (!invalid_expenses_measured) {
 
					width = max(width, GetStringBoundingBox(STR_FINANCES_TOTAL_CAPTION).width);
 
					width = std::max(width, GetStringBoundingBox(STR_FINANCES_TOTAL_CAPTION).width);
 
					invalid_expenses_measured = true;
 
				}
 
			} else {
 
				width = max(width, GetStringBoundingBox(STR_FINANCES_SECTION_CONSTRUCTION + et).width);
 
				width = std::max(width, GetStringBoundingBox(STR_FINANCES_SECTION_CONSTRUCTION + et).width);
 
			}
 
		}
 
		return width;
 
	}
 
};
 

	
 
@@ -319,13 +319,13 @@ struct CompanyFinancesWindow : Window {
 
				FALLTHROUGH;
 

	
 
			case WID_CF_BALANCE_VALUE:
 
			case WID_CF_LOAN_VALUE:
 
			case WID_CF_TOTAL_VALUE:
 
				SetDParamMaxValue(0, CompanyFinancesWindow::max_money);
 
				size->width = max(GetStringBoundingBox(STR_FINANCES_NEGATIVE_INCOME).width, GetStringBoundingBox(STR_FINANCES_POSITIVE_INCOME).width) + padding.width;
 
				size->width = std::max(GetStringBoundingBox(STR_FINANCES_NEGATIVE_INCOME).width, GetStringBoundingBox(STR_FINANCES_POSITIVE_INCOME).width) + padding.width;
 
				break;
 

	
 
			case WID_CF_MAXLOAN_GAP:
 
				size->height = FONT_HEIGHT_NORMAL;
 
				break;
 
		}
 
@@ -339,13 +339,13 @@ struct CompanyFinancesWindow : Window {
 
				break;
 

	
 
			case WID_CF_EXPS_PRICE1:
 
			case WID_CF_EXPS_PRICE2:
 
			case WID_CF_EXPS_PRICE3: {
 
				const Company *c = Company::Get((CompanyID)this->window_number);
 
				int age = min(_cur_year - c->inaugurated_year, 2);
 
				int age = std::min(_cur_year - c->inaugurated_year, 2);
 
				int wid_offset = widget - WID_CF_EXPS_PRICE1;
 
				if (wid_offset <= age) {
 
					DrawYearColumn(r, _cur_year - (age - wid_offset), c->yearly_expenses + (age - wid_offset));
 
				}
 
				break;
 
			}
 
@@ -452,13 +452,13 @@ struct CompanyFinancesWindow : Window {
 
	}
 

	
 
	void OnHundredthTick() override
 
	{
 
		const Company *c = Company::Get((CompanyID)this->window_number);
 
		if (c->money > CompanyFinancesWindow::max_money) {
 
			CompanyFinancesWindow::max_money = max(c->money * 2, CompanyFinancesWindow::max_money * 4);
 
			CompanyFinancesWindow::max_money = std::max(c->money * 2, CompanyFinancesWindow::max_money * 4);
 
			this->SetupWidgets();
 
			this->ReInit();
 
		}
 
	}
 
};
 

	
 
@@ -523,13 +523,13 @@ public:
 
	{
 
		return this->result >= COLOUR_END ? STR_COLOUR_DEFAULT : _colour_dropdown[this->result];
 
	}
 

	
 
	uint Height(uint width) const override
 
	{
 
		return max(FONT_HEIGHT_NORMAL, ScaleGUITrad(12) + 2);
 
		return std::max(FONT_HEIGHT_NORMAL, ScaleGUITrad(12) + 2);
 
	}
 

	
 
	bool Selectable() const override
 
	{
 
		return true;
 
	}
 
@@ -728,13 +728,13 @@ public:
 
		this->BuildGroupList(company);
 
		this->SetRows();
 

	
 
		/* Position scrollbar to selected group */
 
		for (uint i = 0; i < this->rows; i++) {
 
			if (this->groups[i]->index == sel) {
 
				this->vscroll->SetPosition(Clamp(i - this->vscroll->GetCapacity() / 2, 0, max(this->vscroll->GetCount() - this->vscroll->GetCapacity(), 0)));
 
				this->vscroll->SetPosition(Clamp(i - this->vscroll->GetCapacity() / 2, 0, std::max(this->vscroll->GetCount() - this->vscroll->GetCapacity(), 0)));
 
				break;
 
			}
 
		}
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
@@ -752,20 +752,20 @@ public:
 
					if (g->owner == (CompanyID)this->window_number) {
 
						SetDParam(0, g->index);
 
						d = maxdim(d, GetStringBoundingBox(STR_GROUP_NAME));
 
					}
 
				}
 

	
 
				size->width = max(size->width, 5 + d.width + WD_FRAMERECT_RIGHT);
 
				size->width = std::max(size->width, 5 + d.width + WD_FRAMERECT_RIGHT);
 
				break;
 
			}
 

	
 
			case WID_SCL_MATRIX: {
 
				/* 11 items in the default rail class */
 
				this->square = GetSpriteSize(SPR_SQUARE);
 
				this->line_height = max(this->square.height, (uint)FONT_HEIGHT_NORMAL) + 4;
 
				this->line_height = std::max(this->square.height, (uint)FONT_HEIGHT_NORMAL) + 4;
 

	
 
				size->height = 11 * this->line_height;
 
				resize->width = 1;
 
				resize->height = this->line_height;
 
				break;
 
			}
 
@@ -778,15 +778,15 @@ public:
 
				FALLTHROUGH;
 

	
 
			case WID_SCL_PRI_COL_DROPDOWN: {
 
				this->square = GetSpriteSize(SPR_SQUARE);
 
				int padding = this->square.width + NWidgetScrollbar::GetVerticalDimension().width + 10;
 
				for (const StringID *id = _colour_dropdown; id != endof(_colour_dropdown); id++) {
 
					size->width = max(size->width, GetStringBoundingBox(*id).width + padding);
 
					size->width = std::max(size->width, GetStringBoundingBox(*id).width + padding);
 
				}
 
				size->width = max(size->width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + padding);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + padding);
 
				break;
 
			}
 
		}
 
	}
 

	
 
	void OnPaint() override
 
@@ -895,13 +895,13 @@ public:
 
				if (_livery_class[scheme] == this->livery_class && HasBit(_loaded_newgrf_features.used_liveries, scheme)) {
 
					if (pos-- > 0) continue;
 
					draw_livery(STR_LIVERY_DEFAULT + scheme, c->livery[scheme], HasBit(this->sel, scheme), scheme == LS_DEFAULT, 0);
 
				}
 
			}
 
		} else {
 
			uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (uint)this->groups.size());
 
			uint max = static_cast<uint>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->groups.size()));
 
			for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
 
				const Group *g = this->groups[i];
 
				SetDParam(0, g->index);
 
				draw_livery(STR_GROUP_NAME, g->livery, this->sel == g->index, false, this->indents[i] * LEVEL_WIDTH);
 
			}
 
		}
 
@@ -1377,26 +1377,26 @@ public:
 
			number_dim = maxdim(number_dim, GetStringBoundingBox(STR_JUST_INT));
 
		}
 
		uint arrows_width = GetSpriteSize(SPR_ARROW_LEFT).width + GetSpriteSize(SPR_ARROW_RIGHT).width + 2 * (WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT);
 
		number_dim.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT + arrows_width;
 
		number_dim.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
 
		/* Compute width of both buttons. */
 
		yesno_dim.width = max(yesno_dim.width, number_dim.width);
 
		yesno_dim.width = std::max(yesno_dim.width, number_dim.width);
 
		number_dim.width = yesno_dim.width - arrows_width;
 

	
 
		this->yesno_dim = yesno_dim;
 
		this->number_dim = number_dim;
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_SCMF_FACE: {
 
				Dimension face_size = GetSpriteSize(SPR_GRADIENT);
 
				size->width  = max(size->width,  face_size.width);
 
				size->height = max(size->height, face_size.height);
 
				size->width  = std::max(size->width,  face_size.width);
 
				size->height = std::max(size->height, face_size.height);
 
				break;
 
			}
 

	
 
			case WID_SCMF_HAS_MOUSTACHE_EARRING_TEXT:
 
			case WID_SCMF_TIE_EARRING_TEXT: {
 
				int offset = (widget - WID_SCMF_HAS_MOUSTACHE_EARRING_TEXT) * 2;
 
@@ -1882,59 +1882,59 @@ struct CompanyInfrastructureWindow : Win
 
		const Company *c = Company::Get((CompanyID)this->window_number);
 

	
 
		switch (widget) {
 
			case WID_CI_RAIL_DESC: {
 
				uint lines = 1; // Starts at 1 because a line is also required for the section title
 

	
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_RAIL_SECT).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_RAIL_SECT).width);
 

	
 
				RailType rt;
 
				FOR_ALL_SORTED_RAILTYPES(rt) {
 
					if (HasBit(this->railtypes, rt)) {
 
						lines++;
 
						SetDParam(0, GetRailTypeInfo(rt)->strings.name);
 
						size->width = max(size->width, GetStringBoundingBox(STR_WHITE_STRING).width + WD_FRAMERECT_LEFT);
 
						size->width = std::max(size->width, GetStringBoundingBox(STR_WHITE_STRING).width + WD_FRAMERECT_LEFT);
 
					}
 
				}
 
				if (this->railtypes != RAILTYPES_NONE) {
 
					lines++;
 
					size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_SIGNALS).width + WD_FRAMERECT_LEFT);
 
					size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_SIGNALS).width + WD_FRAMERECT_LEFT);
 
				}
 

	
 
				size->height = max(size->height, lines * FONT_HEIGHT_NORMAL);
 
				size->height = std::max(size->height, lines * FONT_HEIGHT_NORMAL);
 
				break;
 
			}
 

	
 
			case WID_CI_ROAD_DESC:
 
			case WID_CI_TRAM_DESC: {
 
				uint lines = 1; // Starts at 1 because a line is also required for the section title
 

	
 
				size->width = max(size->width, GetStringBoundingBox(widget == WID_CI_ROAD_DESC ? STR_COMPANY_INFRASTRUCTURE_VIEW_ROAD_SECT : STR_COMPANY_INFRASTRUCTURE_VIEW_TRAM_SECT).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(widget == WID_CI_ROAD_DESC ? STR_COMPANY_INFRASTRUCTURE_VIEW_ROAD_SECT : STR_COMPANY_INFRASTRUCTURE_VIEW_TRAM_SECT).width);
 

	
 
				RoadType rt;
 
				FOR_ALL_SORTED_ROADTYPES(rt) {
 
					if (HasBit(this->roadtypes, rt) && RoadTypeIsRoad(rt) == (widget == WID_CI_ROAD_DESC)) {
 
						lines++;
 
						SetDParam(0, GetRoadTypeInfo(rt)->strings.name);
 
						size->width = max(size->width, GetStringBoundingBox(STR_WHITE_STRING).width + WD_FRAMERECT_LEFT);
 
						size->width = std::max(size->width, GetStringBoundingBox(STR_WHITE_STRING).width + WD_FRAMERECT_LEFT);
 
					}
 
				}
 

	
 
				size->height = max(size->height, lines * FONT_HEIGHT_NORMAL);
 
				size->height = std::max(size->height, lines * FONT_HEIGHT_NORMAL);
 
				break;
 
			}
 

	
 
			case WID_CI_WATER_DESC:
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_WATER_SECT).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_CANALS).width + WD_FRAMERECT_LEFT);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_WATER_SECT).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_CANALS).width + WD_FRAMERECT_LEFT);
 
				break;
 

	
 
			case WID_CI_STATION_DESC:
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATION_SECT).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATIONS).width + WD_FRAMERECT_LEFT);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_AIRPORTS).width + WD_FRAMERECT_LEFT);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATION_SECT).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATIONS).width + WD_FRAMERECT_LEFT);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_AIRPORTS).width + WD_FRAMERECT_LEFT);
 
				break;
 

	
 
			case WID_CI_RAIL_COUNT:
 
			case WID_CI_ROAD_COUNT:
 
			case WID_CI_TRAM_COUNT:
 
			case WID_CI_WATER_COUNT:
 
@@ -1942,48 +1942,48 @@ struct CompanyInfrastructureWindow : Win
 
			case WID_CI_TOTAL: {
 
				/* Find the maximum count that is displayed. */
 
				uint32 max_val = 1000;  // Some random number to reserve enough space.
 
				Money max_cost = 10000; // Some random number to reserve enough space.
 
				uint32 rail_total = c->infrastructure.GetRailTotal();
 
				for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
 
					max_val = max(max_val, c->infrastructure.rail[rt]);
 
					max_cost = max(max_cost, RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
 
					max_val = std::max(max_val, c->infrastructure.rail[rt]);
 
					max_cost = std::max(max_cost, RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
 
				}
 
				max_val = max(max_val, c->infrastructure.signal);
 
				max_cost = max(max_cost, SignalMaintenanceCost(c->infrastructure.signal));
 
				max_val = std::max(max_val, c->infrastructure.signal);
 
				max_cost = std::max(max_cost, SignalMaintenanceCost(c->infrastructure.signal));
 
				uint32 road_total = c->infrastructure.GetRoadTotal();
 
				uint32 tram_total = c->infrastructure.GetTramTotal();
 
				for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
 
					max_val = max(max_val, c->infrastructure.road[rt]);
 
					max_cost = max(max_cost, RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
 
					max_val = std::max(max_val, c->infrastructure.road[rt]);
 
					max_cost = std::max(max_cost, RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
 

	
 
				}
 
				max_val = max(max_val, c->infrastructure.water);
 
				max_cost = max(max_cost, CanalMaintenanceCost(c->infrastructure.water));
 
				max_val = max(max_val, c->infrastructure.station);
 
				max_cost = max(max_cost, StationMaintenanceCost(c->infrastructure.station));
 
				max_val = max(max_val, c->infrastructure.airport);
 
				max_cost = max(max_cost, AirportMaintenanceCost(c->index));
 
				max_val = std::max(max_val, c->infrastructure.water);
 
				max_cost = std::max(max_cost, CanalMaintenanceCost(c->infrastructure.water));
 
				max_val = std::max(max_val, c->infrastructure.station);
 
				max_cost = std::max(max_cost, StationMaintenanceCost(c->infrastructure.station));
 
				max_val = std::max(max_val, c->infrastructure.airport);
 
				max_cost = std::max(max_cost, AirportMaintenanceCost(c->index));
 

	
 
				SetDParamMaxValue(0, max_val);
 
				uint count_width = GetStringBoundingBox(STR_WHITE_COMMA).width + 20; // Reserve some wiggle room
 

	
 
				if (_settings_game.economy.infrastructure_maintenance) {
 
					SetDParamMaxValue(0, this->GetTotalMaintenanceCost() * 12); // Convert to per year
 
					this->total_width = GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL).width + 20;
 
					size->width = max(size->width, this->total_width);
 
					size->width = std::max(size->width, this->total_width);
 

	
 
					SetDParamMaxValue(0, max_cost * 12); // Convert to per year
 
					count_width += max(this->total_width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL).width);
 
					count_width += std::max(this->total_width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL).width);
 
				}
 

	
 
				size->width = max(size->width, count_width);
 
				size->width = std::max(size->width, count_width);
 

	
 
				/* Set height of the total line. */
 
				if (widget == WID_CI_TOTAL) {
 
					size->height = _settings_game.economy.infrastructure_maintenance ? max(size->height, EXP_LINESPACE + FONT_HEIGHT_NORMAL) : 0;
 
					size->height = _settings_game.economy.infrastructure_maintenance ? std::max(size->height, EXP_LINESPACE + FONT_HEIGHT_NORMAL) : 0;
 
				}
 
				break;
 
			}
 
		}
 
	}
 

	
 
@@ -2364,14 +2364,14 @@ struct CompanyWindow : Window
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_C_FACE: {
 
				Dimension face_size = GetSpriteSize(SPR_GRADIENT);
 
				size->width  = max(size->width,  face_size.width);
 
				size->height = max(size->height, face_size.height);
 
				size->width  = std::max(size->width,  face_size.width);
 
				size->height = std::max(size->height, face_size.height);
 
				break;
 
			}
 

	
 
			case WID_C_DESC_COLOUR_SCHEME_EXAMPLE: {
 
				Point offset;
 
				Dimension d = GetSpriteSize(SPR_VEH_BUS_SW_VIEW, &offset);
 
@@ -2386,50 +2386,50 @@ struct CompanyWindow : Window
 
				size->width = GetStringBoundingBox(STR_COMPANY_VIEW_COMPANY_VALUE).width;
 
				break;
 

	
 
			case WID_C_DESC_VEHICLE_COUNTS:
 
				SetDParamMaxValue(0, 5000); // Maximum number of vehicles
 
				for (uint i = 0; i < lengthof(_company_view_vehicle_count_strings); i++) {
 
					size->width = max(size->width, GetStringBoundingBox(_company_view_vehicle_count_strings[i]).width);
 
					size->width = std::max(size->width, GetStringBoundingBox(_company_view_vehicle_count_strings[i]).width);
 
				}
 
				break;
 

	
 
			case WID_C_DESC_INFRASTRUCTURE_COUNTS:
 
				SetDParamMaxValue(0, UINT_MAX);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_RAIL).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_ROAD).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_WATER).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_STATION).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_AIRPORT).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_NONE).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_RAIL).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_ROAD).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_WATER).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_STATION).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_AIRPORT).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_NONE).width);
 
				break;
 

	
 
			case WID_C_DESC_OWNERS: {
 
				for (const Company *c2 : Company::Iterate()) {
 
					SetDParamMaxValue(0, 75);
 
					SetDParam(1, c2->index);
 

	
 
					size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_SHARES_OWNED_BY).width);
 
					size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_SHARES_OWNED_BY).width);
 
				}
 
				break;
 
			}
 

	
 
			case WID_C_VIEW_HQ:
 
			case WID_C_BUILD_HQ:
 
			case WID_C_RELOCATE_HQ:
 
			case WID_C_VIEW_INFRASTRUCTURE:
 
			case WID_C_GIVE_MONEY:
 
			case WID_C_COMPANY_PASSWORD:
 
			case WID_C_COMPANY_JOIN:
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_VIEW_HQ_BUTTON).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_BUILD_HQ_BUTTON).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_RELOCATE_HQ).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_BUTTON).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_GIVE_MONEY_BUTTON).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_PASSWORD).width);
 
				size->width = max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_JOIN).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_VIEW_HQ_BUTTON).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_BUILD_HQ_BUTTON).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_RELOCATE_HQ).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_BUTTON).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_GIVE_MONEY_BUTTON).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_PASSWORD).width);
 
				size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_JOIN).width);
 
				break;
 

	
 
			case WID_C_HAS_PASSWORD:
 
				*size = maxdim(*size, GetSpriteSize(SPR_LOCK));
 
				break;
 
		}
src/console_cmds.cpp
Show inline comments
 
@@ -2012,13 +2012,13 @@ DEF_CONSOLE_CMD(ConNewGRFProfile)
 
				grfids += grfidstr;
 
			}
 
		}
 
		if (started > 0) {
 
			IConsolePrintF(CC_DEBUG, "Started profiling for GRFID%s %s", (started > 1) ? "s" : "", grfids.c_str());
 
			if (argc >= 3) {
 
				int days = max(atoi(argv[2]), 1);
 
				int days = std::max(atoi(argv[2]), 1);
 
				_newgrf_profile_end_date = _date + days;
 

	
 
				char datestrbuf[32]{ 0 };
 
				SetDParam(0, _newgrf_profile_end_date);
 
				GetString(datestrbuf, STR_JUST_DATE_ISO, lastof(datestrbuf));
 
				IConsolePrintF(CC_DEBUG, "Profiling will automatically stop on game date %s", datestrbuf);
src/console_gui.cpp
Show inline comments
 
@@ -191,13 +191,13 @@ struct IConsoleWindow : Window
 
	/**
 
	 * Scroll the content of the console.
 
	 * @param amount Number of lines to scroll back.
 
	 */
 
	void Scroll(int amount)
 
	{
 
		int max_scroll = max<int>(0, IConsoleLine::size + 1 - this->height / this->line_height);
 
		int max_scroll = std::max(0, IConsoleLine::size + 1 - this->height / this->line_height);
 
		IConsoleWindow::scroll = Clamp<int>(IConsoleWindow::scroll + amount, 0, max_scroll);
 
		this->SetDirty();
 
	}
 

	
 
	void OnPaint() override
 
	{
 
@@ -228,13 +228,13 @@ struct IConsoleWindow : Window
 
	}
 

	
 
	void OnHundredthTick() override
 
	{
 
		if (IConsoleLine::Truncate() &&
 
				(IConsoleWindow::scroll > IConsoleLine::size)) {
 
			IConsoleWindow::scroll = max(0, IConsoleLine::size - (this->height / this->line_height) + 1);
 
			IConsoleWindow::scroll = std::max(0, IConsoleLine::size - (this->height / this->line_height) + 1);
 
			this->SetDirty();
 
		}
 
	}
 

	
 
	void OnMouseLoop() override
 
	{
 
@@ -338,32 +338,32 @@ struct IConsoleWindow : Window
 
		*length = _iconsole_cmdline.markend - _iconsole_cmdline.markpos;
 
		return _iconsole_cmdline.buf + _iconsole_cmdline.markpos;
 
	}
 

	
 
	Point GetCaretPosition() const override
 
	{
 
		int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
 
		int delta = std::min<int>(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
 
		Point pt = {this->line_offset + delta + _iconsole_cmdline.caretxoffs, this->height - this->line_height};
 

	
 
		return pt;
 
	}
 

	
 
	Rect GetTextBoundingRect(const char *from, const char *to) const override
 
	{
 
		int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
 
		int delta = std::min<int>(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
 

	
 
		Point p1 = GetCharPosInString(_iconsole_cmdline.buf, from, FS_NORMAL);
 
		Point p2 = from != to ? GetCharPosInString(_iconsole_cmdline.buf, from) : p1;
 

	
 
		Rect r = {this->line_offset + delta + p1.x, this->height - this->line_height, this->line_offset + delta + p2.x, this->height};
 
		return r;
 
	}
 

	
 
	const char *GetTextCharacterAtPosition(const Point &pt) const override
 
	{
 
		int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
 
		int delta = std::min<int>(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
 

	
 
		if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return nullptr;
 

	
 
		return GetCharAtPosition(_iconsole_cmdline.buf, pt.x - delta);
 
	}
 

	
src/core/geometry_func.cpp
Show inline comments
 
@@ -19,10 +19,10 @@
 
 * @param d2 Second dimension.
 
 * @return The bounding box of both dimensions, the smallest dimension that surrounds both arguments.
 
 */
 
Dimension maxdim(const Dimension &d1, const Dimension &d2)
 
{
 
	Dimension d;
 
	d.width  = max(d1.width,  d2.width);
 
	d.height = max(d1.height, d2.height);
 
	d.width  = std::max(d1.width,  d2.width);
 
	d.height = std::max(d1.height, d2.height);
 
	return d;
 
}
src/core/kdtree.hpp
Show inline comments
 
@@ -9,13 +9,12 @@
 

	
 
#ifndef KDTREE_HPP
 
#define KDTREE_HPP
 

	
 
#include "../stdafx.h"
 
#include <vector>
 
#include <algorithm>
 
#include <limits>
 

	
 
/**
 
 * K-dimensional tree, specialised for 2-dimensional space.
 
 * This is not intended as a primary storage of data, but as an index into existing data.
 
 * Usually the type stored by this tree should be an index into an existing array.
 
@@ -258,13 +257,13 @@ class Kdtree {
 
		size_t next = (xy[dim] < c) ? n.left : n.right;
 
		if (next != INVALID_NODE) {
 
			/* Check if there is a better node down the tree */
 
			best = SelectNearestNodeDistance(best, this->FindNearestRecursive(xy, next, level + 1));
 
		}
 

	
 
		limit = min(best.second, limit);
 
		limit = std::min(best.second, limit);
 

	
 
		/* Check if the distance from current best is worse than distance from target to splitting line,
 
		 * if it is we also need to check the other side of the split. */
 
		size_t opposite = (xy[dim] >= c) ? n.left : n.right; // reverse of above
 
		if (opposite != INVALID_NODE && limit >= abs((int)xy[dim] - (int)c)) {
 
			node_distance other_candidate = this->FindNearestRecursive(xy, opposite, level + 1, limit);
src/core/math_func.hpp
Show inline comments
 
@@ -8,72 +8,12 @@
 
/** @file math_func.hpp Integer math functions */
 

	
 
#ifndef MATH_FUNC_HPP
 
#define MATH_FUNC_HPP
 

	
 
/**
 
 * Returns the maximum of two values.
 
 *
 
 * This function returns the greater value of two given values.
 
 * If they are equal the value of a is returned.
 
 *
 
 * @param a The first value
 
 * @param b The second value
 
 * @return The greater value or a if equals
 
 */
 
template <typename T>
 
static inline T max(const T a, const T b)
 
{
 
	return (a >= b) ? a : b;
 
}
 

	
 
/**
 
 * Returns the minimum of two values.
 
 *
 
 * This function returns the smaller value of two given values.
 
 * If they are equal the value of b is returned.
 
 *
 
 * @param a The first value
 
 * @param b The second value
 
 * @return The smaller value or b if equals
 
 */
 
template <typename T>
 
static inline T min(const T a, const T b)
 
{
 
	return (a < b) ? a : b;
 
}
 

	
 
/**
 
 * Returns the minimum of two integer.
 
 *
 
 * This function returns the smaller value of two given integers.
 
 *
 
 * @param a The first integer
 
 * @param b The second integer
 
 * @return The smaller value
 
 */
 
static inline int min(const int a, const int b)
 
{
 
	return min<int>(a, b);
 
}
 

	
 
/**
 
 * Returns the minimum of two unsigned integers.
 
 *
 
 * This function returns the smaller value of two given unsigned integers.
 
 *
 
 * @param a The first unsigned integer
 
 * @param b The second unsigned integer
 
 * @return The smaller value
 
 */
 
static inline uint minu(const uint a, const uint b)
 
{
 
	return min<uint>(a, b);
 
}
 

	
 
/**
 
 * Returns the absolute value of (scalar) variable.
 
 *
 
 * @note assumes variable to be signed
 
 * @param a The value we want to unsign
 
 * @return The unsigned value
 
 */
 
@@ -213,13 +153,13 @@ static inline int32 ClampToI32(const int
 
static inline uint16 ClampToU16(const uint64 a)
 
{
 
	/* MSVC thinks, in its infinite wisdom, that int min(int, int) is a better
 
	 * match for min(uint64, uint) than uint64 min(uint64, uint64). As such we
 
	 * need to cast the UINT16_MAX to prevent MSVC from displaying its
 
	 * infinite loads of warnings. */
 
	return static_cast<uint16>(min<uint64>(a, static_cast<uint64>(UINT16_MAX)));
 
	return static_cast<uint16>(std::min(a, static_cast<uint64>(UINT16_MAX)));
 
}
 

	
 
/**
 
 * Returns the (absolute) difference between two (scalar) variables
 
 *
 
 * @param a The first scalar
src/core/pool_func.hpp
Show inline comments
 
@@ -49,13 +49,13 @@ DEFINE_POOL_METHOD(inline)::Pool(const c
 
 */
 
DEFINE_POOL_METHOD(inline void)::ResizeFor(size_t index)
 
{
 
	assert(index >= this->size);
 
	assert(index < Tmax_size);
 

	
 
	size_t new_size = min(Tmax_size, Align(index + 1, Tgrowth_step));
 
	size_t new_size = std::min(Tmax_size, Align(index + 1, Tgrowth_step));
 

	
 
	this->data = ReallocT(this->data, new_size);
 
	MemSetT(this->data + this->size, 0, new_size - this->size);
 

	
 
	this->size = new_size;
 
}
 
@@ -97,13 +97,13 @@ DEFINE_POOL_METHOD(inline size_t)::FindF
 
 * @pre this->Get(index) == nullptr
 
 */
 
DEFINE_POOL_METHOD(inline void *)::AllocateItem(size_t size, size_t index)
 
{
 
	assert(this->data[index] == nullptr);
 

	
 
	this->first_unused = max(this->first_unused, index + 1);
 
	this->first_unused = std::max(this->first_unused, index + 1);
 
	this->items++;
 

	
 
	Titem *item;
 
	if (Tcache && this->alloc_cache != nullptr) {
 
		assert(sizeof(Titem) == size);
 
		item = (Titem *)this->alloc_cache;
 
@@ -184,13 +184,13 @@ DEFINE_POOL_METHOD(void)::FreeItem(size_
 
		ac->next = this->alloc_cache;
 
		this->alloc_cache = ac;
 
	} else {
 
		free(this->data[index]);
 
	}
 
	this->data[index] = nullptr;
 
	this->first_free = min(this->first_free, index);
 
	this->first_free = std::min(this->first_free, index);
 
	this->items--;
 
	if (!this->cleaning) Titem::PostDestructor(index);
 
}
 

	
 
/** Destroys all items in the pool and resets all member variables. */
 
DEFINE_POOL_METHOD(void)::CleanPool()
src/core/smallmatrix_type.hpp
Show inline comments
 
@@ -231,21 +231,21 @@ public:
 
					/* If matrix is growing, copy from the back to avoid
 
					 * overwriting uncopied data. */
 
					for (uint x = this->width; x > 0; --x) {
 
						if (x * new_height > new_capacity) continue;
 
						(*copy)(new_data + (x - 1) * new_height,
 
								this->data + (x - 1) * this->height,
 
								min(this->height, new_height));
 
								std::min(this->height, new_height));
 
					}
 
				} else {
 
					/* If matrix is shrinking copy from the front. */
 
					for (uint x = 0; x < this->width; ++x) {
 
						if ((x + 1) * new_height > new_capacity) break;
 
						(*copy)(new_data + x * new_height,
 
								this->data + x * this->height,
 
								min(this->height, new_height));
 
								std::min(this->height, new_height));
 
					}
 
				}
 
			}
 
			this->height = new_height;
 
			if (new_data != this->data) {
 
				free(this->data);
src/core/smallstack_type.hpp
Show inline comments
 
@@ -43,25 +43,25 @@ public:
 
	inline Tindex Create()
 
	{
 
		Tindex index = this->FindFirstFree();
 
		if (index < Tmax_size) {
 
			this->data[index].valid = true;
 
			this->first_free = index + 1;
 
			this->first_unused = max(this->first_unused, this->first_free);
 
			this->first_unused = std::max(this->first_unused, this->first_free);
 
		}
 
		return index;
 
	}
 

	
 
	/**
 
	 * Destroy (or rather invalidate) the item at the given index.
 
	 * @param index Index of item to be destroyed.
 
	 */
 
	inline void Destroy(Tindex index)
 
	{
 
		this->data[index].valid = false;
 
		this->first_free = min(this->first_free, index);
 
		this->first_free = std::min(this->first_free, index);
 
	}
 

	
 
private:
 

	
 
	inline Tindex FindFirstFree()
 
	{
src/core/smallvec_type.hpp
Show inline comments
 
@@ -10,13 +10,12 @@
 
#ifndef SMALLVEC_TYPE_HPP
 
#define SMALLVEC_TYPE_HPP
 

	
 
#include "alloc_func.hpp"
 
#include "mem_func.hpp"
 
#include <vector>
 
#include <algorithm>
 

	
 
/**
 
 * Helper function to append an item to a vector if it is not already contained
 
 * Consider using std::set, std::unordered_set or std::flat_set in new code
 
 *
 
 * @param vec A reference to the vector to be extended
src/date_gui.cpp
Show inline comments
 
@@ -38,14 +38,14 @@ struct SetDateWindow : Window {
 
	 * @param max_year the maximum year (inclusive) to show in the year dropdown
 
	 * @param callback the callback to call once a date has been selected
 
	 */
 
	SetDateWindow(WindowDesc *desc, WindowNumber window_number, Window *parent, Date initial_date, Year min_year, Year max_year, SetDateCallback *callback) :
 
			Window(desc),
 
			callback(callback),
 
			min_year(max(MIN_YEAR, min_year)),
 
			max_year(min(MAX_YEAR, max_year))
 
			min_year(std::max(MIN_YEAR, min_year)),
 
			max_year(std::min(MAX_YEAR, max_year))
 
	{
 
		assert(this->min_year <= this->max_year);
 
		this->parent = parent;
 
		this->InitNested(window_number);
 

	
 
		if (initial_date == 0) initial_date = _date;
src/depot_gui.cpp
Show inline comments
 
@@ -191,18 +191,18 @@ static void InitBlocksizeForVehicles(Veh
 

	
 
	int min_extend = ScaleGUITrad(16);
 
	int max_extend = ScaleGUITrad(98);
 

	
 
	switch (image_type) {
 
		case EIT_IN_DEPOT:
 
			_base_block_sizes_depot[type].height       = max<uint>(ScaleGUITrad(GetVehicleHeight(type)), max_height);
 
			_base_block_sizes_depot[type].height       = std::max<uint>(ScaleGUITrad(GetVehicleHeight(type)), max_height);
 
			_base_block_sizes_depot[type].extend_left  = Clamp(max_extend_left, min_extend, max_extend);
 
			_base_block_sizes_depot[type].extend_right = Clamp(max_extend_right, min_extend, max_extend);
 
			break;
 
		case EIT_PURCHASE:
 
			_base_block_sizes_purchase[type].height       = max<uint>(ScaleGUITrad(GetVehicleHeight(type)), max_height);
 
			_base_block_sizes_purchase[type].height       = std::max<uint>(ScaleGUITrad(GetVehicleHeight(type)), max_height);
 
			_base_block_sizes_purchase[type].extend_left  = Clamp(max_extend_left, min_extend, max_extend);
 
			_base_block_sizes_purchase[type].extend_right = Clamp(max_extend_right, min_extend, max_extend);
 
			break;
 

	
 
		default: NOT_REACHED();
 
	}
 
@@ -392,13 +392,13 @@ struct DepotWindow : Window {
 
			}
 
		}
 

	
 
		uint16 rows_in_display = wid->current_y / wid->resize_y;
 

	
 
		uint16 num = this->vscroll->GetPosition() * this->num_columns;
 
		int maxval = min((uint)this->vehicle_list.size(), num + (rows_in_display * this->num_columns));
 
		uint maxval = static_cast<uint>(std::min<size_t>(this->vehicle_list.size(), num + (rows_in_display * this->num_columns)));
 
		int y;
 
		for (y = r.top + 1; num < maxval; y += this->resize.step_height) { // Draw the rows
 
			for (byte i = 0; i < this->num_columns && num < maxval; i++, num++) {
 
				/* Draw all vehicles in the current row */
 
				const Vehicle *v = this->vehicle_list[num];
 
				if (this->num_columns == 1) {
 
@@ -407,13 +407,13 @@ struct DepotWindow : Window {
 
					int x = r.left + (rtl ? (this->num_columns - i - 1) : i) * this->resize.step_width;
 
					this->DrawVehicleInDepot(v, x, x + this->resize.step_width - 1, y);
 
				}
 
			}
 
		}
 

	
 
		maxval = min((uint)this->vehicle_list.size() + (uint)this->wagon_list.size(), (this->vscroll->GetPosition() * this->num_columns) + (rows_in_display * this->num_columns));
 
		maxval = static_cast<uint>(std::min<size_t>(this->vehicle_list.size() + this->wagon_list.size(), (this->vscroll->GetPosition() * this->num_columns) + (rows_in_display * this->num_columns)));
 

	
 
		/* Draw the train wagons without an engine in front. */
 
		for (; num < maxval; num++, y += this->resize.step_height) {
 
			const Vehicle *v = this->wagon_list[num - this->vehicle_list.size()];
 
			this->DrawVehicleInDepot(v, r.left, r.right, y);
 
		}
 
@@ -665,21 +665,21 @@ struct DepotWindow : Window {
 
				Dimension unumber = GetStringBoundingBox(STR_BLACK_COMMA);
 
				const Sprite *spr = GetSprite(SPR_FLAG_VEH_STOPPED, ST_NORMAL);
 
				this->flag_width  = UnScaleGUI(spr->width) + WD_FRAMERECT_RIGHT;
 
				this->flag_height = UnScaleGUI(spr->height);
 

	
 
				if (this->type == VEH_TRAIN || this->type == VEH_ROAD) {
 
					min_height = max<uint>(unumber.height + WD_MATRIX_TOP, UnScaleGUI(spr->height));
 
					min_height = std::max<uint>(unumber.height + WD_MATRIX_TOP, UnScaleGUI(spr->height));
 
					this->header_width = unumber.width + this->flag_width + WD_FRAMERECT_LEFT;
 
				} else {
 
					min_height = unumber.height + UnScaleGUI(spr->height) + WD_MATRIX_TOP + WD_PAR_VSEP_NORMAL + WD_MATRIX_BOTTOM;
 
					this->header_width = max<uint>(unumber.width, this->flag_width) + WD_FRAMERECT_RIGHT;
 
					this->header_width = std::max<uint>(unumber.width, this->flag_width) + WD_FRAMERECT_RIGHT;
 
				}
 
				int base_width = this->count_width + this->header_width;
 

	
 
				resize->height = max<uint>(GetVehicleImageCellSize(this->type, EIT_IN_DEPOT).height, min_height);
 
				resize->height = std::max<uint>(GetVehicleImageCellSize(this->type, EIT_IN_DEPOT).height, min_height);
 
				if (this->type == VEH_TRAIN) {
 
					resize->width = 1;
 
					size->width = base_width + 2 * ScaleGUITrad(29); // about 2 parts
 
					size->height = resize->height * 6;
 
				} else {
 
					resize->width = base_width + GetVehicleImageCellSize(this->type, EIT_IN_DEPOT).extend_left + GetVehicleImageCellSize(this->type, EIT_IN_DEPOT).extend_right;
 
@@ -725,13 +725,13 @@ struct DepotWindow : Window {
 
			uint max_width = ScaleGUITrad(VEHICLEINFO_FULL_VEHICLE_WIDTH);
 
			for (uint num = 0; num < this->vehicle_list.size(); num++) {
 
				uint width = 0;
 
				for (const Train *v = Train::From(this->vehicle_list[num]); v != nullptr; v = v->Next()) {
 
					width += v->GetDisplayImageWidth();
 
				}
 
				max_width = max(max_width, width);
 
				max_width = std::max(max_width, width);
 
			}
 
			/* Always have 1 empty row, so people can change the setting of the train */
 
			this->vscroll->SetCount((uint)this->vehicle_list.size() + (uint)this->wagon_list.size() + 1);
 
			/* Always make it longer than the longest train, so you can attach vehicles at the end, and also see the next vertical tile separator line */
 
			this->hscroll->SetCount(max_width + ScaleGUITrad(2 * VEHICLEINFO_FULL_VEHICLE_WIDTH + 1));
 
		} else {
src/disaster_vehicle.cpp
Show inline comments
 
@@ -190,13 +190,13 @@ void DisasterVehicle::UpdatePosition(int
 
	DisasterVehicle *u = this->Next();
 
	if (u != nullptr) {
 
		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 - 1 - (max(z - GetSlopePixelZ(safe_x, safe_y), 0) >> 3);
 
		u->y_pos = y - 1 - (std::max(z - GetSlopePixelZ(safe_x, safe_y), 0) >> 3);
 
		safe_y = Clamp(u->y_pos, 0, MapMaxY() * TILE_SIZE);
 
		u->z_pos = GetSlopePixelZ(safe_x, safe_y);
 
		u->direction = this->direction;
 

	
 
		u->UpdateImage();
 
		u->UpdatePositionAndViewport();
src/dock_gui.cpp
Show inline comments
 
@@ -69,13 +69,13 @@ static TileIndex GetOtherAqueductEnd(Til
 
	 * don't go "off" the map. That would cause the wrong error message. */
 
	if (!IsValidDiagDirection(dir)) return TILE_ADDXY(tile_from, TileX(tile_from) > 2 ? -1 : 1, 0);
 

	
 
	/* Direction the aqueduct is built to. */
 
	TileIndexDiff offset = TileOffsByDiagDir(ReverseDiagDir(dir));
 
	/* The maximum length of the aqueduct. */
 
	int max_length = min(_settings_game.construction.max_bridge_length, DistanceFromEdgeDir(tile_from, ReverseDiagDir(dir)) - 1);
 
	int max_length = std::min<int>(_settings_game.construction.max_bridge_length, DistanceFromEdgeDir(tile_from, ReverseDiagDir(dir)) - 1);
 

	
 
	TileIndex endtile = tile_from;
 
	for (int length = 0; IsValidTile(endtile) && TileX(endtile) != 0 && TileY(endtile) != 0; length++) {
 
		endtile = TILE_ADD(endtile, offset);
 

	
 
		if (length > max_length) break;
src/economy.cpp
Show inline comments
 
@@ -132,13 +132,13 @@ Money CalculateCompanyValue(const Compan
 
	}
 

	
 
	/* Add real money value */
 
	if (including_loan) value -= c->current_loan;
 
	value += c->money;
 

	
 
	return max(value, (Money)1);
 
	return std::max<Money>(value, 1);
 
}
 

	
 
/**
 
 * if update is set to true, the economy is updated with this score
 
 *  (also the house is updated, should only be true in the on-tick event)
 
 * @param update the economy with calculated score
 
@@ -191,34 +191,34 @@ int UpdateCompanyRatingAndValue(Company 
 
		}
 
		_score_part[owner][SCORE_STATIONS] = num;
 
	}
 

	
 
	/* Generate statistics depending on recent income statistics */
 
	{
 
		int numec = min(c->num_valid_stat_ent, 12);
 
		int numec = std::min<uint>(c->num_valid_stat_ent, 12u);
 
		if (numec != 0) {
 
			const CompanyEconomyEntry *cee = c->old_economy;
 
			Money min_income = cee->income + cee->expenses;
 
			Money max_income = cee->income + cee->expenses;
 

	
 
			do {
 
				min_income = min(min_income, cee->income + cee->expenses);
 
				max_income = max(max_income, cee->income + cee->expenses);
 
				min_income = std::min(min_income, cee->income + cee->expenses);
 
				max_income = std::max(max_income, cee->income + cee->expenses);
 
			} while (++cee, --numec);
 

	
 
			if (min_income > 0) {
 
				_score_part[owner][SCORE_MIN_INCOME] = min_income;
 
			}
 

	
 
			_score_part[owner][SCORE_MAX_INCOME] = max_income;
 
		}
 
	}
 

	
 
	/* Generate score depending on amount of transported cargo */
 
	{
 
		int numec = min(c->num_valid_stat_ent, 4);
 
		int numec = std::min<uint>(c->num_valid_stat_ent, 4u);
 
		if (numec != 0) {
 
			const CompanyEconomyEntry *cee = c->old_economy;
 
			OverflowSafeInt64 total_delivered = 0;
 
			do {
 
				total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
 
			} while (++cee, --numec);
 
@@ -358,13 +358,13 @@ void ChangeOwnershipOfCompanyItems(Owner
 
	for (Town *t : Town::Iterate()) {
 
		/* If a company takes over, give the ratings to that company. */
 
		if (new_owner != INVALID_OWNER) {
 
			if (HasBit(t->have_ratings, old_owner)) {
 
				if (HasBit(t->have_ratings, new_owner)) {
 
					/* use max of the two ratings. */
 
					t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
 
					t->ratings[new_owner] = std::max(t->ratings[new_owner], t->ratings[old_owner]);
 
				} else {
 
					SetBit(t->have_ratings, new_owner);
 
					t->ratings[new_owner] = t->ratings[old_owner];
 
				}
 
			}
 
		}
 
@@ -908,18 +908,18 @@ void StartupIndustryDailyChanges(bool in
 
}
 

	
 
void StartupEconomy()
 
{
 
	_economy.interest_rate = _settings_game.difficulty.initial_interest;
 
	_economy.infl_amount = _settings_game.difficulty.initial_interest;
 
	_economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
 
	_economy.infl_amount_pr = std::max(0, _settings_game.difficulty.initial_interest - 1);
 
	_economy.fluct = GB(Random(), 0, 8) + 168;
 

	
 
	if (_settings_game.economy.inflation) {
 
		/* Apply inflation that happened before our game start year. */
 
		int months = (min(_cur_year, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR) * 12;
 
		int months = (std::min(_cur_year, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR) * 12;
 
		for (int i = 0; i < months; i++) {
 
			AddInflation(false);
 
		}
 
	}
 

	
 
	/* Set up prices */
 
@@ -970,13 +970,13 @@ Money GetTransportedGoodsIncome(uint num
 
		/* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
 
		return 0;
 
	}
 

	
 
	/* Use callback to calculate cargo profit, if available */
 
	if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
 
		uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
 
		uint32 var18 = std::min(dist, 0xFFFFu) | (std::min(num_pieces, 0xFFu) << 16) | (transit_days << 24);
 
		uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
 
		if (callback != CALLBACK_FAILED) {
 
			int result = GB(callback, 0, 14);
 

	
 
			/* Simulate a 15 bit signed value */
 
			if (HasBit(callback, 14)) result -= 0x4000;
 
@@ -990,26 +990,26 @@ Money GetTransportedGoodsIncome(uint num
 

	
 
	static const int MIN_TIME_FACTOR = 31;
 
	static const int MAX_TIME_FACTOR = 255;
 

	
 
	const int days1 = cs->transit_days[0];
 
	const int days2 = cs->transit_days[1];
 
	const int days_over_days1 = max(   transit_days - days1, 0);
 
	const int days_over_days2 = max(days_over_days1 - days2, 0);
 
	const int days_over_days1 = std::max(   transit_days - days1, 0);
 
	const int days_over_days2 = std::max(days_over_days1 - days2, 0);
 

	
 
	/*
 
	 * The time factor is calculated based on the time it took
 
	 * (transit_days) compared two cargo-depending values. The
 
	 * range is divided into three parts:
 
	 *
 
	 *  - constant for fast transits
 
	 *  - linear decreasing with time with a slope of -1 for medium transports
 
	 *  - linear decreasing with time with a slope of -2 for slow transports
 
	 *
 
	 */
 
	const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
 
	const int time_factor = std::max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
 

	
 
	return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
 
}
 

	
 
/** The industries we've currently brought cargo to. */
 
static SmallIndustryList _cargo_delivery_destinations;
 
@@ -1052,13 +1052,13 @@ static uint DeliverGoodsToIndustry(const
 

	
 
		if (ind->exclusive_supplier != INVALID_OWNER && ind->exclusive_supplier != st->owner) continue;
 

	
 
		/* Insert the industry into _cargo_delivery_destinations, if not yet contained */
 
		include(_cargo_delivery_destinations, ind);
 

	
 
		uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
 
		uint amount = std::min(num_pieces, 0xFFFFu - ind->incoming_cargo_waiting[cargo_index]);
 
		ind->incoming_cargo_waiting[cargo_index] += amount;
 
		ind->last_cargo_accepted_at[cargo_index] = _date;
 
		num_pieces -= amount;
 
		accepted += amount;
 

	
 
		/* Update the cargo monitor. */
 
@@ -1147,13 +1147,13 @@ static void TriggerIndustryProduction(In
 
	} else {
 
		for (uint ci_in = 0; ci_in < lengthof(i->incoming_cargo_waiting); ci_in++) {
 
			uint cargo_waiting = i->incoming_cargo_waiting[ci_in];
 
			if (cargo_waiting == 0) continue;
 

	
 
			for (uint ci_out = 0; ci_out < lengthof(i->produced_cargo_waiting); ci_out++) {
 
				i->produced_cargo_waiting[ci_out] = min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFF);
 
				i->produced_cargo_waiting[ci_out] = std::min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFFu);
 
			}
 

	
 
			i->incoming_cargo_waiting[ci_in] = 0;
 
		}
 
	}
 

	
 
@@ -1314,13 +1314,13 @@ static uint GetLoadAmount(Vehicle *v)
 
	}
 

	
 
	/* Scale load amount the same as capacity */
 
	if (HasBit(e->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER) && !air_mail) load_amount = CeilDiv(load_amount * CargoSpec::Get(v->cargo_type)->multiplier, 0x100);
 

	
 
	/* Zero load amount breaks a lot of things. */
 
	return max(1u, load_amount);
 
	return std::max(1u, load_amount);
 
}
 

	
 
/**
 
 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
 
 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
 
 * if that action does so. Otherwise return true.
 
@@ -1593,13 +1593,13 @@ static void UpdateLoadUnloadTicks(Vehicl
 
		if (overhang > 0) {
 
			ticks <<= 1;
 
			ticks += (overhang * ticks) / 8;
 
		}
 
	}
 
	/* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
 
	front->load_unload_ticks = max(1, ticks);
 
	front->load_unload_ticks = std::max(1, ticks);
 
}
 

	
 
/**
 
 * Loads/unload the vehicle if possible.
 
 * @param front the vehicle to be (un)loaded
 
 */
 
@@ -1654,13 +1654,13 @@ static void LoadUnloadVehicle(Vehicle *f
 
		artic_part++;
 

	
 
		GoodsEntry *ge = &st->goods[v->cargo_type];
 

	
 
		if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
 
			uint cargo_count = v->cargo.UnloadCount();
 
			uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count;
 
			uint amount_unloaded = _settings_game.order.gradual_loading ? std::min(cargo_count, GetLoadAmount(v)) : cargo_count;
 
			bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
 

	
 
			assert(payment != nullptr);
 
			payment->SetCargo(v->cargo_type);
 

	
 
			if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
 
@@ -1750,14 +1750,14 @@ static void LoadUnloadVehicle(Vehicle *f
 
				break;
 

	
 
			default: NOT_REACHED();
 
		}
 

	
 
		/* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
 
		ge->last_speed = min(t, 255);
 
		ge->last_age = min(_cur_year - front->build_year, 255);
 
		ge->last_speed = std::min(t, 255);
 
		ge->last_age = std::min(_cur_year - front->build_year, 255);
 

	
 
		assert(v->cargo_cap >= v->cargo.StoredCount());
 
		/* Capacity available for loading more cargo. */
 
		uint cap_left = v->cargo_cap - v->cargo.StoredCount();
 

	
 
		if (cap_left > 0) {
 
@@ -1765,13 +1765,13 @@ static void LoadUnloadVehicle(Vehicle *f
 
			ge->time_since_pickup = 0;
 

	
 
			/* If there's goods waiting at the station, and the vehicle
 
			 * has capacity for it, load it on the vehicle. */
 
			if ((v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
 
				if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
 
				if (_settings_game.order.gradual_loading) cap_left = min(cap_left, GetLoadAmount(v));
 
				if (_settings_game.order.gradual_loading) cap_left = std::min(cap_left, GetLoadAmount(v));
 

	
 
				uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
 
				if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
 
					/* Remember if there are reservations left so that we don't stop
 
					 * loading before they're loaded. */
 
					SetBit(reservation_left, v->cargo_type);
 
@@ -1839,13 +1839,13 @@ static void LoadUnloadVehicle(Vehicle *f
 

	
 
			new_load_unload_ticks = gradual_loading_wait_time[front->type];
 
		}
 
		/* We loaded less cargo than possible for all cargo types and it's not full
 
		 * load and we're not supposed to wait any longer: stop loading. */
 
		if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
 
				front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
 
				front->current_order_time >= (uint)std::max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
 
			SetBit(front->vehicle_flags, VF_STOP_LOADING);
 
		}
 

	
 
		UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
 
	} else {
 
		UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
src/elrail.cpp
Show inline comments
 
@@ -226,13 +226,14 @@ static int GetPCPElevation(TileIndex til
 
	 * To catch all cases we round the Z position to the next (TILE_HEIGHT / 2).
 
	 * This will return the correct elevation for slopes and will also detect non-continuous elevation on edges.
 
	 *
 
	 * Also note that the result of GetSlopePixelZ() is very special on bridge-ramps.
 
	 */
 

	
 
	int z = GetSlopePixelZ(TileX(tile) * TILE_SIZE + min(x_pcp_offsets[PCPpos], TILE_SIZE - 1), TileY(tile) * TILE_SIZE + min(y_pcp_offsets[PCPpos], TILE_SIZE - 1));
 
	int z = GetSlopePixelZ(TileX(tile) * TILE_SIZE + std::min<int8>(x_pcp_offsets[PCPpos], TILE_SIZE - 1),
 
	                       TileY(tile) * TILE_SIZE + std::min<int8>(y_pcp_offsets[PCPpos], TILE_SIZE - 1));
 
	return (z + 2) & ~3; // this means z = (z + TILE_HEIGHT / 4) / (TILE_HEIGHT / 2) * (TILE_HEIGHT / 2);
 
}
 

	
 
/**
 
 * Draws wires on a tunnel tile
 
 *
src/engine.cpp
Show inline comments
 
@@ -575,13 +575,13 @@ static void CalcEngineReliability(Engine
 
{
 
	uint age = e->age;
 

	
 
	/* Check for early retirement */
 
	if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
 
		int retire_early = e->info.retire_early;
 
		uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
 
		uint retire_early_max_age = std::max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
 
		if (retire_early != 0 && age >= retire_early_max_age) {
 
			/* Early retirement is enabled and we're past the date... */
 
			e->company_avail = 0;
 
			AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
 
		}
 
	}
 
@@ -622,13 +622,13 @@ void SetYearEngineAgingStops()
 
		if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
 

	
 
		/* Base year ending date on half the model life */
 
		YearMonthDay ymd;
 
		ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
 

	
 
		_year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
 
		_year_engine_aging_stops = std::max(_year_engine_aging_stops, ymd.year);
 
	}
 
}
 

	
 
/**
 
 * Start/initialise one engine.
 
 * @param e The engine to initialise.
 
@@ -690,13 +690,13 @@ void StartupOneEngine(Engine *e, Date ag
 
 * Start/initialise all our engines. Must be called whenever there are changes
 
 * to the NewGRF config.
 
 */
 
void StartupEngines()
 
{
 
	/* Aging of vehicles stops, so account for that when starting late */
 
	const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
 
	const Date aging_date = std::min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
 

	
 
	for (Engine *e : Engine::Iterate()) {
 
		StartupOneEngine(e, aging_date);
 
	}
 

	
 
	/* Update the bitmasks for the vehicle lists */
 
@@ -1193,13 +1193,13 @@ void CheckEngines()
 
		if (!e->IsEnabled()) continue;
 

	
 
		/* We have an available engine... yay! */
 
		if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
 

	
 
		/* Okay, try to find the earliest date. */
 
		min_date = min(min_date, e->info.base_intro);
 
		min_date = std::min(min_date, e->info.base_intro);
 
	}
 

	
 
	if (min_date < INT32_MAX) {
 
		SetDParam(0, min_date);
 
		ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
 
	} else {
src/engine_gui.cpp
Show inline comments
 
@@ -90,15 +90,15 @@ struct EnginePreviewWindow : Window {
 
			default: NOT_REACHED();
 
			case VEH_TRAIN:    GetTrainSpriteSize(   engine, x, y, x_offs, y_offs, image_type); break;
 
			case VEH_ROAD:     GetRoadVehSpriteSize( engine, x, y, x_offs, y_offs, image_type); break;
 
			case VEH_SHIP:     GetShipSpriteSize(    engine, x, y, x_offs, y_offs, image_type); break;
 
			case VEH_AIRCRAFT: GetAircraftSpriteSize(engine, x, y, x_offs, y_offs, image_type); break;
 
		}
 
		this->vehicle_space = max<int>(40, y - y_offs);
 
		this->vehicle_space = std::max<int>(40, y - y_offs);
 

	
 
		size->width = max(size->width, x - x_offs);
 
		size->width = std::max(size->width, x - x_offs);
 
		SetDParam(0, GetEngineCategoryName(engine));
 
		size->height = GetStringHeight(STR_ENGINE_PREVIEW_MESSAGE, size->width) + WD_PAR_VSEP_WIDE + FONT_HEIGHT_NORMAL + this->vehicle_space;
 
		SetDParam(0, engine);
 
		size->height += GetStringHeight(GetEngineInfoString(engine), size->width);
 
	}
 

	
src/error_gui.cpp
Show inline comments
 
@@ -186,28 +186,28 @@ public:
 
	{
 
		switch (widget) {
 
			case WID_EM_MESSAGE: {
 
				CopyInDParam(0, this->decode_params, lengthof(this->decode_params));
 
				if (this->textref_stack_size > 0) StartTextRefStackUsage(this->textref_stack_grffile, this->textref_stack_size, this->textref_stack);
 

	
 
				int text_width = max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
 
				int text_width = std::max(0, (int)size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
 
				this->height_summary = GetStringHeight(this->summary_msg, text_width);
 
				this->height_detailed = (this->detailed_msg == INVALID_STRING_ID) ? 0 : GetStringHeight(this->detailed_msg, text_width);
 

	
 
				if (this->textref_stack_size > 0) StopTextRefStackUsage();
 

	
 
				uint panel_height = WD_FRAMERECT_TOP + this->height_summary + WD_FRAMERECT_BOTTOM;
 
				if (this->detailed_msg != INVALID_STRING_ID) panel_height += this->height_detailed + WD_PAR_VSEP_WIDE;
 

	
 
				size->height = max(size->height, panel_height);
 
				size->height = std::max(size->height, panel_height);
 
				break;
 
			}
 
			case WID_EM_FACE: {
 
				Dimension face_size = GetSpriteSize(SPR_GRADIENT);
 
				size->width = max(size->width, face_size.width);
 
				size->height = max(size->height, face_size.height);
 
				size->width = std::max(size->width, face_size.width);
 
				size->height = std::max(size->height, face_size.height);
 
				break;
 
			}
 
		}
 
	}
 

	
 
	Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
src/fileio.cpp
Show inline comments
 
@@ -21,13 +21,12 @@
 
#include <storage/FindDirectory.h>
 
#else
 
#include <unistd.h>
 
#include <pwd.h>
 
#endif
 
#include <sys/stat.h>
 
#include <algorithm>
 
#include <array>
 
#include <sstream>
 

	
 
#include "safeguards.h"
 

	
 
/** Size of the #Fio data buffer. */
 
@@ -122,13 +121,13 @@ byte FioReadByte()
 
 * Skip \a n bytes ahead in the file.
 
 * @param n Number of bytes to skip reading.
 
 */
 
void FioSkipBytes(int n)
 
{
 
	for (;;) {
 
		int m = min(_fio.buffer_end - _fio.buffer, n);
 
		int m = std::min<int>(_fio.buffer_end - _fio.buffer, n);
 
		_fio.buffer += m;
 
		n -= m;
 
		if (n == 0) break;
 
		FioReadByte();
 
		n--;
 
	}
 
@@ -889,13 +888,13 @@ bool ExtractTar(const std::string &tar_f
 
		}
 

	
 
		/* Now read from the tar and write it into the file. */
 
		char buffer[4096];
 
		size_t read;
 
		for (; to_copy != 0; to_copy -= read) {
 
			read = fread(buffer, 1, min(to_copy, lengthof(buffer)), in.get());
 
			read = fread(buffer, 1, std::min(to_copy, lengthof(buffer)), in.get());
 
			if (read <= 0 || fwrite(buffer, 1, read, out.get()) != read) break;
 
		}
 

	
 
		if (to_copy != 0) {
 
			DEBUG(misc, 6, "Extracting %s failed; still %i bytes to copy", filename.c_str(), (int)to_copy);
 
			return false;
src/fontcache.cpp
Show inline comments
 
@@ -489,13 +489,13 @@ void FreeTypeFontCache::SetFontSize(Font
 

	
 
		TT_Header *head = (TT_Header *)FT_Get_Sfnt_Table(this->face, ft_sfnt_head);
 
		if (head != nullptr) {
 
			/* Font height is minimum height plus the difference between the default
 
			 * height for this font size and the small size. */
 
			int diff = scaled_height - ScaleFontTrad(_default_font_height[FS_SMALL]);
 
			pixels = Clamp(min(head->Lowest_Rec_PPEM, 20) + diff, scaled_height, MAX_FONT_SIZE);
 
			pixels = Clamp(std::min<uint>(head->Lowest_Rec_PPEM, 20u) + diff, scaled_height, MAX_FONT_SIZE);
 
		}
 
	} else {
 
		pixels = ScaleFontTrad(pixels);
 
	}
 
	this->used_size = pixels;
 

	
 
@@ -653,14 +653,14 @@ const Sprite *FreeTypeFontCache::Interna
 
	FT_Render_Glyph(this->face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
 

	
 
	/* Despite requesting a normal glyph, FreeType may have returned a bitmap */
 
	aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
 

	
 
	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
 
	uint width  = max(1U, (uint)slot->bitmap.width + (this->fs == FS_NORMAL));
 
	uint height = max(1U, (uint)slot->bitmap.rows  + (this->fs == FS_NORMAL));
 
	uint width  = std::max(1U, (uint)slot->bitmap.width + (this->fs == FS_NORMAL));
 
	uint height = std::max(1U, (uint)slot->bitmap.rows  + (this->fs == FS_NORMAL));
 

	
 
	/* Limit glyph size to prevent overflows later on. */
 
	if (width > 256 || height > 256) usererror("Font glyph is too large");
 

	
 
	/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
 
	SpriteLoader::Sprite sprite;
 
@@ -794,13 +794,13 @@ void Win32FontCache::SetFontSize(FontSiz
 
			LPOUTLINETEXTMETRIC otm = (LPOUTLINETEXTMETRIC)AllocaM(BYTE, size);
 
			GetOutlineTextMetrics(this->dc, size, otm);
 

	
 
			/* Font height is minimum height plus the difference between the default
 
			 * height for this font size and the small size. */
 
			int diff = scaled_height - ScaleFontTrad(_default_font_height[FS_SMALL]);
 
			pixels = Clamp(min(otm->otmusMinimumPPEM, 20) + diff, scaled_height, MAX_FONT_SIZE);
 
			pixels = Clamp(std::min(otm->otmusMinimumPPEM, 20u) + diff, scaled_height, MAX_FONT_SIZE);
 

	
 
			SelectObject(dc, old);
 
			DeleteObject(temp);
 
		}
 
	} else {
 
		pixels = ScaleFontTrad(pixels);
 
@@ -848,13 +848,13 @@ void Win32FontCache::ClearFontCache()
 
/* virtual */ const Sprite *Win32FontCache::InternalGetGlyph(GlyphID key, bool aa)
 
{
 
	GLYPHMETRICS gm;
 
	MAT2 mat = { {0, 1}, {0, 0}, {0, 0}, {0, 1} };
 

	
 
	/* Make a guess for the needed memory size. */
 
	DWORD size = this->glyph_size.cy * Align(aa ? this->glyph_size.cx : max(this->glyph_size.cx / 8l, 1l), 4); // Bitmap data is DWORD-aligned rows.
 
	DWORD size = this->glyph_size.cy * Align(aa ? this->glyph_size.cx : std::max(this->glyph_size.cx / 8l, 1l), 4); // Bitmap data is DWORD-aligned rows.
 
	byte *bmp = AllocaM(byte, size);
 
	size = GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, size, bmp, &mat);
 

	
 
	if (size == GDI_ERROR) {
 
		/* No dice with the guess. First query size of needed glyph memory, then allocate the
 
		 * memory and query again. This dance is necessary as some glyphs will only render with
 
@@ -865,14 +865,14 @@ void Win32FontCache::ClearFontCache()
 
		if (size == GDI_ERROR) usererror("Unable to render font glyph");
 
		bmp = AllocaM(byte, size);
 
		GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, size, bmp, &mat);
 
	}
 

	
 
	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel. */
 
	uint width = max(1U, (uint)gm.gmBlackBoxX + (this->fs == FS_NORMAL));
 
	uint height = max(1U, (uint)gm.gmBlackBoxY + (this->fs == FS_NORMAL));
 
	uint width = std::max(1U, (uint)gm.gmBlackBoxX + (this->fs == FS_NORMAL));
 
	uint height = std::max(1U, (uint)gm.gmBlackBoxY + (this->fs == FS_NORMAL));
 

	
 
	/* Limit glyph size to prevent overflows later on. */
 
	if (width > 256 || height > 256) usererror("Font glyph is too large");
 

	
 
	/* GDI has rendered the glyph, now we allocate a sprite and copy the image into it. */
 
	SpriteLoader::Sprite sprite;
 
@@ -886,13 +886,13 @@ void Win32FontCache::ClearFontCache()
 
	if (size > 0) {
 
		/* All pixel data returned by GDI is in the form of DWORD-aligned rows.
 
		 * For a non anti-aliased glyph, the returned bitmap has one bit per pixel.
 
		 * For anti-aliased rendering, GDI uses the strange value range of 0 to 64,
 
		 * inclusively. To map this to 0 to 255, we shift left by two and then
 
		 * subtract one. */
 
		uint pitch = Align(aa ? gm.gmBlackBoxX : max(gm.gmBlackBoxX / 8u, 1u), 4);
 
		uint pitch = Align(aa ? gm.gmBlackBoxX : std::max(gm.gmBlackBoxX / 8u, 1u), 4);
 

	
 
		/* Draw shadow for medium size. */
 
		if (this->fs == FS_NORMAL && !aa) {
 
			for (uint y = 0; y < gm.gmBlackBoxY; y++) {
 
				for (uint x = 0; x < gm.gmBlackBoxX; x++) {
 
					if (aa ? (bmp[x + y * pitch] > 0) : HasBit(bmp[(x / 8) + y * pitch], 7 - (x % 8))) {
src/fontdetection.cpp
Show inline comments
 
@@ -219,13 +219,13 @@ static const char *GetEnglishFontName(co
 
		length = buf[pos++] << 8;
 
		length += buf[pos++];
 
		offset = buf[pos++] << 8;
 
		offset += buf[pos++];
 

	
 
		/* Don't buffer overflow */
 
		length = min(length, MAX_PATH - 1);
 
		length = std::min(length, MAX_PATH - 1);
 
		for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j];
 
		font_name[length] = '\0';
 

	
 
		if ((platformId == 1 && languageId == 0) ||      // Macintosh English
 
				(platformId == 3 && languageId == 0x0409)) { // Microsoft English (US)
 
			ret_font_name = font_name;
src/framerate_gui.cpp
Show inline comments
 
@@ -73,24 +73,24 @@ namespace {
 
		{
 
			this->durations[this->next_index] = end_time - start_time;
 
			this->timestamps[this->next_index] = start_time;
 
			this->prev_index = this->next_index;
 
			this->next_index += 1;
 
			if (this->next_index >= NUM_FRAMERATE_POINTS) this->next_index = 0;
 
			this->num_valid = min(NUM_FRAMERATE_POINTS, this->num_valid + 1);
 
			this->num_valid = std::min(NUM_FRAMERATE_POINTS, this->num_valid + 1);
 
		}
 

	
 
		/** Begin an accumulation of multiple measurements into a single value, from a given start time */
 
		void BeginAccumulate(TimingMeasurement start_time)
 
		{
 
			this->timestamps[this->next_index] = this->acc_timestamp;
 
			this->durations[this->next_index] = this->acc_duration;
 
			this->prev_index = this->next_index;
 
			this->next_index += 1;
 
			if (this->next_index >= NUM_FRAMERATE_POINTS) this->next_index = 0;
 
			this->num_valid = min(NUM_FRAMERATE_POINTS, this->num_valid + 1);
 
			this->num_valid = std::min(NUM_FRAMERATE_POINTS, this->num_valid + 1);
 

	
 
			this->acc_duration = 0;
 
			this->acc_timestamp = start_time;
 
		}
 

	
 
		/** Accumulate a period onto the current measurement */
 
@@ -112,13 +112,13 @@ namespace {
 
			}
 
		}
 

	
 
		/** Get average cycle processing time over a number of data points */
 
		double GetAverageDurationMilliseconds(int count)
 
		{
 
			count = min(count, this->num_valid);
 
			count = std::min(count, this->num_valid);
 

	
 
			int first_point = this->prev_index - count;
 
			if (first_point < 0) first_point += NUM_FRAMERATE_POINTS;
 

	
 
			/* Sum durations, skipping invalid points */
 
			double sumtime = 0;
 
@@ -392,22 +392,22 @@ struct FramerateWindow : Window {
 
		uint32 value;
 

	
 
		inline void SetRate(double value, double target)
 
		{
 
			const double threshold_good = target * 0.95;
 
			const double threshold_bad = target * 2 / 3;
 
			value = min(9999.99, value);
 
			value = std::min(9999.99, value);
 
			this->value = (uint32)(value * 100);
 
			this->strid = (value > threshold_good) ? STR_FRAMERATE_FPS_GOOD : (value < threshold_bad) ? STR_FRAMERATE_FPS_BAD : STR_FRAMERATE_FPS_WARN;
 
		}
 

	
 
		inline void SetTime(double value, double target)
 
		{
 
			const double threshold_good = target / 3;
 
			const double threshold_bad = target;
 
			value = min(9999.99, value);
 
			value = std::min(9999.99, value);
 
			this->value = (uint32)(value * 100);
 
			this->strid = (value < threshold_good) ? STR_FRAMERATE_MS_GOOD : (value > threshold_bad) ? STR_FRAMERATE_MS_BAD : STR_FRAMERATE_MS_WARN;
 
		}
 

	
 
		inline void InsertDParams(uint n) const
 
		{
 
@@ -419,26 +419,26 @@ struct FramerateWindow : Window {
 
	CachedDecimal rate_gameloop;            ///< cached game loop tick rate
 
	CachedDecimal rate_drawing;             ///< cached drawing frame rate
 
	CachedDecimal speed_gameloop;           ///< cached game loop speed factor
 
	CachedDecimal times_shortterm[PFE_MAX]; ///< cached short term average times
 
	CachedDecimal times_longterm[PFE_MAX];  ///< cached long term average times
 

	
 
	static const int VSPACING = 3;          ///< space between column heading and values
 
	static const int MIN_ELEMENTS = 5;      ///< smallest number of elements to display
 
	static constexpr int VSPACING = 3;          ///< space between column heading and values
 
	static constexpr int MIN_ELEMENTS = 5;      ///< smallest number of elements to display
 

	
 
	FramerateWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
 
	{
 
		this->InitNested(number);
 
		this->small = this->IsShaded();
 
		this->showing_memory = true;
 
		this->UpdateData();
 
		this->num_displayed = this->num_active;
 
		this->next_update.SetInterval(100);
 

	
 
		/* Window is always initialised to MIN_ELEMENTS height, resize to contain num_displayed */
 
		ResizeWindow(this, 0, (max(MIN_ELEMENTS, this->num_displayed) - MIN_ELEMENTS) * FONT_HEIGHT_NORMAL);
 
		ResizeWindow(this, 0, (std::max(MIN_ELEMENTS, this->num_displayed) - MIN_ELEMENTS) * FONT_HEIGHT_NORMAL);
 
	}
 

	
 
	void OnRealtimeTick(uint delta_ms) override
 
	{
 
		bool elapsed = this->next_update.Elapsed(delta_ms);
 

	
 
@@ -483,13 +483,13 @@ struct FramerateWindow : Window {
 
		}
 

	
 
		if (new_active != this->num_active) {
 
			this->num_active = new_active;
 
			Scrollbar *sb = this->GetScrollbar(WID_FRW_SCROLLBAR);
 
			sb->SetCount(this->num_active);
 
			sb->SetCapacity(min(this->num_displayed, this->num_active));
 
			sb->SetCapacity(std::min(this->num_displayed, this->num_active));
 
			this->ReInit();
 
		}
 
	}
 

	
 
	void SetStringParameters(int widget) const override
 
	{
 
@@ -552,25 +552,25 @@ struct FramerateWindow : Window {
 
						line_size = GetStringBoundingBox(STR_FRAMERATE_GAMELOOP + e);
 
					} else {
 
						SetDParam(0, e - PFE_AI0 + 1);
 
						SetDParamStr(1, GetAIName(e - PFE_AI0));
 
						line_size = GetStringBoundingBox(STR_FRAMERATE_AI);
 
					}
 
					size->width = max(size->width, line_size.width);
 
					size->width = std::max(size->width, line_size.width);
 
				}
 
				break;
 
			}
 

	
 
			case WID_FRW_TIMES_CURRENT:
 
			case WID_FRW_TIMES_AVERAGE:
 
			case WID_FRW_ALLOCSIZE: {
 
				*size = GetStringBoundingBox(STR_FRAMERATE_CURRENT + (widget - WID_FRW_TIMES_CURRENT));
 
				SetDParam(0, 999999);
 
				SetDParam(1, 2);
 
				Dimension item_size = GetStringBoundingBox(STR_FRAMERATE_MS_GOOD);
 
				size->width = max(size->width, item_size.width);
 
				size->width = std::max(size->width, item_size.width);
 
				size->height += FONT_HEIGHT_NORMAL * MIN_ELEMENTS + VSPACING;
 
				resize->width = 0;
 
				resize->height = FONT_HEIGHT_NORMAL;
 
				break;
 
			}
 
		}
 
@@ -766,13 +766,13 @@ struct FrametimeGraphWindow : Window {
 
			SetDParam(0, 100);
 
			Dimension size_ms_label = GetStringBoundingBox(STR_FRAMERATE_GRAPH_MILLISECONDS);
 
			SetDParam(0, 100);
 
			Dimension size_s_label = GetStringBoundingBox(STR_FRAMERATE_GRAPH_SECONDS);
 

	
 
			/* Size graph in height to fit at least 10 vertical labels with space between, or at least 100 pixels */
 
			graph_size.height = max<uint>(100, 10 * (size_ms_label.height + 1));
 
			graph_size.height = std::max(100u, 10 * (size_ms_label.height + 1));
 
			/* Always 2:1 graph area */
 
			graph_size.width = 2 * graph_size.height;
 
			*size = graph_size;
 

	
 
			size->width += size_ms_label.width + 2;
 
			size->height += size_s_label.height + 2;
 
@@ -977,13 +977,13 @@ struct FrametimeGraphWindow : Window {
 

	
 
			/* If the peak value is significantly larger than the average, mark and label it */
 
			if (points_drawn > 0 && peak_value > TIMESTAMP_PRECISION / 100 && 2 * peak_value > 3 * value_sum / points_drawn) {
 
				TextColour tc_peak = (TextColour)(TC_IS_PALETTE_COLOUR | c_peak);
 
				GfxFillRect(peak_point.x - 1, peak_point.y - 1, peak_point.x + 1, peak_point.y + 1, c_peak);
 
				SetDParam(0, peak_value * 1000 / TIMESTAMP_PRECISION);
 
				int label_y = max(y_max, peak_point.y - FONT_HEIGHT_SMALL);
 
				int label_y = std::max(y_max, peak_point.y - FONT_HEIGHT_SMALL);
 
				if (peak_point.x - x_zero > (int)this->graph_size.width / 2) {
 
					DrawString(x_zero, peak_point.x - 2, label_y, STR_FRAMERATE_GRAPH_MILLISECONDS, tc_peak, SA_RIGHT | SA_FORCE, false, FS_SMALL);
 
				} else {
 
					DrawString(peak_point.x + 2, x_max, label_y, STR_FRAMERATE_GRAPH_MILLISECONDS, tc_peak, SA_LEFT | SA_FORCE, false, FS_SMALL);
 
				}
 
			}
src/gamelog.cpp
Show inline comments
 
@@ -811,13 +811,13 @@ void GamelogInfo(LoggedAction *gamelog_a
 
		for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
 
			switch (lc->ct) {
 
				default: break;
 

	
 
				case GLCT_REVISION:
 
					*last_ottd_rev = lc->revision.newgrf;
 
					*ever_modified = max(*ever_modified, lc->revision.modified);
 
					*ever_modified = std::max(*ever_modified, lc->revision.modified);
 
					break;
 

	
 
				case GLCT_GRFREM:
 
					*removed_newgrfs = true;
 
					break;
 
			}
src/genworld_gui.cpp
Show inline comments
 
@@ -510,13 +510,13 @@ struct GenerateLandscapeWindow : public 
 
		if (strs != nullptr) {
 
			while (*strs != INVALID_STRING_ID) {
 
				*size = maxdim(*size, GetStringBoundingBox(*strs++));
 
			}
 
		}
 
		size->width += padding.width;
 
		size->height = max(size->height, (uint)(FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM));
 
		size->height = std::max(size->height, (uint)(FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM));
 
	}
 

	
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
		switch (widget) {
 
			case WID_GL_HEIGHTMAP_NAME_TEXT: {
 
@@ -1211,13 +1211,13 @@ struct GenerateProgressWindow : public W
 
				size->width += 8;
 
				break;
 
			}
 

	
 
			case WID_GP_PROGRESS_TEXT:
 
				for (uint i = 0; i < GWP_CLASS_COUNT; i++) {
 
					size->width = max(size->width, GetStringBoundingBox(_generation_class_table[i]).width);
 
					size->width = std::max(size->width, GetStringBoundingBox(_generation_class_table[i]).width);
 
				}
 
				size->height = FONT_HEIGHT_NORMAL * 2 + WD_PAR_VSEP_NORMAL;
 
				break;
 
		}
 
	}
 

	
src/gfx.cpp
Show inline comments
 
@@ -260,14 +260,14 @@ void GfxFillPolygon(const std::vector<Po
 
		}
 

	
 
		/* Fill between pairs of intersections. */
 
		std::sort(intersections.begin(), intersections.end());
 
		for (size_t i = 1; i < intersections.size(); i += 2) {
 
			/* Check clipping. */
 
			const int x1 = max(0, intersections[i - 1]);
 
			const int x2 = min(intersections[i], dpi->width);
 
			const int x1 = std::max(0, intersections[i - 1]);
 
			const int x2 = std::min(intersections[i], dpi->width);
 
			if (x2 < 0) continue;
 
			if (x1 >= dpi->width) continue;
 

	
 
			/* Fill line y from x1 to x2. */
 
			void *dst = blitter->MoveTo(dpi->dst_ptr, x1, y);
 
			switch (mode) {
 
@@ -324,13 +324,13 @@ static inline void GfxDoDrawLine(void *v
 
	/* Clipping rectangle. Slightly extended so we can ignore the width of the line. */
 
	int extra = (int)CeilDiv(3 * width, 4); // not less then "width * sqrt(2) / 2"
 
	Rect clip = { -extra, -extra, screen_width - 1 + extra, screen_height - 1 + extra };
 

	
 
	/* prevent integer overflows. */
 
	int margin = 1;
 
	while (INT_MAX / abs(grade_y) < max(abs(clip.left - x), abs(clip.right - x))) {
 
	while (INT_MAX / abs(grade_y) < std::max(abs(clip.left - x), abs(clip.right - x))) {
 
		grade_y /= 2;
 
		grade_x /= 2;
 
		margin  *= 2; // account for rounding errors
 
	}
 

	
 
	/* Imagine that the line is infinitely long and it intersects with
 
@@ -633,13 +633,13 @@ static int DrawLayoutLine(const Paragrap
 
 * @return In case of left or center alignment the right most pixel we have drawn to.
 
 *         In case of right alignment the left most pixel we have drawn to.
 
 */
 
int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
 
{
 
	/* The string may contain control chars to change the font, just use the biggest font for clipping. */
 
	int max_height = max(max(FONT_HEIGHT_SMALL, FONT_HEIGHT_NORMAL), max(FONT_HEIGHT_LARGE, FONT_HEIGHT_MONO));
 
	int max_height = std::max({FONT_HEIGHT_SMALL, FONT_HEIGHT_NORMAL, FONT_HEIGHT_LARGE, FONT_HEIGHT_MONO});
 

	
 
	/* Funny glyphs may extent outside the usual bounds, so relax the clipping somewhat. */
 
	int extra = max_height / 2;
 

	
 
	if (_cur_dpi->top + _cur_dpi->height + extra < top || _cur_dpi->top > top + max_height + extra ||
 
			_cur_dpi->left + _cur_dpi->width + extra < left || _cur_dpi->left > right + extra) {
 
@@ -913,14 +913,14 @@ Dimension GetSpriteSize(SpriteID sprid, 
 
	if (offset != nullptr) {
 
		offset->x = UnScaleByZoom(sprite->x_offs, zoom);
 
		offset->y = UnScaleByZoom(sprite->y_offs, zoom);
 
	}
 

	
 
	Dimension d;
 
	d.width  = max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
 
	d.height = max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
 
	d.width  = std::max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
 
	d.height = std::max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
 
	return d;
 
}
 

	
 
/**
 
 * Helper function to get the blitter mode for different types of palettes.
 
 * @param pal The palette to get the blitter mode for.
 
@@ -1021,16 +1021,16 @@ static void GfxBlitter(const Sprite * co
 
		bp.skip_left = 0;
 
		bp.skip_top = 0;
 
		bp.width = UnScaleByZoom(sprite->width, zoom);
 
		bp.height = UnScaleByZoom(sprite->height, zoom);
 
	} else {
 
		/* Amount of pixels to clip from the source sprite */
 
		int clip_left   = max(0,                   -sprite->x_offs +  sub->left        * ZOOM_BASE );
 
		int clip_top    = max(0,                   -sprite->y_offs +  sub->top         * ZOOM_BASE );
 
		int clip_right  = max(0, sprite->width  - (-sprite->x_offs + (sub->right + 1)  * ZOOM_BASE));
 
		int clip_bottom = max(0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_BASE));
 
		int clip_left   = std::max(0,                   -sprite->x_offs +  sub->left        * ZOOM_BASE );
 
		int clip_top    = std::max(0,                   -sprite->y_offs +  sub->top         * ZOOM_BASE );
 
		int clip_right  = std::max(0, sprite->width  - (-sprite->x_offs + (sub->right + 1)  * ZOOM_BASE));
 
		int clip_bottom = std::max(0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_BASE));
 

	
 
		if (clip_left + clip_right >= sprite->width) return;
 
		if (clip_top + clip_bottom >= sprite->height) return;
 

	
 
		bp.skip_left = UnScaleByZoomLower(clip_left, zoom);
 
		bp.skip_top = UnScaleByZoomLower(clip_top, zoom);
 
@@ -1302,13 +1302,13 @@ byte GetCharacterWidth(FontSize size, WC
 
 * @return Width of the digit.
 
 */
 
byte GetDigitWidth(FontSize size)
 
{
 
	byte width = 0;
 
	for (char c = '0'; c <= '9'; c++) {
 
		width = max(GetCharacterWidth(size, c), width);
 
		width = std::max(GetCharacterWidth(size, c), width);
 
	}
 
	return width;
 
}
 

	
 
/**
 
 * Determine the broadest digits for guessing the maximum width of a n-digit number.
 
@@ -1692,14 +1692,14 @@ void UpdateCursorSize()
 
		size.y = UnScaleGUI(p->height);
 

	
 
		if (i == 0) {
 
			_cursor.total_offs = offs;
 
			_cursor.total_size = size;
 
		} else {
 
			int right  = max(_cursor.total_offs.x + _cursor.total_size.x, offs.x + size.x);
 
			int bottom = max(_cursor.total_offs.y + _cursor.total_size.y, offs.y + size.y);
 
			int right  = std::max(_cursor.total_offs.x + _cursor.total_size.x, offs.x + size.x);
 
			int bottom = std::max(_cursor.total_offs.y + _cursor.total_size.y, offs.y + size.y);
 
			if (offs.x < _cursor.total_offs.x) _cursor.total_offs.x = offs.x;
 
			if (offs.y < _cursor.total_offs.y) _cursor.total_offs.y = offs.y;
 
			_cursor.total_size.x = right  - _cursor.total_offs.x;
 
			_cursor.total_size.y = bottom - _cursor.total_offs.y;
 
		}
 
	}
src/gfx_layout.cpp
Show inline comments
 
@@ -428,13 +428,13 @@ int FallbackParagraphLayout::FallbackVis
 
 * @return The maximum height of the line.
 
 */
 
int FallbackParagraphLayout::FallbackLine::GetLeading() const
 
{
 
	int leading = 0;
 
	for (const auto &run : *this) {
 
		leading = max(leading, run.GetLeading());
 
		leading = std::max(leading, run.GetLeading());
 
	}
 

	
 
	return leading;
 
}
 

	
 
/**
 
@@ -744,13 +744,13 @@ Layouter::Layouter(const char *str, int 
 
 * @return The boundaries.
 
 */
 
Dimension Layouter::GetBounds()
 
{
 
	Dimension d = { 0, 0 };
 
	for (const auto &l : *this) {
 
		d.width = max<uint>(d.width, l->GetWidth());
 
		d.width = std::max<uint>(d.width, l->GetWidth());
 
		d.height += l->GetLeading();
 
	}
 
	return d;
 
}
 

	
 
/**
src/gfxinit.cpp
Show inline comments
 
@@ -402,13 +402,13 @@ MD5File::ChecksumResult MD5File::CheckMD
 
{
 
	size_t size;
 
	FILE *f = FioFOpenFile(this->filename, "rb", subdir, &size);
 

	
 
	if (f == nullptr) return CR_NO_FILE;
 

	
 
	size = min(size, max_size);
 
	size = std::min(size, max_size);
 

	
 
	Md5 checksum;
 
	uint8 buffer[1024];
 
	uint8 digest[16];
 
	size_t len;
 

	
src/goal_gui.cpp
Show inline comments
 
@@ -288,13 +288,13 @@ struct GoalListWindow : public Window {
 
				uint str_width = GetStringBoundingBox(str).width;
 
				if (str_width > max_width) max_width = str_width;
 
			}
 
		}
 

	
 
		NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_GOAL_LIST);
 
		uint progress_col_width = min(max_width, wid->current_x);
 
		uint progress_col_width = std::min(max_width, wid->current_x);
 

	
 
		/* Draw goal list. */
 
		this->DrawListColumn(GC_PROGRESS, wid, progress_col_width);
 
		this->DrawListColumn(GC_GOAL, wid, progress_col_width);
 

	
 
	}
src/graph_gui.cpp
Show inline comments
 
@@ -107,13 +107,13 @@ struct GraphLegendWindow : Window {
 
 * @return Panel with company buttons.
 
 * @post \c *biggest_index contains the largest used index in the tree.
 
 */
 
static NWidgetBase *MakeNWidgetCompanyLines(int *biggest_index)
 
{
 
	NWidgetVertical *vert = new NWidgetVertical();
 
	uint line_height = max<uint>(GetSpriteSize(SPR_COMPANY_ICON).height, FONT_HEIGHT_NORMAL) + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
 
	uint line_height = std::max<uint>(GetSpriteSize(SPR_COMPANY_ICON).height, FONT_HEIGHT_NORMAL) + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
 

	
 
	for (int widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
 
		NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
 
		panel->SetMinimalSize(246, line_height);
 
		panel->SetFill(1, 0);
 
		panel->SetDataTip(0x0, STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
 
@@ -209,14 +209,14 @@ protected:
 
		for (int i = 0; i < this->num_dataset; i++) {
 
			if (HasBit(this->excluded_data, i)) continue;
 
			for (int j = 0; j < this->num_on_x_axis; j++) {
 
				OverflowSafeInt64 datapoint = this->cost[i][j];
 

	
 
				if (datapoint != INVALID_DATAPOINT) {
 
					current_interval.highest = max(current_interval.highest, datapoint);
 
					current_interval.lowest  = min(current_interval.lowest, datapoint);
 
					current_interval.highest = std::max(current_interval.highest, datapoint);
 
					current_interval.lowest  = std::min(current_interval.lowest, datapoint);
 
				}
 
			}
 
		}
 

	
 
		/* Prevent showing values too close to the graph limits. */
 
		current_interval.highest = (11 * current_interval.highest) / 10;
 
@@ -237,13 +237,13 @@ protected:
 
			if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
 
			if (num_pos_grids == num_hori_lines && abs_lower != 0) num_pos_grids--;
 

	
 
			/* Get the required grid size for each side and use the maximum one. */
 
			int64 grid_size_higher = (abs_higher > 0) ? ((int64)abs_higher + num_pos_grids - 1) / num_pos_grids : 0;
 
			int64 grid_size_lower = (abs_lower > 0) ? ((int64)abs_lower + num_hori_lines - num_pos_grids - 1) / (num_hori_lines - num_pos_grids) : 0;
 
			grid_size = max(grid_size_higher, grid_size_lower);
 
			grid_size = std::max(grid_size_higher, grid_size_lower);
 
		} else {
 
			/* If both values are zero, show an empty graph. */
 
			num_pos_grids = num_hori_lines / 2;
 
			grid_size = 1;
 
		}
 

	
 
@@ -432,13 +432,13 @@ protected:
 
						 *
 
						 * If there are more bits needed than would fit in a 32 bits
 
						 * integer, so at about 31 bits because of the sign bit, the
 
						 * least significant bits are removed.
 
						 */
 
						int mult_range = FindLastBit(x_axis_offset) + FindLastBit(abs(datapoint));
 
						int reduce_range = max(mult_range - 31, 0);
 
						int reduce_range = std::max(mult_range - 31, 0);
 

	
 
						/* Handle negative values differently (don't shift sign) */
 
						if (datapoint < 0) {
 
							datapoint = -(abs(datapoint) >> reduce_range);
 
						} else {
 
							datapoint >>= reduce_range;
 
@@ -493,13 +493,13 @@ public:
 
			byte month = this->month;
 
			Year year  = this->year;
 
			for (int i = 0; i < this->num_on_x_axis; i++) {
 
				SetDParam(0, month + STR_MONTH_ABBREV_JAN);
 
				SetDParam(1, month + STR_MONTH_ABBREV_JAN + 2);
 
				SetDParam(2, year);
 
				x_label_width = max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
 
				x_label_width = std::max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
 

	
 
				month += 3;
 
				if (month >= 12) {
 
					month = 0;
 
					year++;
 
				}
 
@@ -511,15 +511,15 @@ public:
 
		}
 

	
 
		SetDParam(0, this->format_str_y_axis);
 
		SetDParam(1, INT64_MAX);
 
		uint y_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL).width;
 

	
 
		size->width  = max<uint>(size->width,  5 + y_label_width + this->num_on_x_axis * (x_label_width + 5) + 9);
 
		size->height = max<uint>(size->height, 5 + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->month != 0xFF ? 3 : 1)) * FONT_HEIGHT_SMALL + 4);
 
		size->height = max<uint>(size->height, size->width / 3);
 
		size->width  = std::max<uint>(size->width,  5 + y_label_width + this->num_on_x_axis * (x_label_width + 5) + 9);
 
		size->height = std::max<uint>(size->height, 5 + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->month != 0xFF ? 3 : 1)) * FONT_HEIGHT_SMALL + 4);
 
		size->height = std::max<uint>(size->height, size->width / 3);
 
	}
 

	
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
		if (widget != this->graph_widget) return;
 

	
 
@@ -565,13 +565,13 @@ public:
 
		for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
 
			if (!Company::IsValidID(c)) SetBit(excluded_companies, c);
 
		}
 

	
 
		byte nums = 0;
 
		for (const Company *c : Company::Iterate()) {
 
			nums = min(this->num_vert_lines, max(nums, c->num_valid_stat_ent));
 
			nums = std::min(this->num_vert_lines, std::max(nums, c->num_valid_stat_ent));
 
		}
 

	
 
		int mo = (_cur_month / 3 - nums) * 3;
 
		int yr = _cur_year;
 
		while (mo < 0) {
 
			yr--;
 
@@ -1112,13 +1112,13 @@ static const StringID _performance_title
 
	STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_PRESIDENT,
 
	STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TYCOON,
 
};
 

	
 
static inline StringID GetPerformanceTitleFromValue(uint value)
 
{
 
	return _performance_titles[minu(value, 1000) >> 6];
 
	return _performance_titles[std::min(value, 1000u) >> 6];
 
}
 

	
 
class CompanyLeagueWindow : public Window {
 
private:
 
	GUIList<const Company*> companies;
 
	uint ordinal_width; ///< The width of the ordinal number
 
@@ -1196,13 +1196,13 @@ public:
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		if (widget != WID_CL_BACKGROUND) return;
 

	
 
		this->ordinal_width = 0;
 
		for (uint i = 0; i < MAX_COMPANIES; i++) {
 
			this->ordinal_width = max(this->ordinal_width, GetStringBoundingBox(STR_ORDINAL_NUMBER_1ST + i).width);
 
			this->ordinal_width = std::max(this->ordinal_width, GetStringBoundingBox(STR_ORDINAL_NUMBER_1ST + i).width);
 
		}
 
		this->ordinal_width += 5; // Keep some extra spacing
 

	
 
		uint widest_width = 0;
 
		uint widest_title = 0;
 
		for (uint i = 0; i < lengthof(_performance_titles); i++) {
 
@@ -1212,19 +1212,19 @@ public:
 
				widest_width = width;
 
			}
 
		}
 

	
 
		Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
 
		this->icon_width = d.width + 2;
 
		this->line_height = max<int>(d.height + 2, FONT_HEIGHT_NORMAL);
 
		this->line_height = std::max<int>(d.height + 2, FONT_HEIGHT_NORMAL);
 

	
 
		for (const Company *c : Company::Iterate()) {
 
			SetDParam(0, c->index);
 
			SetDParam(1, c->index);
 
			SetDParam(2, _performance_titles[widest_title]);
 
			widest_width = max(widest_width, GetStringBoundingBox(STR_COMPANY_LEAGUE_COMPANY_NAME).width);
 
			widest_width = std::max(widest_width, GetStringBoundingBox(STR_COMPANY_LEAGUE_COMPANY_NAME).width);
 
		}
 

	
 
		this->text_width = widest_width + 30; // Keep some extra spacing
 

	
 
		size->width = WD_FRAMERECT_LEFT + this->ordinal_width + WD_FRAMERECT_RIGHT + this->icon_width + WD_FRAMERECT_LEFT + this->text_width + WD_FRAMERECT_RIGHT;
 
		size->height = WD_FRAMERECT_TOP + this->line_height * MAX_COMPANIES + WD_FRAMERECT_BOTTOM;
 
@@ -1318,13 +1318,13 @@ struct PerformanceRatingDetailWindow : W
 
			case WID_PRD_SCORE_FIRST:
 
				this->bar_height = FONT_HEIGHT_NORMAL + 4;
 
				size->height = this->bar_height + 2 * WD_MATRIX_TOP;
 

	
 
				uint score_info_width = 0;
 
				for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
 
					score_info_width = max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
 
					score_info_width = std::max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
 
				}
 
				SetDParamMaxValue(0, 1000);
 
				score_info_width += GetStringBoundingBox(STR_BLACK_COMMA).width + WD_FRAMERECT_LEFT;
 

	
 
				SetDParamMaxValue(0, 100);
 
				this->bar_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_PERCENT).width + 20; // Wide bars!
src/ground_vehicle.cpp
Show inline comments
 
@@ -35,23 +35,23 @@ void GroundVehicle<T, Type>::PowerChange
 
		/* Only powered parts add tractive effort. */
 
		if (current_power > 0) max_te += u->GetWeight() * u->GetTractiveEffort();
 
		number_of_parts++;
 

	
 
		/* Get minimum max speed for this track. */
 
		uint16 track_speed = u->GetMaxTrackSpeed();
 
		if (track_speed > 0) max_track_speed = min(max_track_speed, track_speed);
 
		if (track_speed > 0) max_track_speed = std::min(max_track_speed, track_speed);
 
	}
 

	
 
	byte air_drag;
 
	byte air_drag_value = v->GetAirDrag();
 

	
 
	/* If air drag is set to zero (default), the resulting air drag coefficient is dependent on max speed. */
 
	if (air_drag_value == 0) {
 
		uint16 max_speed = v->GetDisplayMaxSpeed();
 
		/* Simplification of the method used in TTDPatch. It uses <= 10 to change more steadily from 128 to 196. */
 
		air_drag = (max_speed <= 10) ? 192 : max(2048 / max_speed, 1);
 
		air_drag = (max_speed <= 10) ? 192 : std::max(2048 / max_speed, 1);
 
	} else {
 
		/* According to the specs, a value of 0x01 in the air drag property means "no air drag". */
 
		air_drag = (air_drag_value == 1) ? 0 : air_drag_value;
 
	}
 

	
 
	this->gcache.cached_air_drag = air_drag + 3 * air_drag * number_of_parts / 20;
 
@@ -86,13 +86,13 @@ void GroundVehicle<T, Type>::CargoChange
 
		weight += current_weight;
 
		/* Slope steepness is in percent, result in N. */
 
		u->gcache.cached_slope_resistance = current_weight * u->GetSlopeSteepness() * 100;
 
	}
 

	
 
	/* Store consist weight in cache. */
 
	this->gcache.cached_weight = max<uint32>(1, weight);
 
	this->gcache.cached_weight = std::max(1u, weight);
 
	/* Friction in bearings and other mechanical parts is 0.1% of the weight (result in N). */
 
	this->gcache.cached_axle_resistance = 10 * weight;
 

	
 
	/* Now update vehicle power (tractive effort is dependent on weight). */
 
	this->PowerChanged();
 
}
 
@@ -159,29 +159,29 @@ int GroundVehicle<T, Type>::GetAccelerat
 
			if (mode == AS_ACCEL && force > max_te) force = max_te;
 
		} else {
 
			force = power / 25;
 
		}
 
	} else {
 
		/* "Kickoff" acceleration. */
 
		force = (mode == AS_ACCEL && !maglev) ? min(max_te, power) : power;
 
		force = max(force, (mass * 8) + resistance);
 
		force = (mode == AS_ACCEL && !maglev) ? std::min<int>(max_te, power) : power;
 
		force = std::max(force, (mass * 8) + resistance);
 
	}
 

	
 
	if (mode == AS_ACCEL) {
 
		/* Easy way out when there is no acceleration. */
 
		if (force == resistance) return 0;
 

	
 
		/* When we accelerate, make sure we always keep doing that, even when
 
		 * the excess force is more than the mass. Otherwise a vehicle going
 
		 * down hill will never slow down enough, and a vehicle that came up
 
		 * a hill will never speed up enough to (eventually) get back to the
 
		 * same (maximum) speed. */
 
		int accel = ClampToI32((force - resistance) / (mass * 4));
 
		return force < resistance ? min(-1, accel) : max(1, accel);
 
		return force < resistance ? std::min(-1, accel) : std::max(1, accel);
 
	} else {
 
		return ClampToI32(min(-force - resistance, -10000) / mass);
 
		return ClampToI32(std::min<int64>(-force - resistance, -10000) / mass);
 
	}
 
}
 

	
 
/**
 
 * Check whether the whole vehicle chain is in the depot.
 
 * @return true if and only if the whole chain is in the depot.
src/ground_vehicle.hpp
Show inline comments
 
@@ -366,21 +366,21 @@ protected:
 
		this->subspeed = (byte)spd;
 

	
 
		/* When we are going faster than the maximum speed, reduce the speed
 
		 * somewhat gradually. But never lower than the maximum speed. */
 
		int tempmax = max_speed;
 
		if (this->cur_speed > max_speed) {
 
			tempmax = max(this->cur_speed - (this->cur_speed / 10) - 1, max_speed);
 
			tempmax = std::max(this->cur_speed - (this->cur_speed / 10) - 1, max_speed);
 
		}
 

	
 
		/* Enforce a maximum and minimum speed. Normally we would use something like
 
		 * Clamp for this, but in this case min_speed might be below the maximum speed
 
		 * threshold for some reason. That makes acceleration fail and assertions
 
		 * happen in Clamp. So make it explicit that min_speed overrules the maximum
 
		 * speed by explicit ordering of min and max. */
 
		this->cur_speed = spd = max(min(this->cur_speed + ((int)spd >> 8), tempmax), min_speed);
 
		this->cur_speed = spd = std::max(std::min(this->cur_speed + ((int)spd >> 8), tempmax), min_speed);
 

	
 
		int scaled_spd = this->GetAdvanceSpeed(spd);
 

	
 
		scaled_spd += this->progress;
 
		this->progress = 0; // set later in *Handler or *Controller
 
		return scaled_spd;
src/group_gui.cpp
Show inline comments
 
@@ -202,35 +202,35 @@ private:
 
	uint ComputeGroupInfoSize()
 
	{
 
		this->column_size[VGC_FOLD] = maxdim(GetSpriteSize(SPR_CIRCLE_FOLDED), GetSpriteSize(SPR_CIRCLE_UNFOLDED));
 
		this->tiny_step_height = this->column_size[VGC_FOLD].height;
 

	
 
		this->column_size[VGC_NAME] = maxdim(GetStringBoundingBox(STR_GROUP_DEFAULT_TRAINS + this->vli.vtype), GetStringBoundingBox(STR_GROUP_ALL_TRAINS + this->vli.vtype));
 
		this->column_size[VGC_NAME].width = max(170u, this->column_size[VGC_NAME].width);
 
		this->tiny_step_height = max(this->tiny_step_height, this->column_size[VGC_NAME].height);
 
		this->column_size[VGC_NAME].width = std::max(170u, this->column_size[VGC_NAME].width);
 
		this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_NAME].height);
 

	
 
		this->column_size[VGC_PROTECT] = GetSpriteSize(SPR_GROUP_REPLACE_PROTECT);
 
		this->tiny_step_height = max(this->tiny_step_height, this->column_size[VGC_PROTECT].height);
 
		this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_PROTECT].height);
 

	
 
		this->column_size[VGC_AUTOREPLACE] = GetSpriteSize(SPR_GROUP_REPLACE_ACTIVE);
 
		this->tiny_step_height = max(this->tiny_step_height, this->column_size[VGC_AUTOREPLACE].height);
 
		this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_AUTOREPLACE].height);
 

	
 
		this->column_size[VGC_PROFIT].width = 0;
 
		this->column_size[VGC_PROFIT].height = 0;
 
		static const SpriteID profit_sprites[] = {SPR_PROFIT_NA, SPR_PROFIT_NEGATIVE, SPR_PROFIT_SOME, SPR_PROFIT_LOT};
 
		for (uint i = 0; i < lengthof(profit_sprites); i++) {
 
			Dimension d = GetSpriteSize(profit_sprites[i]);
 
			this->column_size[VGC_PROFIT] = maxdim(this->column_size[VGC_PROFIT], d);
 
		}
 
		this->tiny_step_height = max(this->tiny_step_height, this->column_size[VGC_PROFIT].height);
 
		this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_PROFIT].height);
 

	
 
		int num_vehicle = GetGroupNumVehicle(this->vli.company, ALL_GROUP, this->vli.vtype);
 
		SetDParamMaxValue(0, num_vehicle, 3, FS_SMALL);
 
		SetDParamMaxValue(1, num_vehicle, 3, FS_SMALL);
 
		this->column_size[VGC_NUMBER] = GetStringBoundingBox(STR_GROUP_COUNT_WITH_SUBGROUP);
 
		this->tiny_step_height = max(this->tiny_step_height, this->column_size[VGC_NUMBER].height);
 
		this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_NUMBER].height);
 

	
 
		this->tiny_step_height += WD_MATRIX_TOP;
 

	
 
		return WD_FRAMERECT_LEFT + 8 +
 
			this->column_size[VGC_FOLD].width + 2 +
 
			this->column_size[VGC_NAME].width + 8 +
 
@@ -387,15 +387,15 @@ public:
 

	
 
				/* Minimum height is the height of the list widget minus all and default vehicles... */
 
				size->height =  4 * GetVehicleListHeight(this->vli.vtype, this->tiny_step_height) - 2 * this->tiny_step_height;
 

	
 
				/* ... minus the buttons at the bottom ... */
 
				uint max_icon_height = GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_CREATE_GROUP)->widget_data).height;
 
				max_icon_height = max(max_icon_height, GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_RENAME_GROUP)->widget_data).height);
 
				max_icon_height = max(max_icon_height, GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_DELETE_GROUP)->widget_data).height);
 
				max_icon_height = max(max_icon_height, GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_REPLACE_PROTECTION)->widget_data).height);
 
				max_icon_height = std::max(max_icon_height, GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_RENAME_GROUP)->widget_data).height);
 
				max_icon_height = std::max(max_icon_height, GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_DELETE_GROUP)->widget_data).height);
 
				max_icon_height = std::max(max_icon_height, GetSpriteSize(this->GetWidget<NWidgetCore>(WID_GL_REPLACE_PROTECTION)->widget_data).height);
 

	
 
				/* ... minus the height of the group info ... */
 
				max_icon_height += (FONT_HEIGHT_NORMAL * 3) + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
 

	
 
				/* Get a multiple of tiny_step_height of that amount */
 
				size->height = Ceil(size->height - max_icon_height, tiny_step_height);
 
@@ -598,13 +598,13 @@ public:
 

	
 
				break;
 
			}
 

	
 
			case WID_GL_LIST_GROUP: {
 
				int y1 = r.top + WD_FRAMERECT_TOP;
 
				int max = min(this->group_sb->GetPosition() + this->group_sb->GetCapacity(), (uint)this->groups.size());
 
				int max = std::min<size_t>(this->group_sb->GetPosition() + this->group_sb->GetCapacity(), this->groups.size());
 
				for (int i = this->group_sb->GetPosition(); i < max; ++i) {
 
					const Group *g = this->groups[i];
 

	
 
					assert(g->owner == this->owner);
 

	
 
					DrawGroupInfo(y1, r.left, r.right, g->index, this->indents[i] * LEVEL_WIDTH, g->replace_protection, g->folded || (i + 1 < (int)this->groups.size() && indents[i + 1] > this->indents[i]));
 
@@ -622,13 +622,13 @@ public:
 
				break;
 

	
 
			case WID_GL_LIST_VEHICLE:
 
				if (this->vli.index != ALL_GROUP && this->grouping == GB_NONE) {
 
					/* Mark vehicles which are in sub-groups (only if we are not using shared order coalescing) */
 
					int y = r.top;
 
					uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), static_cast<uint>(this->vehgroups.size()));
 
					uint max = static_cast<uint>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehgroups.size()));
 
					for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
 
						const Vehicle *v = this->vehgroups[i].GetSingleVehicle();
 
						if (v->group_id != this->vli.index) {
 
							GfxFillRect(r.left + 1, y + 1, r.right - 1, y + this->resize.step_height - 2, _colour_gradient[COLOUR_GREY][3], FILLRECT_CHECKER);
 
						}
 
						y += this->resize.step_height;
src/highscore.cpp
Show inline comments
 
@@ -40,13 +40,13 @@ static const StringID _endgame_perf_titl
 
	STR_HIGHSCORE_PERFORMANCE_TITLE_MOGUL,
 
	STR_HIGHSCORE_PERFORMANCE_TITLE_TYCOON_OF_THE_CENTURY
 
};
 

	
 
StringID EndGameGetPerformanceTitleFromValue(uint value)
 
{
 
	value = minu(value / 64, lengthof(_endgame_perf_titles) - 1);
 
	value = std::min<uint>(value / 64, lengthof(_endgame_perf_titles) - 1);
 

	
 
	return _endgame_perf_titles[value];
 
}
 

	
 
/** Save the highscore for the company */
 
int8 SaveHighScoreValue(const Company *c)
 
@@ -129,13 +129,13 @@ void SaveToHighScore()
 
		uint i;
 
		HighScore *hs;
 

	
 
		for (i = 0; i < SP_SAVED_HIGHSCORE_END; i++) {
 
			for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
 
				/* First character is a command character, so strlen will fail on that */
 
				byte length = min(sizeof(hs->company), StrEmpty(hs->company) ? 0 : (int)strlen(&hs->company[1]) + 1);
 
				byte length = std::min(sizeof(hs->company), StrEmpty(hs->company) ? 0 : strlen(&hs->company[1]) + 1);
 

	
 
				if (fwrite(&length, sizeof(length), 1, fp)       != 1 || // write away string length
 
						fwrite(hs->company, length, 1, fp)           >  1 || // Yes... could be 0 bytes too
 
						fwrite(&hs->score, sizeof(hs->score), 1, fp) != 1 ||
 
						fwrite("  ", 2, 1, fp)                       != 1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
 
					DEBUG(misc, 1, "Could not save highscore.");
 
@@ -160,13 +160,13 @@ void LoadFromHighScore()
 
		HighScore *hs;
 

	
 
		for (i = 0; i < SP_SAVED_HIGHSCORE_END; i++) {
 
			for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
 
				byte length;
 
				if (fread(&length, sizeof(length), 1, fp)                              !=  1 ||
 
						fread(hs->company, min<int>(lengthof(hs->company), length), 1, fp) >   1 || // Yes... could be 0 bytes too
 
						fread(hs->company, std::min<int>(lengthof(hs->company), length), 1, fp) >   1 || // Yes... could be 0 bytes too
 
						fread(&hs->score, sizeof(hs->score), 1, fp)                        !=  1 ||
 
						fseek(fp, 2, SEEK_CUR)                                             == -1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
 
					DEBUG(misc, 1, "Highscore corrupted");
 
					i = SP_SAVED_HIGHSCORE_END;
 
					break;
 
				}
src/highscore_gui.cpp
Show inline comments
 
@@ -55,13 +55,13 @@ struct EndGameHighScoreBaseWindow : Wind
 
		}
 
	}
 

	
 
	/** Return the coordinate of the screen such that a window of 640x480 is centered at the screen. */
 
	Point GetTopLeft(int x, int y)
 
	{
 
		Point pt = {max(0, (_screen.width / 2) - (x / 2)), max(0, (_screen.height / 2) - (y / 2))};
 
		Point pt = {std::max(0, (_screen.width / 2) - (x / 2)), std::max(0, (_screen.height / 2) - (y / 2))};
 
		return pt;
 
	}
 

	
 
	void OnClick(Point pt, int widget, int click_count) override
 
	{
 
		delete this;
src/industry.h
Show inline comments
 
@@ -7,13 +7,12 @@
 

	
 
/** @file industry.h Base of all industries. */
 

	
 
#ifndef INDUSTRY_H
 
#define INDUSTRY_H
 

	
 
#include <algorithm>
 
#include "newgrf_storage.h"
 
#include "subsidy_type.h"
 
#include "industry_map.h"
 
#include "industrytype.h"
 
#include "tilearea_type.h"
 
#include "station_base.h"
src/industry_cmd.cpp
Show inline comments
 
@@ -528,13 +528,13 @@ static bool TransportIndustryGoods(TileI
 
{
 
	Industry *i = Industry::GetByTile(tile);
 
	const IndustrySpec *indspec = GetIndustrySpec(i->type);
 
	bool moved_cargo = false;
 

	
 
	for (uint j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
 
		uint cw = min(i->produced_cargo_waiting[j], 255);
 
		uint cw = std::min<uint>(i->produced_cargo_waiting[j], 255u);
 
		if (cw > indspec->minimal_cargo && i->produced_cargo[j] != CT_INVALID) {
 
			i->produced_cargo_waiting[j] -= cw;
 

	
 
			/* fluctuating economy? */
 
			if (EconomyIsInRecession()) cw = (cw + 1) / 2;
 

	
 
@@ -1029,13 +1029,13 @@ static void PlantFarmField(TileIndex til
 
	/* determine field size */
 
	uint32 r = (Random() & 0x303) + 0x404;
 
	if (_settings_game.game_creation.landscape == LT_ARCTIC) r += 0x404;
 
	uint size_x = GB(r, 0, 8);
 
	uint size_y = GB(r, 8, 8);
 

	
 
	TileArea ta(tile - TileDiffXY(min(TileX(tile), size_x / 2), min(TileY(tile), size_y / 2)), size_x, size_y);
 
	TileArea ta(tile - TileDiffXY(std::min(TileX(tile), size_x / 2), std::min(TileY(tile), size_y / 2)), size_x, size_y);
 
	ta.ClampToMap();
 

	
 
	if (ta.w == 0 || ta.h == 0) return;
 

	
 
	/* check the amount of bad tiles */
 
	int count = 0;
 
@@ -1118,13 +1118,13 @@ static void ChopLumberMillTrees(Industry
 
			if (!IsIndustryCompleted(tile_cur)) return;
 
		}
 
	}
 

	
 
	TileIndex tile = i->location.tile;
 
	if (CircularTileSearch(&tile, 40, SearchLumberMillTrees, nullptr)) { // 40x40 tiles  to search.
 
		i->produced_cargo_waiting[0] = min(0xffff, i->produced_cargo_waiting[0] + 45); // Found a tree, add according value to waiting cargo.
 
		i->produced_cargo_waiting[0] = std::min(0xffff, i->produced_cargo_waiting[0] + 45); // Found a tree, add according value to waiting cargo.
 
	}
 
}
 

	
 
static void ProduceIndustryGoods(Industry *i)
 
{
 
	const IndustrySpec *indsp = GetIndustrySpec(i->type);
 
@@ -1150,13 +1150,13 @@ static void ProduceIndustryGoods(Industr
 
	/* produce some cargo */
 
	if ((i->counter % INDUSTRY_PRODUCE_TICKS) == 0) {
 
		if (HasBit(indsp->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) IndustryProductionCallback(i, 1);
 

	
 
		IndustryBehaviour indbehav = indsp->behaviour;
 
		for (size_t j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
 
			i->produced_cargo_waiting[j] = min(0xffff, i->produced_cargo_waiting[j] + i->production_rate[j]);
 
			i->produced_cargo_waiting[j] = std::min(0xffff, i->produced_cargo_waiting[j] + i->production_rate[j]);
 
		}
 

	
 
		if ((indbehav & INDUSTRYBEH_PLANT_FIELDS) != 0) {
 
			uint16 cb_res = CALLBACK_FAILED;
 
			if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
 
				cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 0, i, i->type, i->location.tile);
 
@@ -1740,13 +1740,13 @@ static void DoCreateNewIndustry(Industry
 
	MemSetT(i->incoming_cargo_waiting,     0, lengthof(i->incoming_cargo_waiting));
 
	MemSetT(i->last_cargo_accepted_at,     0, lengthof(i->last_cargo_accepted_at));
 

	
 
	/* Randomize inital production if non-original economy is used and there are no production related callbacks. */
 
	if (!indspec->UsesOriginalEconomy()) {
 
		for (size_t ci = 0; ci < lengthof(i->production_rate); ci++) {
 
			i->production_rate[ci] = min((RandomRange(256) + 128) * i->production_rate[ci] >> 8, 255);
 
			i->production_rate[ci] = std::min((RandomRange(256) + 128) * i->production_rate[ci] >> 8, 255u);
 
		}
 
	}
 

	
 
	i->town = t;
 
	i->owner = OWNER_NONE;
 

	
 
@@ -2205,13 +2205,13 @@ static uint GetNumberOfIndustries()
 
		55,   // normal
 
		80,   // high
 
	};
 

	
 
	assert(lengthof(numof_industry_table) == ID_END);
 
	uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
 
	return min(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
 
	return std::min<uint>(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
 
}
 

	
 
/**
 
 * Try to place the industry in the game.
 
 * Since there is no feedback why placement fails, there is no other option
 
 * than to try a few times before concluding it does not work.
 
@@ -2281,13 +2281,13 @@ void IndustryBuildData::MonthlyLoop()
 
{
 
	static const int NEWINDS_PER_MONTH = 0x38000 / (10 * 12); // lower 16 bits is a float fraction, 3.5 industries per decade, divided by 10 * 12 months.
 
	if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // 'no industries' setting.
 

	
 
	/* To prevent running out of unused industries for the player to connect,
 
	 * add a fraction of new industries each month, but only if the manager can keep up. */
 
	uint max_behind = 1 + min(99u, ScaleByMapSize(3)); // At most 2 industries for small maps, and 100 at the biggest map (about 6 months industry build attempts).
 
	uint max_behind = 1 + std::min(99u, ScaleByMapSize(3)); // At most 2 industries for small maps, and 100 at the biggest map (about 6 months industry build attempts).
 
	if (GetCurrentTotalNumberOfIndustries() + max_behind >= (this->wanted_inds >> 16)) {
 
		this->wanted_inds += ScaleByMapSize(NEWINDS_PER_MONTH);
 
	}
 
}
 

	
 
/**
 
@@ -2349,13 +2349,13 @@ static void UpdateIndustryStatistics(Ind
 
{
 
	for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
 
		if (i->produced_cargo[j] != CT_INVALID) {
 
			byte pct = 0;
 
			if (i->this_month_production[j] != 0) {
 
				i->last_prod_year = _cur_year;
 
				pct = min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255);
 
				pct = std::min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255);
 
			}
 
			i->last_month_pct_transported[j] = pct;
 

	
 
			i->last_month_production[j] = i->this_month_production[j];
 
			i->this_month_production[j] = 0;
 

	
 
@@ -2373,13 +2373,13 @@ void Industry::RecomputeProductionMultip
 
{
 
	const IndustrySpec *indspec = GetIndustrySpec(this->type);
 
	assert(indspec->UsesOriginalEconomy());
 

	
 
	/* Rates are rounded up, so e.g. oilrig always produces some passengers */
 
	for (size_t i = 0; i < lengthof(this->production_rate); i++) {
 
		this->production_rate[i] = min(CeilDiv(indspec->production_rate[i] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
 
		this->production_rate[i] = std::min(CeilDiv(indspec->production_rate[i] * this->prod_level, PRODLEVEL_DEFAULT), 0xFFu);
 
	}
 
}
 

	
 
void Industry::FillCachedName() const
 
{
 
	char buf[256];
 
@@ -2506,16 +2506,16 @@ void IndustryBuildData::TryBuildNewIndus
 
		}
 

	
 
		/* Try to create the industry. */
 
		const Industry *ind = PlaceIndustry(it, IACT_RANDOMCREATION, false);
 
		if (ind == nullptr) {
 
			this->builddata[it].wait_count = this->builddata[it].max_wait + 1; // Compensate for decrementing below.
 
			this->builddata[it].max_wait = min(1000, this->builddata[it].max_wait + 2);
 
			this->builddata[it].max_wait = std::min(1000, this->builddata[it].max_wait + 2);
 
		} else {
 
			AdvertiseIndustryOpening(ind);
 
			this->builddata[it].max_wait = max(this->builddata[it].max_wait / 2, 1); // Reduce waiting time of the industry type.
 
			this->builddata[it].max_wait = std::max(this->builddata[it].max_wait / 2, 1); // Reduce waiting time of the industry type.
 
		}
 
	}
 

	
 
	/* Decrement wait counters. */
 
	for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
 
		if (this->builddata[it].wait_count > 0) this->builddata[it].wait_count--;
 
@@ -2746,13 +2746,13 @@ static void ChangeIndustryProduction(Ind
 
					mult *= -1;
 
				}
 

	
 
				/* 4.5% chance for 3-23% (or 1 unit for very low productions) production change,
 
				 * determined by mult value. If mult = 1 prod. increases, else (-1) it decreases. */
 
				if (Chance16I(1, 22, r >> 16)) {
 
					new_prod += mult * (max(((RandomRange(50) + 10) * old_prod) >> 8, 1U));
 
					new_prod += mult * (std::max(((RandomRange(50) + 10) * old_prod) >> 8, 1U));
 
				}
 

	
 
				/* Prevent production to overflow or Oil Rig passengers to be over-"produced" */
 
				new_prod = Clamp(new_prod, 1, 255);
 

	
 
				if (((indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) && j == 1 && !(indspec->behaviour & INDUSTRYBEH_WATER_NO_CLAMP_PROD)) {
 
@@ -2791,24 +2791,24 @@ static void ChangeIndustryProduction(Ind
 
			closeit = true;
 
		}
 
	}
 

	
 
	/* Increase if needed */
 
	while (mul-- != 0 && i->prod_level < PRODLEVEL_MAXIMUM) {
 
		i->prod_level = min(i->prod_level * 2, PRODLEVEL_MAXIMUM);
 
		i->prod_level = std::min<int>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
 
		recalculate_multipliers = true;
 
		if (str == STR_NULL) str = indspec->production_up_text;
 
	}
 

	
 
	/* Decrease if needed */
 
	while (div-- != 0 && !closeit) {
 
		if (i->prod_level == PRODLEVEL_MINIMUM) {
 
			closeit = true;
 
			break;
 
		} else {
 
			i->prod_level = max(i->prod_level / 2, (int)PRODLEVEL_MINIMUM); // typecast to int required to please MSVC
 
			i->prod_level = std::max<int>(i->prod_level / 2, PRODLEVEL_MINIMUM);
 
			recalculate_multipliers = true;
 
			if (str == STR_NULL) str = indspec->production_down_text;
 
		}
 
	}
 

	
 
	/* Increase or Decreasing the production level if needed */
 
@@ -2894,13 +2894,13 @@ void IndustryDailyLoop()
 
	Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
 

	
 
	/* perform the required industry changes for the day */
 

	
 
	uint perc = 3; // Between 3% and 9% chance of creating a new industry.
 
	if ((_industry_builder.wanted_inds >> 16) > GetCurrentTotalNumberOfIndustries()) {
 
		perc = min(9u, perc + (_industry_builder.wanted_inds >> 16) - GetCurrentTotalNumberOfIndustries());
 
		perc = std::min(9u, perc + (_industry_builder.wanted_inds >> 16) - GetCurrentTotalNumberOfIndustries());
 
	}
 
	for (uint16 j = 0; j < change_loop; j++) {
 
		if (Chance16(perc, 100)) {
 
			_industry_builder.TryBuildNewIndustry();
 
		} else {
 
			Industry *i = Industry::GetRandom();
src/industry_gui.cpp
Show inline comments
 
@@ -431,23 +431,23 @@ public:
 

	
 
					/* Measure the accepted cargoes, if any. */
 
					GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
 
					std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
 
					Dimension strdim = GetStringBoundingBox(cargostring.c_str());
 
					if (strdim.width > max_minwidth) {
 
						extra_lines_req = max(extra_lines_req, strdim.width / max_minwidth + 1);
 
						extra_lines_req = std::max(extra_lines_req, strdim.width / max_minwidth + 1);
 
						strdim.width = max_minwidth;
 
					}
 
					d = maxdim(d, strdim);
 

	
 
					/* Measure the produced cargoes, if any. */
 
					GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
 
					cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
 
					strdim = GetStringBoundingBox(cargostring.c_str());
 
					if (strdim.width > max_minwidth) {
 
						extra_lines_prd = max(extra_lines_prd, strdim.width / max_minwidth + 1);
 
						extra_lines_prd = std::max(extra_lines_prd, strdim.width / max_minwidth + 1);
 
						strdim.width = max_minwidth;
 
					}
 
					d = maxdim(d, strdim);
 

	
 
					if (indsp->grf_prop.grffile != nullptr) {
 
						/* Reserve a few extra lines for text from an industry NewGRF. */
 
@@ -963,28 +963,28 @@ public:
 
					/* Clicked buttons, decrease or increase production */
 
					byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
 
					switch (this->editable) {
 
						case EA_MULTIPLIER:
 
							if (button == 1) {
 
								if (i->prod_level <= PRODLEVEL_MINIMUM) return;
 
								i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
 
								i->prod_level = std::max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
 
							} else {
 
								if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
 
								i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
 
								i->prod_level = std::min<uint>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
 
							}
 
							break;
 

	
 
						case EA_RATE:
 
							if (button == 1) {
 
								if (i->production_rate[line - IL_RATE1] <= 0) return;
 
								i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
 
								i->production_rate[line - IL_RATE1] = std::max(i->production_rate[line - IL_RATE1] / 2, 0);
 
							} else {
 
								if (i->production_rate[line - IL_RATE1] >= 255) return;
 
								/* a zero production industry is unlikely to give anything but zero, so push it a little bit */
 
								int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
 
								i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
 
								i->production_rate[line - IL_RATE1] = std::min<uint>(new_prod, 255);
 
							}
 
							break;
 

	
 
						default: NOT_REACHED();
 
					}
 

	
 
@@ -1465,13 +1465,13 @@ protected:
 
			if (filtered_ci != cargos.end()) {
 
				std::rotate(cargos.begin(), filtered_ci, filtered_ci + 1);
 
			}
 
		}
 

	
 
		/* Display first 3 cargos */
 
		for (size_t j = 0; j < min<size_t>(3, cargos.size()); j++) {
 
		for (size_t j = 0; j < std::min<size_t>(3, cargos.size()); j++) {
 
			CargoInfo ci = cargos[j];
 
			SetDParam(p++, STR_INDUSTRY_DIRECTORY_ITEM_INFO);
 
			SetDParam(p++, std::get<0>(ci));
 
			SetDParam(p++, std::get<1>(ci));
 
			SetDParamStr(p++, std::get<2>(ci));
 
			SetDParam(p++, std::get<3>(ci));
 
@@ -2396,16 +2396,16 @@ struct IndustryCargoesWindow : public Wi
 
		this->ind_textsize.height = 0;
 
		CargoesField::max_cargoes = 0;
 
		for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
 
			const IndustrySpec *indsp = GetIndustrySpec(it);
 
			if (!indsp->enabled) continue;
 
			this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
 
			CargoesField::max_cargoes = max<uint>(CargoesField::max_cargoes, std::count_if(indsp->accepts_cargo, endof(indsp->accepts_cargo), IsCargoIDValid));
 
			CargoesField::max_cargoes = max<uint>(CargoesField::max_cargoes, std::count_if(indsp->produced_cargo, endof(indsp->produced_cargo), IsCargoIDValid));
 
			CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->accepts_cargo, endof(indsp->accepts_cargo), IsCargoIDValid));
 
			CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->produced_cargo, endof(indsp->produced_cargo), IsCargoIDValid));
 
		}
 
		d.width = max(d.width, this->ind_textsize.width);
 
		d.width = std::max(d.width, this->ind_textsize.width);
 
		d.height = this->ind_textsize.height;
 
		this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
 

	
 
		/* Compute max size of the cargo texts. */
 
		this->cargo_textsize.width = 0;
 
		this->cargo_textsize.height = 0;
 
@@ -2417,13 +2417,13 @@ struct IndustryCargoesWindow : public Wi
 
		d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
 
		this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
 

	
 
		d.width  += 2 * HOR_TEXT_PADDING;
 
		/* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
 
		uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + CargoesField::max_cargoes * FONT_HEIGHT_NORMAL + (CargoesField::max_cargoes - 1) *  CargoesField::VERT_CARGO_SPACE;
 
		d.height = max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
 
		d.height = std::max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
 

	
 
		CargoesField::industry_width = d.width;
 
		CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
 

	
 
		/* Width of a #CFT_CARGO field. */
 
		CargoesField::cargo_field_width = CargoesField::HOR_CARGO_BORDER_SPACE * 2 + CargoesField::HOR_CARGO_WIDTH * CargoesField::max_cargoes + CargoesField::HOR_CARGO_SPACE * (CargoesField::max_cargoes - 1);
 
@@ -2434,17 +2434,17 @@ struct IndustryCargoesWindow : public Wi
 
		switch (widget) {
 
			case WID_IC_PANEL:
 
				size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::cargo_field_width * 2 + WD_FRAMETEXT_RIGHT;
 
				break;
 

	
 
			case WID_IC_IND_DROPDOWN:
 
				size->width = max(size->width, this->ind_textsize.width + padding.width);
 
				size->width = std::max(size->width, this->ind_textsize.width + padding.width);
 
				break;
 

	
 
			case WID_IC_CARGO_DROPDOWN:
 
				size->width = max(size->width, this->cargo_textsize.width + padding.width);
 
				size->width = std::max(size->width, this->cargo_textsize.width + padding.width);
 
				break;
 
		}
 
	}
 

	
 

	
 
	CargoesFieldType type; ///< Type of field.
 
@@ -2635,13 +2635,13 @@ struct IndustryCargoesWindow : public Wi
 
		const IndustrySpec *central_sp = GetIndustrySpec(it);
 
		bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
 
		bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
 
		/* Make a field consisting of two cargo columns. */
 
		int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
 
		int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
 
		int num_indrows = max(3, max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
 
		int num_indrows = std::max(3, std::max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
 
		for (int i = 0; i < num_indrows; i++) {
 
			CargoesRow &row = this->fields.emplace_back();
 
			row.columns[0].MakeEmpty(CFT_EMPTY);
 
			row.columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
 
			row.columns[2].MakeEmpty(CFT_EMPTY);
 
			row.columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
 
@@ -2711,13 +2711,13 @@ struct IndustryCargoesWindow : public Wi
 
		row.columns[4].MakeEmpty(CFT_SMALL_EMPTY);
 

	
 
		bool houses_supply = HousesCanSupply(&cid, 1);
 
		bool houses_accept = HousesCanAccept(&cid, 1);
 
		int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
 
		int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
 
		int num_indrows = max(num_supp, num_cust);
 
		int num_indrows = std::max(num_supp, num_cust);
 
		for (int i = 0; i < num_indrows; i++) {
 
			CargoesRow &row = this->fields.emplace_back();
 
			row.columns[0].MakeEmpty(CFT_EMPTY);
 
			row.columns[1].MakeCargo(&cid, 1);
 
			row.columns[2].MakeEmpty(CFT_EMPTY);
 
			row.columns[3].MakeEmpty(CFT_EMPTY);
src/ini_load.cpp
Show inline comments
 
@@ -223,13 +223,13 @@ void IniLoadFile::LoadFromDisk(const std
 
		/* Skip comments and empty lines outside IGT_SEQUENCE groups. */
 
		if ((group == nullptr || group->type != IGT_SEQUENCE) && (*s == '#' || *s == ';' || *s == '\0')) {
 
			uint ns = comment_size + (e - s + 1);
 
			uint a = comment_alloc;
 
			/* add to comment */
 
			if (ns > a) {
 
				a = max(a, 128U);
 
				a = std::max(a, 128U);
 
				do a *= 2; while (a < ns);
 
				comment = ReallocT(comment, comment_alloc = a);
 
			}
 
			uint pos = comment_size;
 
			comment_size += (e - s + 1);
 
			comment[pos + e - s] = '\n'; // comment newline
src/landscape.cpp
Show inline comments
 
@@ -127,18 +127,18 @@ Point InverseRemapCoords2(int x, int y, 
 
	 * 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. */
 
	int z = 0;
 
	if (clamp_to_map) {
 
		for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(pt.x + max(z, 4) - 4, min_coord, max_x), Clamp(pt.y + max(z, 4) - 4, min_coord, max_y)) / 2;
 
		for (int m = 3; m > 0; m--) z = GetSlopePixelZ(Clamp(pt.x + max(z, m) - m, min_coord, max_x), Clamp(pt.y + max(z, m) - m, min_coord, max_y)) / 2;
 
		for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(pt.x + std::max(z, 4) - 4, min_coord, max_x), Clamp(pt.y + std::max(z, 4) - 4, min_coord, max_y)) / 2;
 
		for (int m = 3; m > 0; m--) z = GetSlopePixelZ(Clamp(pt.x + std::max(z, m) - m, min_coord, max_x), Clamp(pt.y + std::max(z, m) - m, min_coord, max_y)) / 2;
 
		for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(pt.x + z,             min_coord, max_x), Clamp(pt.y + z,             min_coord, max_y)) / 2;
 
	} else {
 
		for (int i = 0; i < 5; i++) z = GetSlopePixelZOutsideMap(pt.x + max(z, 4) - 4, pt.y + max(z, 4) - 4) / 2;
 
		for (int m = 3; m > 0; m--) z = GetSlopePixelZOutsideMap(pt.x + max(z, m) - m, pt.y + max(z, m) - m) / 2;
 
		for (int i = 0; i < 5; i++) z = GetSlopePixelZOutsideMap(pt.x + std::max(z, 4) - 4, pt.y + std::max(z, 4) - 4) / 2;
 
		for (int m = 3; m > 0; m--) z = GetSlopePixelZOutsideMap(pt.x + std::max(z, m) - m, pt.y + std::max(z, m) - m) / 2;
 
		for (int i = 0; i < 5; i++) z = GetSlopePixelZOutsideMap(pt.x + z,             pt.y + z            ) / 2;
 
	}
 

	
 
	pt.x += z;
 
	pt.y += z;
 
	if (clamp_to_map) {
 
@@ -627,14 +627,14 @@ void SetSnowLine(byte table[SNOW_LINE_MO
 
	_snow_line = CallocT<SnowLine>(1);
 
	_snow_line->lowest_value = 0xFF;
 
	memcpy(_snow_line->table, table, sizeof(_snow_line->table));
 

	
 
	for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
 
		for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
 
			_snow_line->highest_value = max(_snow_line->highest_value, table[i][j]);
 
			_snow_line->lowest_value = min(_snow_line->lowest_value, table[i][j]);
 
			_snow_line->highest_value = std::max(_snow_line->highest_value, table[i][j]);
 
			_snow_line->lowest_value = std::min(_snow_line->lowest_value, table[i][j]);
 
		}
 
	}
 
}
 

	
 
/**
 
 * Get the current snow line, either variable or static.
src/linkgraph/demands.cpp
Show inline comments
 
@@ -42,25 +42,25 @@ public:
 
	/**
 
	 * Calculate the mean demand per node using the sum of supplies.
 
	 * @param num_demands Number of accepting nodes.
 
	 */
 
	inline void SetDemandPerNode(uint num_demands)
 
	{
 
		this->demand_per_node = max(this->supply_sum / num_demands, 1U);
 
		this->demand_per_node = std::max(this->supply_sum / num_demands, 1U);
 
	}
 

	
 
	/**
 
	 * Get the effective supply of one node towards another one. In symmetric
 
	 * distribution the supply of the other node is weighed in.
 
	 * @param from The supplying node.
 
	 * @param to The receiving node.
 
	 * @return Effective supply.
 
	 */
 
	inline uint EffectiveSupply(const Node &from, const Node &to)
 
	{
 
		return max(from.Supply() * max(1U, to.Supply()) * this->mod_size / 100 / this->demand_per_node, 1U);
 
		return std::max(from.Supply() * std::max(1U, to.Supply()) * this->mod_size / 100 / this->demand_per_node, 1U);
 
	}
 

	
 
	/**
 
	 * Check if there is any acceptance left for this node. In symmetric distribution
 
	 * nodes only accept anything if they also supply something. So if
 
	 * undelivered_supply == 0 at the node there isn't any demand left either.
 
@@ -131,13 +131,13 @@ void SymmetricScaler::SetDemands(LinkGra
 
{
 
	if (job[from_id].Demand() > 0) {
 
		uint demand_back = demand_forw * this->mod_size / 100;
 
		uint undelivered = job[to_id].UndeliveredSupply();
 
		if (demand_back > undelivered) {
 
			demand_back = undelivered;
 
			demand_forw = max(1U, demand_back * 100 / this->mod_size);
 
			demand_forw = std::max(1U, demand_back * 100 / this->mod_size);
 
		}
 
		this->Scaler::SetDemands(job, to_id, from_id, demand_back);
 
	}
 

	
 
	this->Scaler::SetDemands(job, from_id, to_id, demand_forw);
 
}
 
@@ -227,13 +227,13 @@ void DemandCalculator::CalcDemand(LinkGr
 
			} else if (++chance > this->accuracy * num_demands * num_supplies) {
 
				/* After some trying, if there is still supply left, distribute
 
				 * demand also to other nodes. */
 
				demand_forw = 1;
 
			}
 

	
 
			demand_forw = min(demand_forw, job[from_id].UndeliveredSupply());
 
			demand_forw = std::min(demand_forw, job[from_id].UndeliveredSupply());
 

	
 
			scaler.SetDemands(job, from_id, to_id, demand_forw);
 

	
 
			if (scaler.HasDemandLeft(job[to_id])) {
 
				demands.push(to_id);
 
			} else {
src/linkgraph/linkgraph.cpp
Show inline comments
 
@@ -68,13 +68,13 @@ void LinkGraph::Compress()
 
	this->last_compression = (_date + this->last_compression) / 2;
 
	for (NodeID node1 = 0; node1 < this->Size(); ++node1) {
 
		this->nodes[node1].supply /= 2;
 
		for (NodeID node2 = 0; node2 < this->Size(); ++node2) {
 
			BaseEdge &edge = this->edges[node1][node2];
 
			if (edge.capacity > 0) {
 
				edge.capacity = max(1U, edge.capacity / 2);
 
				edge.capacity = std::max(1U, edge.capacity / 2);
 
				edge.usage /= 2;
 
			}
 
		}
 
	}
 
}
 

	
 
@@ -160,14 +160,13 @@ NodeID LinkGraph::AddNode(const Station 
 
	const GoodsEntry &good = st->goods[this->cargo];
 

	
 
	NodeID new_node = this->Size();
 
	this->nodes.emplace_back();
 
	/* Avoid reducing the height of the matrix as that is expensive and we
 
	 * most likely will increase it again later which is again expensive. */
 
	this->edges.Resize(new_node + 1U,
 
			max(new_node + 1U, this->edges.Height()));
 
	this->edges.Resize(new_node + 1U, std::max(new_node + 1U, this->edges.Height()));
 

	
 
	this->nodes[new_node].Init(st->xy, st->index,
 
			HasBit(good.status, GoodsEntry::GES_ACCEPTANCE));
 

	
 
	BaseEdge *new_edges = this->edges[new_node];
 

	
 
@@ -263,14 +262,14 @@ void LinkGraph::Edge::Update(uint capaci
 
	assert(capacity >= usage);
 

	
 
	if (mode & EUM_INCREASE) {
 
		this->edge.capacity += capacity;
 
		this->edge.usage += usage;
 
	} else if (mode & EUM_REFRESH) {
 
		this->edge.capacity = max(this->edge.capacity, capacity);
 
		this->edge.usage = max(this->edge.usage, usage);
 
		this->edge.capacity = std::max(this->edge.capacity, capacity);
 
		this->edge.usage = std::max(this->edge.usage, usage);
 
	}
 
	if (mode & EUM_UNRESTRICTED) this->edge.last_unrestricted_update = _date;
 
	if (mode & EUM_RESTRICTED) this->edge.last_restricted_update = _date;
 
}
 

	
 
/**
src/linkgraph/linkgraph.h
Show inline comments
 
@@ -110,13 +110,13 @@ public:
 
		Date LastRestrictedUpdate() const { return this->edge.last_restricted_update; }
 

	
 
		/**
 
		 * Get the date of the last update to any part of the edge's capacity.
 
		 * @return Last update.
 
		 */
 
		Date LastUpdate() const { return max(this->edge.last_unrestricted_update, this->edge.last_restricted_update); }
 
		Date LastUpdate() const { return std::max(this->edge.last_unrestricted_update, this->edge.last_restricted_update); }
 
	};
 

	
 
	/**
 
	 * Wrapper for a node (const or not) allowing retrieval, but no modification.
 
	 * @tparam Tedge Actual node class, may be "const BaseNode" or just "BaseNode".
 
	 * @tparam Tedge Actual edge class, may be "const BaseEdge" or just "BaseEdge".
 
@@ -450,13 +450,13 @@ public:
 
	 * @param target_age Age of the target link graph.
 
	 * @param orig_age Age of the original link graph.
 
	 * @return scaled value.
 
	 */
 
	inline static uint Scale(uint val, uint target_age, uint orig_age)
 
	{
 
		return val > 0 ? max(1U, val * target_age / orig_age) : 0;
 
		return val > 0 ? std::max(1U, val * target_age / orig_age) : 0;
 
	}
 

	
 
	/** Bare constructor, only for save/load. */
 
	LinkGraph() : cargo(INVALID_CARGO), last_compression(0) {}
 
	/**
 
	 * Real constructor.
src/linkgraph/linkgraph_gui.cpp
Show inline comments
 
@@ -221,13 +221,13 @@ void LinkGraphOverlay::AddLinks(const St
 
 * @param cargo LinkProperties to write the information to.
 
 */
 
/* static */ void LinkGraphOverlay::AddStats(uint new_cap, uint new_usg, uint new_plan, bool new_shared, LinkProperties &cargo)
 
{
 
	/* multiply the numbers by 32 in order to avoid comparing to 0 too often. */
 
	if (cargo.capacity == 0 ||
 
			max(cargo.usage, cargo.planned) * 32 / (cargo.capacity + 1) < max(new_usg, new_plan) * 32 / (new_cap + 1)) {
 
			std::max(cargo.usage, cargo.planned) * 32 / (cargo.capacity + 1) < std::max(new_usg, new_plan) * 32 / (new_cap + 1)) {
 
		cargo.capacity = new_cap;
 
		cargo.usage = new_usg;
 
		cargo.planned = new_plan;
 
	}
 
	if (new_shared) cargo.shared = true;
 
}
 
@@ -269,13 +269,13 @@ void LinkGraphOverlay::DrawLinks(const D
 
 * @param pta Source of the link.
 
 * @param ptb Destination of the link.
 
 * @param cargo Properties of the link.
 
 */
 
void LinkGraphOverlay::DrawContent(Point pta, Point ptb, const LinkProperties &cargo) const
 
{
 
	uint usage_or_plan = min(cargo.capacity * 2 + 1, max(cargo.usage, cargo.planned));
 
	uint usage_or_plan = std::min(cargo.capacity * 2 + 1, std::max(cargo.usage, cargo.planned));
 
	int colour = LinkGraphOverlay::LINK_COLOURS[usage_or_plan * lengthof(LinkGraphOverlay::LINK_COLOURS) / (cargo.capacity * 2 + 2)];
 
	int dash = cargo.shared ? this->scale * 4 : 0;
 

	
 
	/* Move line a bit 90° against its dominant direction to prevent it from
 
	 * being hidden below the grey line. */
 
	int side = _settings_game.vehicle.road_side ? 1 : -1;
 
@@ -299,13 +299,13 @@ void LinkGraphOverlay::DrawStationDots(c
 
	for (StationSupplyList::const_iterator i(this->cached_stations.begin()); i != this->cached_stations.end(); ++i) {
 
		const Station *st = Station::GetIfValid(i->first);
 
		if (st == nullptr) continue;
 
		Point pt = this->GetStationMiddle(st);
 
		if (!this->IsPointVisible(pt, dpi, 3 * this->scale)) continue;
 

	
 
		uint r = this->scale * 2 + this->scale * 2 * min(200, i->second) / 200;
 
		uint r = this->scale * 2 + this->scale * 2 * std::min(200U, i->second) / 200;
 

	
 
		LinkGraphOverlay::DrawVertex(pt.x, pt.y, r,
 
				_colour_gradient[st->owner != OWNER_NONE ?
 
						(Colours)Company::Get(st->owner)->colour : COLOUR_GREY][5],
 
				_colour_gradient[COLOUR_GREY][1]);
 
	}
src/linkgraph/linkgraphjob.cpp
Show inline comments
 
@@ -220,14 +220,14 @@ void LinkGraphJob::NodeAnnotation::Init(
 
 * @param cap Maximum capacity of the new leg.
 
 * @param free_cap Remaining free capacity of the new leg.
 
 * @param dist Distance of the new leg.
 
 */
 
void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
 
{
 
	this->capacity = min(base->capacity, cap);
 
	this->free_capacity = min(base->free_capacity, free_cap);
 
	this->capacity = std::min(base->capacity, cap);
 
	this->free_capacity = std::min(base->free_capacity, free_cap);
 
	this->distance = base->distance + dist;
 
	assert(this->distance > 0);
 
	if (this->parent != base) {
 
		this->Detach();
 
		this->parent = base;
 
		this->parent->num_children++;
 
@@ -247,13 +247,13 @@ uint Path::AddFlow(uint new_flow, LinkGr
 
{
 
	if (this->parent != nullptr) {
 
		LinkGraphJob::Edge edge = job[this->parent->node][this->node];
 
		if (max_saturation != UINT_MAX) {
 
			uint usable_cap = edge.Capacity() * max_saturation / 100;
 
			if (usable_cap > edge.Flow()) {
 
				new_flow = min(new_flow, usable_cap - edge.Flow());
 
				new_flow = std::min(new_flow, usable_cap - edge.Flow());
 
			} else {
 
				return 0;
 
			}
 
		}
 
		new_flow = this->parent->AddFlow(new_flow, job, max_saturation);
 
		if (this->flow == 0 && new_flow > 0) {
src/linkgraph/linkgraphjob.h
Show inline comments
 
@@ -389,13 +389,13 @@ public:
 
	 * @param free Free capacity.
 
	 * @param total Total capacity.
 
	 * @return free * 16 / max(total, 1).
 
	 */
 
	inline static int GetCapacityRatio(int free, uint total)
 
	{
 
		return Clamp(free, PATH_CAP_MIN_FREE, PATH_CAP_MAX_FREE) * PATH_CAP_MULTIPLIER / max(total, 1U);
 
		return Clamp(free, PATH_CAP_MIN_FREE, PATH_CAP_MAX_FREE) * PATH_CAP_MULTIPLIER / std::max(total, 1U);
 
	}
 

	
 
	/**
 
	 * Get capacity ratio of this path.
 
	 * @return free capacity * 16 / (total capacity + 1).
 
	 */
src/linkgraph/mcf.cpp
Show inline comments
 
@@ -232,13 +232,13 @@ bool DistanceAnnotation::IsBetter(const 
 
 * @return True if base + the new edge would be better than the path associated
 
 * with this annotation.
 
 */
 
bool CapacityAnnotation::IsBetter(const CapacityAnnotation *base, uint cap,
 
		int free_cap, uint dist) const
 
{
 
	int min_cap = Path::GetCapacityRatio(min(base->free_capacity, free_cap), min(base->capacity, cap));
 
	int min_cap = Path::GetCapacityRatio(std::min(base->free_capacity, free_cap), std::min(base->capacity, cap));
 
	int this_cap = this->GetCapacityRatio();
 
	if (min_cap == this_cap) {
 
		/* If the capacities are the same and the other path isn't disconnected
 
		 * choose the shorter path. */
 
		return base->distance == UINT_MAX ? false : (base->distance + dist < this->distance);
 
	} else {
 
@@ -351,13 +351,13 @@ uint MultiCommodityFlow::PushFlow(Edge &
 
 */
 
uint MCF1stPass::FindCycleFlow(const PathVector &path, const Path *cycle_begin)
 
{
 
	uint flow = UINT_MAX;
 
	const Path *cycle_end = cycle_begin;
 
	do {
 
		flow = min(flow, cycle_begin->GetFlow());
 
		flow = std::min(flow, cycle_begin->GetFlow());
 
		cycle_begin = path[cycle_begin->GetNode()];
 
	} while (cycle_begin != cycle_end);
 
	return flow;
 
}
 

	
 
/**
src/map.cpp
Show inline comments
 
@@ -187,13 +187,13 @@ uint DistanceSquare(TileIndex t0, TileIn
 
 * @return the distance
 
 */
 
uint DistanceMax(TileIndex t0, TileIndex t1)
 
{
 
	const uint dx = Delta(TileX(t0), TileX(t1));
 
	const uint dy = Delta(TileY(t0), TileY(t1));
 
	return max(dx, dy);
 
	return std::max(dx, dy);
 
}
 

	
 

	
 
/**
 
 * Gets the biggest distance component (x or y) between the two given tiles
 
 * plus the Manhattan distance, i.e. two times the biggest distance component
 
@@ -217,15 +217,15 @@ uint DistanceMaxPlusManhattan(TileIndex 
 
uint DistanceFromEdge(TileIndex tile)
 
{
 
	const uint xl = TileX(tile);
 
	const uint yl = TileY(tile);
 
	const uint xh = MapSizeX() - 1 - xl;
 
	const uint yh = MapSizeY() - 1 - yl;
 
	const uint minl = min(xl, yl);
 
	const uint minh = min(xh, yh);
 
	return min(minl, minh);
 
	const uint minl = std::min(xl, yl);
 
	const uint minh = std::min(xh, yh);
 
	return std::min(minl, minh);
 
}
 

	
 
/**
 
 * Gets the distance to the edge of the map in given direction.
 
 * @param tile the tile to get the distance from
 
 * @param dir the direction of interest
src/misc/str.hpp
Show inline comments
 
@@ -89,13 +89,13 @@ struct CStrA : public CBlobT<char>
 
		return strcmp(base::Data(), other.Data()) < 0;
 
	}
 

	
 
	/** Add formatted string (like vsprintf) at the end of existing contents. */
 
	int AddFormatL(const char *format, va_list args) WARN_FORMAT(2, 0)
 
	{
 
		size_t addSize = max<size_t>(strlen(format), 16);
 
		size_t addSize = std::max<size_t>(strlen(format), 16);
 
		addSize += addSize / 2;
 
		int ret;
 
		int err = 0;
 
		for (;;) {
 
			char *buf = MakeFreeSpace(addSize);
 
			ret = vseprintf(buf, buf + base::GetReserve() - 1, format, args);
src/misc_cmd.cpp
Show inline comments
 
@@ -95,16 +95,16 @@ CommandCost CmdDecreaseLoan(TileIndex ti
 
	if (c->current_loan == 0) return_cmd_error(STR_ERROR_LOAN_ALREADY_REPAYED);
 

	
 
	Money loan;
 
	switch (p2 & 3) {
 
		default: return CMD_ERROR; // Invalid method
 
		case 0: // Pay back one step
 
			loan = min(c->current_loan, (Money)LOAN_INTERVAL);
 
			loan = std::min(c->current_loan, (Money)LOAN_INTERVAL);
 
			break;
 
		case 1: // Pay back as much as possible
 
			loan = max(min(c->current_loan, c->money), (Money)LOAN_INTERVAL);
 
			loan = std::max(std::min(c->current_loan, c->money), (Money)LOAN_INTERVAL);
 
			loan -= loan % LOAN_INTERVAL;
 
			break;
 
		case 2: // Repay the given amount of loan
 
			loan = ((uint64)p1 << 32) | (p2 & 0xFFFFFFFC);
 
			if (loan % LOAN_INTERVAL != 0 || loan < LOAN_INTERVAL || loan > c->current_loan) return CMD_ERROR; // Invalid amount to loan
 
			break;
src/misc_gui.cpp
Show inline comments
 
@@ -96,21 +96,21 @@ public:
 

	
 
		size->height = WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
 
		for (uint i = 0; i < LAND_INFO_CENTERED_LINES; i++) {
 
			if (StrEmpty(this->landinfo_data[i])) break;
 

	
 
			uint width = GetStringBoundingBox(this->landinfo_data[i]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
 
			size->width = max(size->width, width);
 
			size->width = std::max(size->width, width);
 

	
 
			size->height += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
 
			if (i == 0) size->height += 4;
 
		}
 

	
 
		if (!StrEmpty(this->landinfo_data[LAND_INFO_MULTICENTER_LINE])) {
 
			uint width = GetStringBoundingBox(this->landinfo_data[LAND_INFO_MULTICENTER_LINE]).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
 
			size->width = max(size->width, min(300u, width));
 
			size->width = std::max(size->width, std::min(300u, width));
 
			SetDParamStr(0, this->landinfo_data[LAND_INFO_MULTICENTER_LINE]);
 
			size->height += GetStringHeight(STR_JUST_RAW_STRING, size->width - WD_FRAMETEXT_LEFT - WD_FRAMETEXT_RIGHT);
 
		}
 
	}
 

	
 
	LandInfoWindow(TileIndex tile) : Window(&_land_info_desc), tile(tile)
 
@@ -507,13 +507,13 @@ struct AboutWindow : public Window {
 

	
 
		Dimension d;
 
		d.height = this->line_height * num_visible_lines;
 

	
 
		d.width = 0;
 
		for (uint i = 0; i < lengthof(_credits); i++) {
 
			d.width = max(d.width, GetStringBoundingBox(_credits[i]).width);
 
			d.width = std::max(d.width, GetStringBoundingBox(_credits[i]).width);
 
		}
 
		*size = maxdim(*size, d);
 
	}
 

	
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
@@ -703,24 +703,24 @@ struct TooltipsWindow : public Window
 
		Point pt;
 

	
 
		/* 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 */
 
		pt.y = Clamp(_cursor.pos.y + _cursor.total_size.y + _cursor.total_offs.y + 5, scr_top, scr_bot);
 
		if (pt.y + sm_height > scr_bot) pt.y = min(_cursor.pos.y + _cursor.total_offs.y - 5, scr_bot) - sm_height;
 
		if (pt.y + sm_height > scr_bot) pt.y = std::min(_cursor.pos.y + _cursor.total_offs.y - 5, scr_bot) - sm_height;
 
		pt.x = sm_width >= _screen.width ? 0 : Clamp(_cursor.pos.x - (sm_width >> 1), 0, _screen.width - sm_width);
 

	
 
		return pt;
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		/* There is only one widget. */
 
		for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
 

	
 
		size->width  = min(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
 
		size->width  = std::min<uint>(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
 
		size->height = GetStringHeight(this->string_id, size->width);
 

	
 
		/* Increase slightly to have some space around the box. */
 
		size->width  += 2 + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
 
		size->height += 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
 
	}
 
@@ -814,13 +814,13 @@ void QueryString::DrawEditBox(const Wind
 
	DrawPixelInfo *old_dpi = _cur_dpi;
 
	_cur_dpi = &dpi;
 

	
 
	/* We will take the current widget length as maximum width, with a small
 
	 * space reserved at the end for the caret to show */
 
	const Textbuf *tb = &this->text;
 
	int delta = min(0, (right - left) - tb->pixels - 10);
 
	int delta = std::min(0, (right - left) - tb->pixels - 10);
 

	
 
	if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
 

	
 
	/* If we have a marked area, draw a background highlight. */
 
	if (tb->marklength != 0) GfxFillRect(delta + tb->markxoffs, 0, delta + tb->markxoffs + tb->marklength - 1, bottom - top, PC_GREY);
 

	
 
@@ -852,13 +852,13 @@ Point QueryString::GetCaretPosition(cons
 

	
 
	int left   = wi->pos_x + (rtl ? clearbtn_width : 0);
 
	int right  = wi->pos_x + (rtl ? wi->current_x : wi->current_x - clearbtn_width) - 1;
 

	
 
	/* Clamp caret position to be inside out current width. */
 
	const Textbuf *tb = &this->text;
 
	int delta = min(0, (right - left) - tb->pixels - 10);
 
	int delta = std::min(0, (right - left) - tb->pixels - 10);
 
	if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
 

	
 
	Point pt = {left + WD_FRAMERECT_LEFT + tb->caretxoffs + delta, (int)wi->pos_y + WD_FRAMERECT_TOP};
 
	return pt;
 
}
 

	
 
@@ -885,13 +885,13 @@ Rect QueryString::GetBoundingRect(const 
 

	
 
	int top    = wi->pos_y + WD_FRAMERECT_TOP;
 
	int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
 

	
 
	/* Clamp caret position to be inside our current width. */
 
	const Textbuf *tb = &this->text;
 
	int delta = min(0, (right - left) - tb->pixels - 10);
 
	int delta = std::min(0, (right - left) - tb->pixels - 10);
 
	if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
 

	
 
	/* Get location of first and last character. */
 
	Point p1 = GetCharPosInString(tb->buf, from, FS_NORMAL);
 
	Point p2 = from != to ? GetCharPosInString(tb->buf, to, FS_NORMAL) : p1;
 

	
 
@@ -924,13 +924,13 @@ const char *QueryString::GetCharAtPositi
 
	int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
 

	
 
	if (!IsInsideMM(pt.y, top, bottom)) return nullptr;
 

	
 
	/* Clamp caret position to be inside our current width. */
 
	const Textbuf *tb = &this->text;
 
	int delta = min(0, (right - left) - tb->pixels - 10);
 
	int delta = std::min(0, (right - left) - tb->pixels - 10);
 
	if (tb->caretxoffs + delta < 0) delta = -tb->caretxoffs;
 

	
 
	return ::GetCharAtPosition(tb->buf, pt.x - delta - left);
 
}
 

	
 
void QueryString::ClickEditBox(Window *w, Point pt, int wid, int click_count, bool focus_changed)
src/music/dmusic.cpp
Show inline comments
 
@@ -22,13 +22,12 @@
 
#include "midifile.hpp"
 
#include "midi.h"
 

	
 
#include <windows.h>
 
#include <dmksctrl.h>
 
#include <dmusicc.h>
 
#include <algorithm>
 
#include <mutex>
 

	
 
#include "../safeguards.h"
 

	
 
#if defined(_MSC_VER)
 
#	pragma comment(lib, "ole32.lib")
src/music/midifile.cpp
Show inline comments
 
@@ -11,13 +11,12 @@
 
#include "../fileio_func.h"
 
#include "../fileio_type.h"
 
#include "../string_func.h"
 
#include "../core/endian_func.hpp"
 
#include "../base_media_base.h"
 
#include "midi.h"
 
#include <algorithm>
 

	
 
#include "../console_func.h"
 
#include "../console_internal.h"
 

	
 
/* SMF reader based on description at: http://www.somascape.org/midi/tech/mfile.html */
 

	
src/music/win32_m.cpp
Show inline comments
 
@@ -404,13 +404,13 @@ const char *MusicDriver_Win32::Start(con
 

	
 
	midiOutReset(_midi.midi_out);
 

	
 
	/* prepare multimedia timer */
 
	TIMECAPS timecaps;
 
	if (timeGetDevCaps(&timecaps, sizeof(timecaps)) == MMSYSERR_NOERROR) {
 
		_midi.time_period = min(max((UINT)resolution, timecaps.wPeriodMin), timecaps.wPeriodMax);
 
		_midi.time_period = std::min(std::max((UINT)resolution, timecaps.wPeriodMin), timecaps.wPeriodMax);
 
		if (timeBeginPeriod(_midi.time_period) == MMSYSERR_NOERROR) {
 
			/* success */
 
			DEBUG(driver, 2, "Win32-MIDI: Start: timer resolution is %d", (int)_midi.time_period);
 
			return nullptr;
 
		}
 
	}
src/music_gui.cpp
Show inline comments
 
@@ -502,13 +502,13 @@ struct MusicTrackSelectionWindow : publi
 

	
 
				for (MusicSystem::Playlist::const_iterator song = _music.music_set.begin(); song != _music.music_set.end(); ++song) {
 
					SetDParam(0, song->tracknr);
 
					SetDParam(1, 2);
 
					SetDParamStr(2, song->songname);
 
					Dimension d2 = GetStringBoundingBox(STR_PLAYLIST_TRACK_NAME);
 
					d.width = max(d.width, d2.width);
 
					d.width = std::max(d.width, d2.width);
 
					d.height += d2.height;
 
				}
 
				d.width += padding.width;
 
				d.height += padding.height;
 
				*size = maxdim(*size, d);
 
				break;
src/network/core/tcp_http.cpp
Show inline comments
 
@@ -247,14 +247,14 @@ int NetworkHTTPSocketHandler::Receive()
 
			this->callback->OnReceiveData(nullptr, 0);
 
			return 0;
 
		}
 

	
 
		/* Wait till we read the end-of-header identifier */
 
		if (this->recv_length == 0) {
 
			int read = this->recv_pos + res;
 
			int end = min(read, lengthof(this->recv_buffer) - 1);
 
			ssize_t read = this->recv_pos + res;
 
			ssize_t end = std::min<ssize_t>(read, lengthof(this->recv_buffer) - 1);
 

	
 
			/* Do a 'safe' search for the end of the header. */
 
			char prev = this->recv_buffer[end];
 
			this->recv_buffer[end] = '\0';
 
			char *end_of_header = strstr(this->recv_buffer, END_OF_HEADER);
 
			this->recv_buffer[end] = prev;
 
@@ -269,22 +269,22 @@ int NetworkHTTPSocketHandler::Receive()
 
				int ret = this->HandleHeader();
 
				if (ret <= 0) return ret;
 

	
 
				this->recv_length = ret;
 

	
 
				end_of_header += strlen(END_OF_HEADER);
 
				int len = min(read - (end_of_header - this->recv_buffer), res);
 
				int len = std::min(read - (end_of_header - this->recv_buffer), res);
 
				if (len != 0) {
 
					this->callback->OnReceiveData(end_of_header, len);
 
					this->recv_length -= len;
 
				}
 

	
 
				this->recv_pos = 0;
 
			}
 
		} else {
 
			res = min(this->recv_length, res);
 
			res = std::min<ssize_t>(this->recv_length, res);
 
			/* Receive whatever we're expecting. */
 
			this->callback->OnReceiveData(this->recv_buffer, res);
 
			this->recv_length -= res;
 
		}
 
	}
 
}
src/network/network_admin.cpp
Show inline comments
 
@@ -410,19 +410,19 @@ NetworkRecvStatus ServerNetworkAdminSock
 
		p->Send_uint8(company->index);
 

	
 
		/* Current information. */
 
		p->Send_uint64(company->money);
 
		p->Send_uint64(company->current_loan);
 
		p->Send_uint64(income);
 
		p->Send_uint16(min(UINT16_MAX, company->cur_economy.delivered_cargo.GetSum<OverflowSafeInt64>()));
 
		p->Send_uint16(static_cast<uint16>(std::min<uint64>(UINT16_MAX, company->cur_economy.delivered_cargo.GetSum<OverflowSafeInt64>())));
 

	
 
		/* Send stats for the last 2 quarters. */
 
		for (uint i = 0; i < 2; i++) {
 
			p->Send_uint64(company->old_economy[i].company_value);
 
			p->Send_uint16(company->old_economy[i].performance_history);
 
			p->Send_uint16(min(UINT16_MAX, company->old_economy[i].delivered_cargo.GetSum<OverflowSafeInt64>()));
 
			p->Send_uint16(static_cast<uint16>(std::min<uint64>(UINT16_MAX, company->old_economy[i].delivered_cargo.GetSum<OverflowSafeInt64>())));
 
		}
 

	
 
		this->SendPacket(p);
 
	}
 

	
 

	
src/network/network_chat_gui.cpp
Show inline comments
 
@@ -151,13 +151,13 @@ void NetworkUndrawChatMessage()
 
		Blitter *blitter = BlitterFactory::GetCurrentBlitter();
 
		int x      = _chatmsg_box.x;
 
		int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
 
		int width  = _chatmsg_box.width;
 
		int height = _chatmsg_box.height;
 
		if (y < 0) {
 
			height = max(height + y, min(_chatmsg_box.height, _screen.height));
 
			height = std::max(height + y, std::min(_chatmsg_box.height, _screen.height));
 
			y = 0;
 
		}
 
		if (x + width >= _screen.width) {
 
			width = _screen.width - x;
 
		}
 
		if (width <= 0 || height <= 0) return;
 
@@ -211,13 +211,13 @@ void NetworkDrawChatMessage()
 

	
 
	int x      = _chatmsg_box.x;
 
	int y      = _screen.height - _chatmsg_box.y - _chatmsg_box.height;
 
	int width  = _chatmsg_box.width;
 
	int height = _chatmsg_box.height;
 
	if (y < 0) {
 
		height = max(height + y, min(_chatmsg_box.height, _screen.height));
 
		height = std::max(height + y, std::min(_chatmsg_box.height, _screen.height));
 
		y = 0;
 
	}
 
	if (x + width >= _screen.width) {
 
		width = _screen.width - x;
 
	}
 
	if (width <= 0 || height <= 0) return;
 
@@ -232,13 +232,13 @@ void NetworkDrawChatMessage()
 
	int string_height = 0;
 
	for (uint i = 0; i < count; i++) {
 
		SetDParamStr(0, _chatmsg_list[i].message);
 
		string_height += GetStringLineCount(STR_JUST_RAW_STRING, width - 1) * FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING;
 
	}
 

	
 
	string_height = min(string_height, MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING));
 
	string_height = std::min<uint>(string_height, MAX_CHAT_MESSAGES * (FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING));
 

	
 
	int top = _screen.height - _chatmsg_box.y - string_height - 2;
 
	int bottom = _screen.height - _chatmsg_box.y - 2;
 
	/* Paint a half-transparent box behind the chat messages */
 
	GfxFillRect(_chatmsg_box.x, top - 2, _chatmsg_box.x + _chatmsg_box.width - 1, bottom,
 
			PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR // black, but with some alpha for background
src/network/network_client.cpp
Show inline comments
 
@@ -65,13 +65,13 @@ struct PacketReader : LoadFilter {
 
	 */
 
	void AddPacket(const Packet *p)
 
	{
 
		assert(this->read_bytes == 0);
 

	
 
		size_t in_packet = p->size - p->pos;
 
		size_t to_write  = min((size_t)(this->bufe - this->buf), in_packet);
 
		size_t to_write  = std::min<size_t>(this->bufe - this->buf, in_packet);
 
		const byte *pbuf = p->buffer + p->pos;
 

	
 
		this->written_bytes += in_packet;
 
		if (to_write != 0) {
 
			memcpy(this->buf, pbuf, to_write);
 
			this->buf += to_write;
 
@@ -90,23 +90,23 @@ struct PacketReader : LoadFilter {
 
		this->buf += to_write;
 
	}
 

	
 
	size_t Read(byte *rbuf, size_t size) override
 
	{
 
		/* Limit the amount to read to whatever we still have. */
 
		size_t ret_size = size = min(this->written_bytes - this->read_bytes, size);
 
		size_t ret_size = size = std::min(this->written_bytes - this->read_bytes, size);
 
		this->read_bytes += ret_size;
 
		const byte *rbufe = rbuf + ret_size;
 

	
 
		while (rbuf != rbufe) {
 
			if (this->buf == this->bufe) {
 
				this->buf = *this->block++;
 
				this->bufe = this->buf + CHUNK;
 
			}
 

	
 
			size_t to_write = min(this->bufe - this->buf, rbufe - rbuf);
 
			size_t to_write = std::min(this->bufe - this->buf, rbufe - rbuf);
 
			memcpy(rbuf, this->buf, to_write);
 
			rbuf += to_write;
 
			this->buf += to_write;
 
		}
 

	
 
		return ret_size;
src/network/network_content.cpp
Show inline comments
 
@@ -218,13 +218,13 @@ void ClientNetworkContentSocketHandler::
 

	
 
	while (count > 0) {
 
		/* We can "only" send a limited number of IDs in a single packet.
 
		 * A packet begins with the packet size and a byte for the type.
 
		 * Then this packet adds a uint16 for the count in this packet.
 
		 * The rest of the packet can be used for the IDs. */
 
		uint p_count = min(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
 
		uint p_count = std::min<uint>(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
 

	
 
		Packet *p = new Packet(PACKET_CONTENT_CLIENT_INFO_ID);
 
		p->Send_uint16(p_count);
 

	
 
		for (uint i = 0; i < p_count; i++) {
 
			p->Send_uint32(content_ids[i]);
 
@@ -360,13 +360,13 @@ void ClientNetworkContentSocketHandler::
 

	
 
	while (count > 0) {
 
		/* We can "only" send a limited number of IDs in a single packet.
 
		 * A packet begins with the packet size and a byte for the type.
 
		 * Then this packet adds a uint16 for the count in this packet.
 
		 * The rest of the packet can be used for the IDs. */
 
		uint p_count = min(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
 
		uint p_count = std::min<uint>(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
 

	
 
		Packet *p = new Packet(PACKET_CONTENT_CLIENT_CONTENT);
 
		p->Send_uint16(p_count);
 

	
 
		for (uint i = 0; i < p_count; i++) {
 
			p->Send_uint32(content_ids[i]);
src/network/network_content_gui.cpp
Show inline comments
 
@@ -572,13 +572,13 @@ public:
 
				}
 
				size->width = d.width + WD_MATRIX_RIGHT + WD_MATRIX_LEFT;
 
				break;
 
			}
 

	
 
			case WID_NCL_MATRIX:
 
				resize->height = max(this->checkbox_size.height, (uint)FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 
				resize->height = std::max(this->checkbox_size.height, (uint)FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 
				size->height = 10 * resize->height;
 
				break;
 
		}
 
	}
 

	
 

	
 
@@ -623,13 +623,13 @@ public:
 
	void DrawMatrix(const Rect &r) const
 
	{
 
		const NWidgetBase *nwi_checkbox = this->GetWidget<NWidgetBase>(WID_NCL_CHECKBOX);
 
		const NWidgetBase *nwi_name = this->GetWidget<NWidgetBase>(WID_NCL_NAME);
 
		const NWidgetBase *nwi_type = this->GetWidget<NWidgetBase>(WID_NCL_TYPE);
 

	
 
		int line_height = max(this->checkbox_size.height, (uint)FONT_HEIGHT_NORMAL);
 
		int line_height = std::max(this->checkbox_size.height, (uint)FONT_HEIGHT_NORMAL);
 

	
 
		/* Fill the matrix with the information */
 
		int sprite_y_offset = WD_MATRIX_TOP + (line_height - this->checkbox_size.height) / 2 - 1;
 
		int text_y_offset = WD_MATRIX_TOP + (line_height - FONT_HEIGHT_NORMAL) / 2;
 
		uint y = r.top;
 

	
 
@@ -874,13 +874,13 @@ public:
 
			case WKC_PAGEUP:
 
				/* scroll up a page */
 
				this->list_pos = (this->list_pos < this->vscroll->GetCapacity()) ? 0 : this->list_pos - this->vscroll->GetCapacity();
 
				break;
 
			case WKC_PAGEDOWN:
 
				/* scroll down a page */
 
				this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->content.size() - 1);
 
				this->list_pos = std::min(this->list_pos + this->vscroll->GetCapacity(), (int)this->content.size() - 1);
 
				break;
 
			case WKC_HOME:
 
				/* jump to beginning */
 
				this->list_pos = 0;
 
				break;
 
			case WKC_END:
src/network/network_gui.cpp
Show inline comments
 
@@ -120,13 +120,13 @@ public:
 
		this->resize_x = 1; // We only resize in this direction
 
		this->resize_y = 0; // We never resize in this direction
 

	
 
		/* First initialise some variables... */
 
		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
 
			child_wid->SetupSmallestSize(w, init_array);
 
			this->smallest_y = max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
 
			this->smallest_y = std::max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
 
		}
 

	
 
		/* ... then in a second pass make sure the 'current' sizes are set. Won't change for most widgets. */
 
		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
 
			child_wid->current_x = child_wid->smallest_x;
 
			child_wid->current_y = this->smallest_y;
 
@@ -495,18 +495,18 @@ public:
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_NG_MATRIX:
 
				resize->height = WD_MATRIX_TOP + max(GetSpriteSize(SPR_BLOT).height, (uint)FONT_HEIGHT_NORMAL) + WD_MATRIX_BOTTOM;
 
				resize->height = WD_MATRIX_TOP + std::max(GetSpriteSize(SPR_BLOT).height, (uint)FONT_HEIGHT_NORMAL) + WD_MATRIX_BOTTOM;
 
				size->height = 12 * resize->height;
 
				break;
 

	
 
			case WID_NG_LASTJOINED:
 
				size->height = WD_MATRIX_TOP + max(GetSpriteSize(SPR_BLOT).height, (uint)FONT_HEIGHT_NORMAL) + WD_MATRIX_BOTTOM;
 
				size->height = WD_MATRIX_TOP + std::max(GetSpriteSize(SPR_BLOT).height, (uint)FONT_HEIGHT_NORMAL) + WD_MATRIX_BOTTOM;
 
				break;
 

	
 
			case WID_NG_LASTJOINED_SPACER:
 
				size->width = NWidgetScrollbar::GetVerticalDimension().width;
 
				break;
 

	
 
@@ -542,13 +542,13 @@ public:
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
		switch (widget) {
 
			case WID_NG_MATRIX: {
 
				uint16 y = r.top;
 

	
 
				const int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (int)this->servers.size());
 
				const int max = std::min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (int)this->servers.size());
 

	
 
				for (int i = this->vscroll->GetPosition(); i < max; ++i) {
 
					const NetworkGameList *ngl = this->servers[i];
 
					this->DrawServerLine(ngl, y, ngl == this->server);
 
					y += this->resize.step_height;
 
				}
 
@@ -809,13 +809,13 @@ public:
 
					if (this->list_pos == SLP_INVALID) return ES_HANDLED;
 
					this->list_pos = (this->list_pos < this->vscroll->GetCapacity()) ? 0 : this->list_pos - this->vscroll->GetCapacity();
 
					break;
 
				case WKC_PAGEDOWN:
 
					/* scroll down a page */
 
					if (this->list_pos == SLP_INVALID) return ES_HANDLED;
 
					this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->servers.size() - 1);
 
					this->list_pos = std::min(this->list_pos + this->vscroll->GetCapacity(), (int)this->servers.size() - 1);
 
					break;
 
				case WKC_HOME:
 
					/* jump to beginning */
 
					this->list_pos = 0;
 
					break;
 
				case WKC_END:
 
@@ -901,13 +901,13 @@ GUIGameServerList::SortFunction * const 
 
GUIGameServerList::FilterFunction * const NetworkGameWindow::filter_funcs[] = {
 
	&NGameSearchFilter
 
};
 

	
 
static NWidgetBase *MakeResizableHeader(int *biggest_index)
 
{
 
	*biggest_index = max<int>(*biggest_index, WID_NG_INFO);
 
	*biggest_index = std::max<int>(*biggest_index, WID_NG_INFO);
 
	return new NWidgetServerListHeader();
 
}
 

	
 
static const NWidgetPart _nested_network_game_widgets[] = {
 
	/* TOP */
 
	NWidget(NWID_HORIZONTAL),
 
@@ -1858,19 +1858,19 @@ struct NetworkClientListWindow : Window 
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		if (widget != WID_CL_PANEL) return;
 

	
 
		this->server_client_width = max(GetStringBoundingBox(STR_NETWORK_SERVER).width, GetStringBoundingBox(STR_NETWORK_CLIENT).width) + WD_FRAMERECT_RIGHT;
 
		this->server_client_width = std::max(GetStringBoundingBox(STR_NETWORK_SERVER).width, GetStringBoundingBox(STR_NETWORK_CLIENT).width) + WD_FRAMERECT_RIGHT;
 
		this->icon_size = GetSpriteSize(SPR_COMPANY_ICON);
 
		this->line_height = max(this->icon_size.height + 2U, (uint)FONT_HEIGHT_NORMAL);
 
		this->line_height = std::max(this->icon_size.height + 2U, (uint)FONT_HEIGHT_NORMAL);
 

	
 
		uint width = 100; // Default width
 
		for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
 
			width = max(width, GetStringBoundingBox(ci->client_name).width);
 
			width = std::max(width, GetStringBoundingBox(ci->client_name).width);
 
		}
 

	
 
		size->width = WD_FRAMERECT_LEFT + this->server_client_width + this->icon_size.width + WD_FRAMERECT_LEFT + width + WD_FRAMERECT_RIGHT;
 
	}
 

	
 
	void OnPaint() override
 
@@ -2025,24 +2025,24 @@ struct NetworkJoinStatusWindow : Window 
 

	
 
		size->height = 25 + 2 * FONT_HEIGHT_NORMAL;
 

	
 
		/* Account for the statuses */
 
		uint width = 0;
 
		for (uint i = 0; i < NETWORK_JOIN_STATUS_END; i++) {
 
			width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_1 + i).width);
 
			width = std::max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_1 + i).width);
 
		}
 

	
 
		/* For the number of waiting (other) players */
 
		SetDParamMaxValue(0, MAX_CLIENTS);
 
		width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_WAITING).width);
 
		width = std::max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_WAITING).width);
 

	
 
		/* Account for downloading ~ 10 MiB */
 
		SetDParamMaxDigits(0, 8);
 
		SetDParamMaxDigits(1, 8);
 
		width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_DOWNLOADING_1).width);
 
		width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_DOWNLOADING_2).width);
 
		width = std::max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_DOWNLOADING_1).width);
 
		width = std::max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_DOWNLOADING_2).width);
 

	
 
		/* Give a bit more clearing for the widest strings than strictly needed */
 
		size->width = width + WD_FRAMERECT_LEFT + WD_FRAMERECT_BOTTOM + 10;
 
	}
 

	
 
	void OnClick(Point pt, int widget, int click_count) override
src/network/network_server.cpp
Show inline comments
 
@@ -171,13 +171,13 @@ struct PacketWriter : SaveFilter {
 
		if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA);
 

	
 
		std::lock_guard<std::mutex> lock(this->mutex);
 

	
 
		byte *bufe = buf + size;
 
		while (buf != bufe) {
 
			size_t to_write = min(SEND_MTU - this->current->size, bufe - buf);
 
			size_t to_write = std::min<size_t>(SEND_MTU - this->current->size, bufe - buf);
 
			memcpy(this->current->buffer + this->current->size, buf, to_write);
 
			this->current->size += (PacketSize)to_write;
 
			buf += to_write;
 

	
 
			if (this->current->size == SEND_MTU) {
 
				this->AppendQueue();
 
@@ -1804,13 +1804,13 @@ void NetworkServer_Tick(bool send_frame)
 

	
 
	/* Now we are done with the frame, inform the clients that they can
 
	 *  do their frame! */
 
	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
 
		/* We allow a number of bytes per frame, but only to the burst amount
 
		 * to be available for packet receiving at any particular time. */
 
		cs->receive_limit = min(cs->receive_limit + _settings_client.network.bytes_per_frame,
 
		cs->receive_limit = std::min<int>(cs->receive_limit + _settings_client.network.bytes_per_frame,
 
				_settings_client.network.bytes_per_frame_burst);
 

	
 
		/* Check if the speed of the client is what we can expect from a client */
 
		uint lag = NetworkCalculateLag(cs);
 
		switch (cs->status) {
 
			case NetworkClientSocket::STATUS_ACTIVE:
src/network/network_udp.cpp
Show inline comments
 
@@ -260,13 +260,13 @@ void ServerNetworkUDPSocketHandler::Rece
 
		if (f == nullptr) continue; // The GRF is unknown to this server
 

	
 
		/* If the reply might exceed the size of the packet, only reply
 
		 * the current list and do not send the other data.
 
		 * The name could be an empty string, if so take the filename. */
 
		packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
 
				min(strlen(f->GetName()) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
 
				std::min(strlen(f->GetName()) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
 
		if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
 
			break;
 
		}
 
		in_reply[in_reply_count] = f;
 
		in_reply_count++;
 
	}
src/newgrf.cpp
Show inline comments
 
@@ -7,13 +7,12 @@
 

	
 
/** @file newgrf.cpp Base of all NewGRF support. */
 

	
 
#include "stdafx.h"
 

	
 
#include <stdarg.h>
 
#include <algorithm>
 

	
 
#include "debug.h"
 
#include "fileio_func.h"
 
#include "engine_func.h"
 
#include "engine_base.h"
 
#include "bridge.h"
 
@@ -660,13 +659,13 @@ static Engine *GetNewEngine(const GRFFil
 
	/* Reserve the engine slot */
 
	assert(_engine_mngr.size() == e->index);
 
	_engine_mngr.push_back({
 
			scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
 
			internal_id,
 
			type,
 
			static_cast<uint8>(min(internal_id, _engine_counts[type])) // substitute_id == _engine_counts[subtype] means "no substitute"
 
			std::min<uint8>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
 
	});
 

	
 
	if (engine_pool_size != Engine::GetPoolSize()) {
 
		/* Resize temporary engine data ... */
 
		_gted = ReallocT(_gted, Engine::GetPoolSize());
 

	
 
@@ -2457,13 +2456,13 @@ static ChangeInfoResult TownHouseChangeI
 

	
 
				_house_mngr.Add(hid + i, _cur.grffile->grfid, override);
 
				break;
 
			}
 

	
 
			case 0x16: // Periodic refresh multiplier
 
				housespec->processing_time = min(buf->ReadByte(), 63);
 
				housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
 
				break;
 

	
 
			case 0x17: // Four random colours to use
 
				for (uint j = 0; j < 4; j++) housespec->random_colour[j] = buf->ReadByte();
 
				break;
 

	
 
@@ -2639,13 +2638,13 @@ static ChangeInfoResult GlobalVarChangeI
 
		switch (prop) {
 
			case 0x08: { // Cost base factor
 
				int factor = buf->ReadByte();
 
				uint price = gvid + i;
 

	
 
				if (price < PR_END) {
 
					_cur.grffile->price_base_multipliers[price] = min<int>(factor - 8, MAX_PRICE_MODIFIER);
 
					_cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
 
				} else {
 
					grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
 
				}
 
				break;
 
			}
 

	
 
@@ -3026,13 +3025,13 @@ static ChangeInfoResult CargoChangeInfo(
 

	
 
			case 0x1A: // Bitmask of callbacks to use
 
				cs->callback_mask = buf->ReadByte();
 
				break;
 

	
 
			case 0x1D: // Vehicle capacity muliplier
 
				cs->multiplier = max<uint16>(1u, buf->ReadWord());
 
				cs->multiplier = std::max<uint16>(1u, buf->ReadWord());
 
				break;
 

	
 
			default:
 
				ret = CIR_UNKNOWN;
 
				break;
 
		}
 
@@ -3908,17 +3907,17 @@ static ChangeInfoResult AirportChangeInf
 
							} else if (att[k].gfx == 0xFF) {
 
								att[k].ti.x = (int8)GB(att[k].ti.x, 0, 8);
 
								att[k].ti.y = (int8)GB(att[k].ti.y, 0, 8);
 
							}
 

	
 
							if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
 
								as->size_x = max<byte>(as->size_x, att[k].ti.y + 1);
 
								as->size_y = max<byte>(as->size_y, att[k].ti.x + 1);
 
								as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
 
								as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
 
							} else {
 
								as->size_x = max<byte>(as->size_x, att[k].ti.x + 1);
 
								as->size_y = max<byte>(as->size_y, att[k].ti.y + 1);
 
								as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
 
								as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
 
							}
 
						}
 
						tile_table[j] = CallocT<AirportTileTable>(size);
 
						memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
 
					}
 
					/* Install final layout construction in the airport spec */
 
@@ -5194,13 +5193,13 @@ static void NewSpriteGroup(ByteReader *b
 
				}
 

	
 
				case GSF_HOUSES:
 
				case GSF_AIRPORTTILES:
 
				case GSF_OBJECTS:
 
				case GSF_INDUSTRYTILES: {
 
					byte num_building_sprites = max((uint8)1, type);
 
					byte num_building_sprites = std::max((uint8)1, type);
 

	
 
					assert(TileLayoutSpriteGroup::CanAllocateItem());
 
					TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
 
					group->nfo_line = _cur.nfo_line;
 
					act_group = group;
 

	
 
@@ -6069,13 +6068,13 @@ static uint16 SanitizeSpriteOffset(uint1
 
		return orig_num;
 
	}
 

	
 
	if (offset + num > max_sprites) {
 
		grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
 
		uint orig_num = num;
 
		num = max(max_sprites - offset, 0);
 
		num = std::max(max_sprites - offset, 0);
 
		return orig_num - num;
 
	}
 

	
 
	return 0;
 
}
 

	
 
@@ -6230,13 +6229,13 @@ static void SkipAct5(ByteReader *buf)
 
 * @return true iff the variable is known and the value is returned in 'value'.
 
 */
 
bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
 
{
 
	switch (param) {
 
		case 0x00: // current date
 
			*value = max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
 
			*value = std::max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
 
			return true;
 

	
 
		case 0x01: // current year
 
			*value = Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
			return true;
 

	
 
@@ -6951,13 +6950,13 @@ static void SafeParamSet(ByteReader *buf
 

	
 

	
 
static uint32 GetPatchVariable(uint8 param)
 
{
 
	switch (param) {
 
		/* start year - 1920 */
 
		case 0x0B: return max(_settings_game.game_creation.starting_year, ORIGINAL_BASE_YEAR) - ORIGINAL_BASE_YEAR;
 
		case 0x0B: return std::max(_settings_game.game_creation.starting_year, ORIGINAL_BASE_YEAR) - ORIGINAL_BASE_YEAR;
 

	
 
		/* freight trains weight factor */
 
		case 0x0E: return _settings_game.vehicle.freight_trains;
 

	
 
		/* empty wagon speed increase */
 
		case 0x0F: return 0;
 
@@ -6990,21 +6989,21 @@ static uint32 GetPatchVariable(uint8 par
 
		 * SS : combination of both X and Y, thus giving the size(log2) of the map
 
		 */
 
		case 0x13: {
 
			byte map_bits = 0;
 
			byte log_X = MapLogX() - 6; // subtraction is required to make the minimal size (64) zero based
 
			byte log_Y = MapLogY() - 6;
 
			byte max_edge = max(log_X, log_Y);
 
			byte max_edge = std::max(log_X, log_Y);
 

	
 
			if (log_X == log_Y) { // we have a squared map, since both edges are identical
 
				SetBit(map_bits, 0);
 
			} else {
 
				if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
 
			}
 

	
 
			return (map_bits << 24) | (min(log_X, log_Y) << 20) | (max_edge << 16) |
 
			return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
 
				(log_X << 12) | (log_Y << 8) | (log_X + log_Y);
 
		}
 

	
 
		/* The maximum height of the map. */
 
		case 0x14:
 
			return _settings_game.construction.max_heightlevel;
 
@@ -7822,13 +7821,13 @@ static bool ChangeGRFURL(byte langid, co
 
static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
 
{
 
	if (len != 1) {
 
		grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
 
		buf->Skip(len);
 
	} else {
 
		_cur.grfconfig->num_valid_params = min(buf->ReadByte(), lengthof(_cur.grfconfig->param));
 
		_cur.grfconfig->num_valid_params = std::min<byte>(buf->ReadByte(), lengthof(_cur.grfconfig->param));
 
	}
 
	return true;
 
}
 

	
 
/** Callback function for 'INFO'->'PALS' to set the number of valid parameters. */
 
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
 
@@ -7976,14 +7975,14 @@ static bool ChangeGRFParamMask(size_t le
 
		byte param_nr = buf->ReadByte();
 
		if (param_nr >= lengthof(_cur.grfconfig->param)) {
 
			grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
 
			buf->Skip(len - 1);
 
		} else {
 
			_cur_parameter->param_nr = param_nr;
 
			if (len >= 2) _cur_parameter->first_bit = min(buf->ReadByte(), 31);
 
			if (len >= 3) _cur_parameter->num_bit = min(buf->ReadByte(), 32 - _cur_parameter->first_bit);
 
			if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
 
			if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
 
		}
 
	}
 

	
 
	return true;
 
}
 

	
src/newgrf_config.cpp
Show inline comments
 
@@ -257,13 +257,13 @@ void GRFParameterInfo::SetValue(struct G
 
	/* SB doesn't work correctly with nbits == 32, so handle that case here. */
 
	if (this->num_bit == 32) {
 
		config->param[this->param_nr] = value;
 
	} else {
 
		SB(config->param[this->param_nr], this->first_bit, this->num_bit, value);
 
	}
 
	config->num_params = max<uint>(config->num_params, this->param_nr + 1);
 
	config->num_params = std::max<uint>(config->num_params, this->param_nr + 1);
 
	SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
 
}
 

	
 
/**
 
 * Finalize Action 14 info after file scan is finished.
 
 */
 
@@ -336,13 +336,13 @@ static bool CalcGRFMD5Sum(GRFConfig *con
 

	
 
	/* open the file */
 
	f = FioFOpenFile(config->filename, "rb", subdir, &size);
 
	if (f == nullptr) return false;
 

	
 
	long start = ftell(f);
 
	size = min(size, GRFGetSizeOfDataSection(f));
 
	size = std::min(size, GRFGetSizeOfDataSection(f));
 

	
 
	if (start < 0 || fseek(f, start, SEEK_SET) < 0) {
 
		FioFCloseFile(f);
 
		return false;
 
	}
 

	
src/newgrf_debug_gui.cpp
Show inline comments
 
@@ -371,18 +371,18 @@ struct NewGRFInspectWindow : Window {
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_NGRFI_VEH_CHAIN: {
 
				assert(this->HasChainIndex());
 
				GrfSpecFeature f = GetFeatureNum(this->window_number);
 
				size->height = max(size->height, GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height + 2 + WD_BEVEL_TOP + WD_BEVEL_BOTTOM);
 
				size->height = std::max(size->height, GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height + 2 + WD_BEVEL_TOP + WD_BEVEL_BOTTOM);
 
				break;
 
			}
 

	
 
			case WID_NGRFI_MAINPANEL:
 
				resize->height = max(11, FONT_HEIGHT_NORMAL + 1);
 
				resize->height = std::max(11, FONT_HEIGHT_NORMAL + 1);
 
				resize->width  = 1;
 

	
 
				size->height = 5 * resize->height + TOP_OFFSET + BOTTOM_OFFSET;
 
				break;
 
		}
 
	}
 
@@ -427,13 +427,13 @@ struct NewGRFInspectWindow : Window {
 
				}
 

	
 
				int width = r.right + 1 - r.left - WD_BEVEL_LEFT - WD_BEVEL_RIGHT;
 
				int skip = 0;
 
				if (total_width > width) {
 
					int sel_center = (sel_start + sel_end) / 2;
 
					if (sel_center > width / 2) skip = min(total_width - width, sel_center - width / 2);
 
					if (sel_center > width / 2) skip = std::min(total_width - width, sel_center - width / 2);
 
				}
 

	
 
				GrfSpecFeature f = GetFeatureNum(this->window_number);
 
				int h = GetVehicleImageCellSize((VehicleType)(VEH_TRAIN + (f - GSF_TRAINS)), EIT_IN_DEPOT).height;
 
				int y = (r.top + r.bottom - h) / 2;
 
				DrawVehicleImage(v->First(), r.left + WD_BEVEL_LEFT, r.right - WD_BEVEL_RIGHT, y + 1, INVALID_VEHICLE, EIT_IN_DETAILS, skip);
 
@@ -858,13 +858,13 @@ struct SpriteAlignerWindow : Window {
 
	{
 
		switch (widget) {
 
			case WID_SA_SPRITE:
 
				size->height = ScaleGUITrad(200);
 
				break;
 
			case WID_SA_LIST:
 
				resize->height = max(11, FONT_HEIGHT_NORMAL + 1);
 
				resize->height = std::max(11, FONT_HEIGHT_NORMAL + 1);
 
				resize->width  = 1;
 
				break;
 
			default:
 
				break;
 
		}
 
	}
 
@@ -894,13 +894,13 @@ struct SpriteAlignerWindow : Window {
 

	
 
			case WID_SA_LIST: {
 
				const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget);
 
				int step_size = nwid->resize_y;
 

	
 
				std::vector<SpriteID> &list = _newgrf_debug_sprite_picker.sprites;
 
				int max = min<int>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (uint)list.size());
 
				int max = std::min<int>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (uint)list.size());
 

	
 
				int y = r.top + WD_FRAMERECT_TOP;
 
				for (int i = this->vscroll->GetPosition(); i < max; i++) {
 
					SetDParam(0, list[i]);
 
					DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_BLACK_COMMA, TC_FROMSTRING, SA_RIGHT | SA_FORCE);
 
					y += step_size;
src/newgrf_engine.cpp
Show inline comments
 
@@ -937,14 +937,14 @@ static uint32 VehicleGetVariable(Vehicle
 
	bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
 

	
 
	uint totalsets = in_motion ? group->num_loaded : group->num_loading;
 

	
 
	if (totalsets == 0) return nullptr;
 

	
 
	uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
 
	set = min(set, totalsets - 1);
 
	uint set = (v->cargo.StoredCount() * totalsets) / std::max<uint16>(1u, v->cargo_cap);
 
	set = std::min(set, totalsets - 1);
 

	
 
	return in_motion ? group->loaded[set] : group->loading[set];
 
}
 

	
 
GrfSpecFeature VehicleResolverObject::GetFeature() const
 
{
src/newgrf_gui.cpp
Show inline comments
 
@@ -190,14 +190,14 @@ struct NewGRFParametersWindow : public W
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_NP_NUMPAR_DEC:
 
			case WID_NP_NUMPAR_INC: {
 
				size->width  = max(SETTING_BUTTON_WIDTH / 2, FONT_HEIGHT_NORMAL);
 
				size->height = max(SETTING_BUTTON_HEIGHT, FONT_HEIGHT_NORMAL);
 
				size->width  = std::max(SETTING_BUTTON_WIDTH / 2, FONT_HEIGHT_NORMAL);
 
				size->height = std::max(SETTING_BUTTON_HEIGHT, FONT_HEIGHT_NORMAL);
 
				break;
 
			}
 

	
 
			case WID_NP_NUMPAR: {
 
				SetDParamMaxValue(0, lengthof(this->grf_config->param));
 
				Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
 
@@ -205,13 +205,13 @@ struct NewGRFParametersWindow : public W
 
				d.height += padding.height;
 
				*size = maxdim(*size, d);
 
				break;
 
			}
 

	
 
			case WID_NP_BACKGROUND:
 
				this->line_height = max(SETTING_BUTTON_HEIGHT, FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 
				this->line_height = std::max(SETTING_BUTTON_HEIGHT, FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 

	
 
				resize->width = 1;
 
				resize->height = this->line_height;
 
				size->height = 5 * this->line_height;
 
				break;
 

	
 
@@ -718,31 +718,31 @@ struct NewGRFWindow : public Window, New
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		switch (widget) {
 
			case WID_NS_FILE_LIST:
 
			{
 
				Dimension d = maxdim(GetSpriteSize(SPR_SQUARE), GetSpriteSize(SPR_WARNING_SIGN));
 
				resize->height = max(d.height + 2U, FONT_HEIGHT_NORMAL + 2U);
 
				size->height = max(size->height, WD_FRAMERECT_TOP + 6 * resize->height + WD_FRAMERECT_BOTTOM);
 
				resize->height = std::max(d.height + 2U, FONT_HEIGHT_NORMAL + 2U);
 
				size->height = std::max(size->height, WD_FRAMERECT_TOP + 6 * resize->height + WD_FRAMERECT_BOTTOM);
 
				break;
 
			}
 

	
 
			case WID_NS_AVAIL_LIST:
 
				resize->height = max(12, FONT_HEIGHT_NORMAL + 2);
 
				size->height = max(size->height, WD_FRAMERECT_TOP + 8 * resize->height + WD_FRAMERECT_BOTTOM);
 
				resize->height = std::max(12, FONT_HEIGHT_NORMAL + 2);
 
				size->height = std::max(size->height, WD_FRAMERECT_TOP + 8 * resize->height + WD_FRAMERECT_BOTTOM);
 
				break;
 

	
 
			case WID_NS_NEWGRF_INFO_TITLE: {
 
				Dimension dim = GetStringBoundingBox(STR_NEWGRF_SETTINGS_INFO_TITLE);
 
				size->height = max(size->height, dim.height + WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM);
 
				size->width  = max(size->width,  dim.width  + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
 
				size->height = std::max(size->height, dim.height + WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM);
 
				size->width  = std::max(size->width,  dim.width  + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
 
				break;
 
			}
 

	
 
			case WID_NS_NEWGRF_INFO:
 
				size->height = max(size->height, WD_FRAMERECT_TOP + 10 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + padding.height + 2);
 
				size->height = std::max(size->height, WD_FRAMERECT_TOP + 10 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + padding.height + 2);
 
				break;
 

	
 
			case WID_NS_PRESET_LIST: {
 
				Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
 
				for (const auto &i : this->grf_presets) {
 
					SetDParamStr(0, i.c_str());
 
@@ -874,13 +874,13 @@ struct NewGRFWindow : public Window, New
 
				GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, this->active_over == -2 ? PC_DARK_GREY : PC_BLACK);
 

	
 
				uint step_height = this->GetWidget<NWidgetBase>(WID_NS_AVAIL_LIST)->resize_y;
 
				int offset_y = (step_height - FONT_HEIGHT_NORMAL) / 2;
 
				uint y = r.top + WD_FRAMERECT_TOP;
 
				uint min_index = this->vscroll2->GetPosition();
 
				uint max_index = min(min_index + this->vscroll2->GetCapacity(), (uint)this->avails.size());
 
				uint max_index = std::min(min_index + this->vscroll2->GetCapacity(), (uint)this->avails.size());
 

	
 
				for (uint i = min_index; i < max_index; i++) {
 
					const GRFConfig *c = this->avails[i];
 
					bool h = (c == this->avail_sel);
 
					const char *text = c->GetName();
 

	
 
@@ -1308,13 +1308,13 @@ struct NewGRFWindow : public Window, New
 
				/* scroll up a page */
 
				this->avail_pos = (this->avail_pos < this->vscroll2->GetCapacity()) ? 0 : this->avail_pos - this->vscroll2->GetCapacity();
 
				break;
 

	
 
			case WKC_PAGEDOWN:
 
				/* scroll down a page */
 
				this->avail_pos = min(this->avail_pos + this->vscroll2->GetCapacity(), (int)this->avails.size() - 1);
 
				this->avail_pos = std::min(this->avail_pos + this->vscroll2->GetCapacity(), (int)this->avails.size() - 1);
 
				break;
 

	
 
			case WKC_HOME:
 
				/* jump to beginning */
 
				this->avail_pos = 0;
 
				break;
 
@@ -1360,13 +1360,13 @@ struct NewGRFWindow : public Window, New
 
				/* Get pointer to the selected file in the active list. */
 
				int from_pos = 0;
 
				GRFConfig **from_prev;
 
				for (from_prev = &this->actives; *from_prev != this->active_sel; from_prev = &(*from_prev)->next, from_pos++) {}
 

	
 
				/* Gets the drag-and-drop destination offset. Ignore the last dummy line. */
 
				int to_pos = min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 2);
 
				int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 2);
 
				if (to_pos != from_pos) { // Don't move NewGRF file over itself.
 
					/* Get pointer to destination position. */
 
					GRFConfig **to_prev = &this->actives;
 
					for (int i = from_pos < to_pos ? -1 : 0; *to_prev != nullptr && i < to_pos; to_prev = &(*to_prev)->next, i++) {}
 

	
 
					/* Detach NewGRF file from its original position. */
 
@@ -1378,13 +1378,13 @@ struct NewGRFWindow : public Window, New
 

	
 
					this->vscroll->ScrollTowards(to_pos);
 
					this->preset = -1;
 
					this->InvalidateData();
 
				}
 
			} else if (this->avail_sel != nullptr) {
 
				int to_pos = min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 1);
 
				int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 1);
 
				this->AddGRFToActive(to_pos);
 
			}
 
		} else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
 
			/* Remove active NewGRF file by dragging it over available list. */
 
			Point dummy = {-1, -1};
 
			this->OnClick(dummy, WID_NS_REMOVE, 1);
 
@@ -1404,13 +1404,13 @@ struct NewGRFWindow : public Window, New
 
		if (!this->editable) return;
 

	
 
		if (widget == WID_NS_FILE_LIST && (this->active_sel != nullptr || this->avail_sel != nullptr)) {
 
			/* An NewGRF file is dragged over the active list. */
 
			int to_pos = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST);
 
			/* Skip the last dummy line if the source is from the active list. */
 
			to_pos = min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
 
			to_pos = std::min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
 

	
 
			if (to_pos != this->active_over) {
 
				this->active_over = to_pos;
 
				this->SetWidgetDirty(WID_NS_FILE_LIST);
 
			}
 
		} else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
 
@@ -1617,14 +1617,14 @@ public:
 

	
 
		uint min_avs_height = this->avs->smallest_y + this->avs->padding_top + this->avs->padding_bottom;
 
		uint min_acs_height = this->acs->smallest_y + this->acs->padding_top + this->acs->padding_bottom;
 
		uint min_inf_height = this->inf->smallest_y + this->inf->padding_top + this->inf->padding_bottom;
 

	
 
		/* Smallest window is in two column mode. */
 
		this->smallest_x = max(min_avs_width, min_acs_width) + INTER_COLUMN_SPACING + min_inf_width;
 
		this->smallest_y = max(min_inf_height, min_acs_height + INTER_LIST_SPACING + min_avs_height);
 
		this->smallest_x = std::max(min_avs_width, min_acs_width) + INTER_COLUMN_SPACING + min_inf_width;
 
		this->smallest_y = std::max(min_inf_height, min_acs_height + INTER_LIST_SPACING + min_avs_height);
 

	
 
		/* Filling. */
 
		this->fill_x = LeastCommonMultiple(this->avs->fill_x, this->acs->fill_x);
 
		if (this->inf->fill_x > 0 && (this->fill_x == 0 || this->fill_x > this->inf->fill_x)) this->fill_x = this->inf->fill_x;
 

	
 
		this->fill_y = this->avs->fill_y;
 
@@ -1648,41 +1648,41 @@ public:
 
		this->StoreSizePosition(sizing, x, y, given_width, given_height);
 

	
 
		uint min_avs_width = this->avs->smallest_x + this->avs->padding_left + this->avs->padding_right;
 
		uint min_acs_width = this->acs->smallest_x + this->acs->padding_left + this->acs->padding_right;
 
		uint min_inf_width = this->inf->smallest_x + this->inf->padding_left + this->inf->padding_right;
 

	
 
		uint min_list_width = max(min_avs_width, min_acs_width); // Smallest width of the lists such that they have equal width (incl padding).
 
		uint min_list_width = std::max(min_avs_width, min_acs_width); // Smallest width of the lists such that they have equal width (incl padding).
 
		uint avs_extra_width = min_list_width - min_avs_width;   // Additional width needed for avs to reach min_list_width.
 
		uint acs_extra_width = min_list_width - min_acs_width;   // Additional width needed for acs to reach min_list_width.
 

	
 
		/* Use 2 or 3 columns? */
 
		uint min_three_columns = min_avs_width + min_acs_width + min_inf_width + 2 * INTER_COLUMN_SPACING;
 
		uint min_two_columns   = min_list_width + min_inf_width + INTER_COLUMN_SPACING;
 
		bool use_three_columns = this->editable && (min_three_columns + MIN_EXTRA_FOR_3_COLUMNS <= given_width);
 

	
 
		/* Info panel is a separate column in both modes. Compute its width first. */
 
		uint extra_width, inf_width;
 
		if (use_three_columns) {
 
			extra_width = given_width - min_three_columns;
 
			inf_width = min(MAX_EXTRA_INFO_WIDTH, extra_width / 2);
 
			inf_width = std::min(MAX_EXTRA_INFO_WIDTH, extra_width / 2);
 
		} else {
 
			extra_width = given_width - min_two_columns;
 
			inf_width = min(MAX_EXTRA_INFO_WIDTH, extra_width / 2);
 
			inf_width = std::min(MAX_EXTRA_INFO_WIDTH, extra_width / 2);
 
		}
 
		inf_width = ComputeMaxSize(this->inf->smallest_x, this->inf->smallest_x + inf_width, this->inf->GetHorizontalStepSize(sizing));
 
		extra_width -= inf_width - this->inf->smallest_x;
 

	
 
		uint inf_height = ComputeMaxSize(this->inf->smallest_y, given_height, this->inf->GetVerticalStepSize(sizing));
 

	
 
		if (use_three_columns) {
 
			/* Three column display, first make both lists equally wide, then divide whatever is left between both lists.
 
			 * Only keep track of what avs gets, all other space goes to acs. */
 
			uint avs_width = min(avs_extra_width, extra_width);
 
			uint avs_width = std::min(avs_extra_width, extra_width);
 
			extra_width -= avs_width;
 
			extra_width -= min(acs_extra_width, extra_width);
 
			extra_width -= std::min(acs_extra_width, extra_width);
 
			avs_width += extra_width / 2;
 

	
 
			avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_width, this->avs->GetHorizontalStepSize(sizing));
 

	
 
			uint acs_width = given_width - // Remaining space, including horizontal padding.
 
					inf_width - this->inf->padding_left - this->inf->padding_right -
 
@@ -1751,13 +1751,13 @@ public:
 
					this->avs->AssignSizePosition(sizing, x + this->avs->padding_left, y + given_height - avs_height - this->avs->padding_bottom, avs_width, avs_height, rtl);
 
				} else {
 
					this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
 
				}
 
				uint dx = this->acs->current_x + this->acs->padding_left + this->acs->padding_right;
 
				if (this->editable) {
 
					dx = max(dx, this->avs->current_x + this->avs->padding_left + this->avs->padding_right);
 
					dx = std::max(dx, this->avs->current_x + this->avs->padding_left + this->avs->padding_right);
 
				}
 
				x += dx + INTER_COLUMN_SPACING + this->inf->padding_left;
 
				this->inf->AssignSizePosition(sizing, x, y + this->inf->padding_top, inf_width, inf_height, rtl);
 
			}
 
		}
 
	}
 
@@ -1911,16 +1911,16 @@ static const NWidgetPart _nested_newgrf_
 
NWidgetBase* NewGRFDisplay(int *biggest_index)
 
{
 
	NWidgetBase *avs = MakeNWidgets(_nested_newgrf_availables_widgets, lengthof(_nested_newgrf_availables_widgets), biggest_index, nullptr);
 

	
 
	int biggest2;
 
	NWidgetBase *acs = MakeNWidgets(_nested_newgrf_actives_widgets, lengthof(_nested_newgrf_actives_widgets), &biggest2, nullptr);
 
	*biggest_index = max(*biggest_index, biggest2);
 
	*biggest_index = std::max(*biggest_index, biggest2);
 

	
 
	NWidgetBase *inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, lengthof(_nested_newgrf_infopanel_widgets), &biggest2, nullptr);
 
	*biggest_index = max(*biggest_index, biggest2);
 
	*biggest_index = std::max(*biggest_index, biggest2);
 

	
 
	return new NWidgetNewGRFDisplay(avs, acs, inf);
 
}
 

	
 
/* Widget definition of the manage newgrfs window */
 
static const NWidgetPart _nested_newgrf_widgets[] = {
 
@@ -2074,14 +2074,14 @@ struct SavePresetWindow : public Window 
 
		switch (widget) {
 
			case WID_SVP_PRESET_LIST: {
 
				resize->height = FONT_HEIGHT_NORMAL + 2U;
 
				size->height = 0;
 
				for (uint i = 0; i < this->presets.size(); i++) {
 
					Dimension d = GetStringBoundingBox(this->presets[i].c_str());
 
					size->width = max(size->width, d.width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
 
					resize->height = max(resize->height, d.height);
 
					size->width = std::max(size->width, d.width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
 
					resize->height = std::max(resize->height, d.height);
 
				}
 
				size->height = ClampU((uint)this->presets.size(), 5, 20) * resize->height + 1;
 
				break;
 
			}
 
		}
 
	}
 
@@ -2093,13 +2093,13 @@ struct SavePresetWindow : public Window 
 
				GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_BLACK);
 

	
 
				uint step_height = this->GetWidget<NWidgetBase>(WID_SVP_PRESET_LIST)->resize_y;
 
				int offset_y = (step_height - FONT_HEIGHT_NORMAL) / 2;
 
				uint y = r.top + WD_FRAMERECT_TOP;
 
				uint min_index = this->vscroll->GetPosition();
 
				uint max_index = min(min_index + this->vscroll->GetCapacity(), (uint)this->presets.size());
 
				uint max_index = std::min(min_index + this->vscroll->GetCapacity(), (uint)this->presets.size());
 

	
 
				for (uint i = min_index; i < max_index; i++) {
 
					if ((int)i == this->selected) GfxFillRect(r.left + 1, y, r.right - 1, y + step_height - 2, PC_DARK_BLUE);
 

	
 
					const char *text = this->presets[i].c_str();
 
					DrawString(r.left + WD_FRAMERECT_LEFT, r.right, y + offset_y, text, ((int)i == this->selected) ? TC_WHITE : TC_SILVER);
 
@@ -2206,25 +2206,25 @@ struct ScanProgressWindow : public Windo
 

	
 
			case WID_SP_PROGRESS_TEXT:
 
				SetDParamMaxDigits(0, 4);
 
				SetDParamMaxDigits(1, 4);
 
				/* We really don't know the width. We could determine it by scanning the NewGRFs,
 
				 * but this is the status window for scanning them... */
 
				size->width = max(400U, GetStringBoundingBox(STR_NEWGRF_SCAN_STATUS).width);
 
				size->width = std::max(400U, GetStringBoundingBox(STR_NEWGRF_SCAN_STATUS).width);
 
				size->height = FONT_HEIGHT_NORMAL * 2 + WD_PAR_VSEP_NORMAL;
 
				break;
 
		}
 
	}
 

	
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
		switch (widget) {
 
			case WID_SP_PROGRESS_BAR: {
 
				/* Draw the % complete with a bar and a text */
 
				DrawFrameRect(r.left, r.top, r.right, r.bottom, COLOUR_GREY, FR_BORDERONLY);
 
				uint percent = scanned * 100 / max(1U, _settings_client.gui.last_newgrf_count);
 
				uint percent = scanned * 100 / std::max(1U, _settings_client.gui.last_newgrf_count);
 
				DrawFrameRect(r.left + 1, r.top + 1, (int)((r.right - r.left - 2) * percent / 100) + r.left + 1, r.bottom - 1, COLOUR_MAUVE, FR_NONE);
 
				SetDParam(0, percent);
 
				DrawString(r.left, r.right, r.top + 5, STR_GENERATION_PROGRESS, TC_FROMSTRING, SA_HOR_CENTER);
 
				break;
 
			}
 

	
src/newgrf_industries.cpp
Show inline comments
 
@@ -91,13 +91,13 @@ uint32 GetIndustryIDAtOffset(TileIndex t
 
static uint32 GetClosestIndustry(TileIndex tile, IndustryType type, const Industry *current)
 
{
 
	uint32 best_dist = UINT32_MAX;
 
	for (const Industry *i : Industry::Iterate()) {
 
		if (i->type != type || i == current) continue;
 

	
 
		best_dist = min(best_dist, DistanceManhattan(tile, i->location.tile));
 
		best_dist = std::min(best_dist, DistanceManhattan(tile, i->location.tile));
 
	}
 

	
 
	return best_dist;
 
}
 

	
 
/**
 
@@ -137,19 +137,19 @@ static uint32 GetCountAndDistanceOfClose
 
	if (ind_index >= NUM_INDUSTRYTYPES) return 0 | 0xFFFF;
 

	
 
	if (layout_filter == 0 && !town_filter) {
 
		/* If the filter is 0, it could be because none was specified as well as being really a 0.
 
		 * In either case, just do the regular var67 */
 
		closest_dist = GetClosestIndustry(current->location.tile, ind_index, current);
 
		count = min(Industry::GetIndustryTypeCount(ind_index), UINT8_MAX); // clamp to 8 bit
 
		count = std::min<uint>(Industry::GetIndustryTypeCount(ind_index), UINT8_MAX); // clamp to 8 bit
 
	} else {
 
		/* Count only those who match the same industry type and layout filter
 
		 * Unfortunately, we have to do it manually */
 
		for (const Industry *i : Industry::Iterate()) {
 
			if (i->type == ind_index && i != current && (i->selected_layout == layout_filter || layout_filter == 0) && (!town_filter || i->town == current->town)) {
 
				closest_dist = min(closest_dist, DistanceManhattan(current->location.tile, i->location.tile));
 
				closest_dist = std::min(closest_dist, DistanceManhattan(current->location.tile, i->location.tile));
 
				count++;
 
			}
 
		}
 
	}
 

	
 
	return count << 16 | GB(closest_dist, 0, 16);
 
@@ -177,22 +177,22 @@ static uint32 GetCountAndDistanceOfClose
 
			case 0x87: return GetTerrainType(this->tile);
 

	
 
			/* Town zone */
 
			case 0x88: return GetTownRadiusGroup(this->industry->town, this->tile);
 

	
 
			/* Manhattan distance of the closest town */
 
			case 0x89: return min(DistanceManhattan(this->industry->town->xy, this->tile), 255);
 
			case 0x89: return std::min(DistanceManhattan(this->industry->town->xy, this->tile), 255u);
 

	
 
			/* Lowest height of the tile */
 
			case 0x8A: return Clamp(GetTileZ(this->tile) * (this->ro.grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFF);
 

	
 
			/* Distance to the nearest water/land tile */
 
			case 0x8B: return GetClosestWaterDistance(this->tile, (GetIndustrySpec(this->industry->type)->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
 

	
 
			/* Square of Euclidian distance from town */
 
			case 0x8D: return min(DistanceSquare(this->industry->town->xy, this->tile), 65535);
 
			case 0x8D: return std::min(DistanceSquare(this->industry->town->xy, this->tile), 65535u);
 

	
 
			/* 32 random bits */
 
			case 0x8F: return this->random_bits;
 
		}
 
	}
 

	
 
@@ -210,15 +210,15 @@ static uint32 GetCountAndDistanceOfClose
 
		case 0x41:
 
		case 0x42: { // waiting cargo, but only if those two callback flags are set
 
			uint16 callback = indspec->callback_mask;
 
			if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
 
				if ((indspec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) {
 
					if (this->industry->prod_level == 0) return 0;
 
					return min(this->industry->incoming_cargo_waiting[variable - 0x40] / this->industry->prod_level, (uint16)0xFFFF);
 
					return std::min<uint16>(this->industry->incoming_cargo_waiting[variable - 0x40] / this->industry->prod_level, 0xFFFFu);
 
				} else {
 
					return min(this->industry->incoming_cargo_waiting[variable - 0x40], (uint16)0xFFFF);
 
					return std::min<uint16>(this->industry->incoming_cargo_waiting[variable - 0x40], 0xFFFFu);
 
				}
 
			} else {
 
				return 0;
 
			}
 
		}
 

	
 
@@ -280,17 +280,17 @@ static uint32 GetCountAndDistanceOfClose
 
		case 0x64:
 
			if (this->tile == INVALID_TILE) break;
 
			return GetClosestIndustry(this->tile, MapNewGRFIndustryType(parameter, indspec->grf_prop.grffile->grfid), this->industry);
 
		/* Get town zone and Manhattan distance of closest town */
 
		case 0x65:
 
			if (this->tile == INVALID_TILE) break;
 
			return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceManhattan(this->tile, this->industry->town->xy), 0xFFFF);
 
			return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | std::min(DistanceManhattan(this->tile, this->industry->town->xy), 0xFFFFu);
 
		/* Get square of Euclidian distance of closes town */
 
		case 0x66:
 
			if (this->tile == INVALID_TILE) break;
 
			return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceSquare(this->tile, this->industry->town->xy), 0xFFFF);
 
			return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | std::min(DistanceSquare(this->tile, this->industry->town->xy), 0xFFFFu);
 

	
 
		/* Count of industry, distance of closest instance
 
		 * 68 is the same as 67, but with a filtering on selected layout */
 
		case 0x67:
 
		case 0x68: {
 
			byte layout_filter = 0;
 
@@ -636,25 +636,25 @@ void IndustryProductionCallback(Industry
 
		if (group->version < 2) {
 
			/* Callback parameters map directly to industry cargo slot indices */
 
			for (uint i = 0; i < group->num_input; i++) {
 
				ind->incoming_cargo_waiting[i] = Clamp(ind->incoming_cargo_waiting[i] - DerefIndProd(group->subtract_input[i], deref) * multiplier, 0, 0xFFFF);
 
			}
 
			for (uint i = 0; i < group->num_output; i++) {
 
				ind->produced_cargo_waiting[i] = Clamp(ind->produced_cargo_waiting[i] + max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
 
				ind->produced_cargo_waiting[i] = Clamp(ind->produced_cargo_waiting[i] + std::max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
 
			}
 
		} else {
 
			/* Callback receives list of cargos to apply for, which need to have their cargo slots in industry looked up */
 
			for (uint i = 0; i < group->num_input; i++) {
 
				int cargo_index = ind->GetCargoAcceptedIndex(group->cargo_input[i]);
 
				if (cargo_index < 0) continue;
 
				ind->incoming_cargo_waiting[cargo_index] = Clamp(ind->incoming_cargo_waiting[cargo_index] - DerefIndProd(group->subtract_input[i], deref) * multiplier, 0, 0xFFFF);
 
			}
 
			for (uint i = 0; i < group->num_output; i++) {
 
				int cargo_index = ind->GetCargoProducedIndex(group->cargo_output[i]);
 
				if (cargo_index < 0) continue;
 
				ind->produced_cargo_waiting[cargo_index] = Clamp(ind->produced_cargo_waiting[cargo_index] + max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
 
				ind->produced_cargo_waiting[cargo_index] = Clamp(ind->produced_cargo_waiting[cargo_index] + std::max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
 
			}
 
		}
 

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

	
src/newgrf_object.cpp
Show inline comments
 
@@ -186,13 +186,13 @@ static uint32 GetNearbyObjectTileInforma
 
static uint32 GetClosestObject(TileIndex tile, ObjectType type, const Object *current)
 
{
 
	uint32 best_dist = UINT32_MAX;
 
	for (const Object *o : Object::Iterate()) {
 
		if (o->type != type || o == current) continue;
 

	
 
		best_dist = min(best_dist, DistanceManhattan(tile, o->location.tile));
 
		best_dist = std::min(best_dist, DistanceManhattan(tile, o->location.tile));
 
	}
 

	
 
	return best_dist;
 
}
 

	
 
/**
 
@@ -223,13 +223,13 @@ static uint32 GetCountAndDistanceOfClose
 
			break;
 
	}
 

	
 
	/* If the object type is invalid, there is none and the closest is far away. */
 
	if (idx >= NUM_OBJECTS) return 0 | 0xFFFF;
 

	
 
	return Object::GetTypeCount(idx) << 16 | min(GetClosestObject(tile, idx, current), 0xFFFF);
 
	return Object::GetTypeCount(idx) << 16 | std::min(GetClosestObject(tile, idx, current), 0xFFFFu);
 
}
 

	
 
/** Used by the resolver to get values for feature 0F deterministic spritegroups. */
 
/* virtual */ uint32 ObjectScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
 
{
 
	/* We get the town from the object, or we calculate the closest
 
@@ -298,16 +298,16 @@ static uint32 GetCountAndDistanceOfClose
 
		case 0x43: return GetAnimationFrame(this->tile);
 

	
 
		/* Object founder information */
 
		case 0x44: return GetTileOwner(this->tile);
 

	
 
		/* Get town zone and Manhattan distance of closest town */
 
		case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | min(DistanceManhattan(this->tile, t->xy), 0xFFFF);
 
		case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | std::min(DistanceManhattan(this->tile, t->xy), 0xFFFFu);
 

	
 
		/* Get square of Euclidian distance of closes town */
 
		case 0x46: return GetTownRadiusGroup(t, this->tile) << 16 | min(DistanceSquare(this->tile, t->xy), 0xFFFF);
 
		case 0x46: return GetTownRadiusGroup(t, this->tile) << 16 | std::min(DistanceSquare(this->tile, t->xy), 0xFFFFu);
 

	
 
		/* Object colour */
 
		case 0x47: return this->obj->colour;
 

	
 
		/* Object view */
 
		case 0x48: return this->obj->view;
src/newgrf_profiling.cpp
Show inline comments
 
@@ -145,13 +145,13 @@ uint32 NewGRFProfiler::FinishAll()
 
{
 
	int max_ticks = 0;
 
	uint32 total_microseconds = 0;
 
	for (NewGRFProfiler &pr : _newgrf_profilers) {
 
		if (pr.active) {
 
			total_microseconds += pr.Finish();
 
			max_ticks = max(max_ticks, _tick_counter - pr.start_tick);
 
			max_ticks = std::max(max_ticks, _tick_counter - pr.start_tick);
 
		}
 
	}
 

	
 
	if (total_microseconds > 0 && max_ticks > 0) {
 
		IConsolePrintF(CC_DEBUG, "Total NewGRF callback processing: %u microseconds over %d ticks", total_microseconds, max_ticks);
 
	}
src/newgrf_spritegroup.cpp
Show inline comments
 
@@ -5,13 +5,12 @@
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file newgrf_spritegroup.cpp Handling of primarily NewGRF action 2. */
 

	
 
#include "stdafx.h"
 
#include <algorithm>
 
#include "debug.h"
 
#include "newgrf_spritegroup.h"
 
#include "newgrf_profiling.h"
 
#include "core/pool_func.hpp"
 

	
 
#include "safeguards.h"
 
@@ -170,16 +169,16 @@ static U EvalAdjustT(const Deterministic
 
		case DSGA_TYPE_NONE: break;
 
	}
 

	
 
	switch (adjust->operation) {
 
		case DSGA_OP_ADD:  return last_value + value;
 
		case DSGA_OP_SUB:  return last_value - value;
 
		case DSGA_OP_SMIN: return min((S)last_value, (S)value);
 
		case DSGA_OP_SMAX: return max((S)last_value, (S)value);
 
		case DSGA_OP_UMIN: return min((U)last_value, (U)value);
 
		case DSGA_OP_UMAX: return max((U)last_value, (U)value);
 
		case DSGA_OP_SMIN: return std::min<S>(last_value, value);
 
		case DSGA_OP_SMAX: return std::max<S>(last_value, value);
 
		case DSGA_OP_UMIN: return std::min<U>(last_value, value);
 
		case DSGA_OP_UMAX: return std::max<U>(last_value, value);
 
		case DSGA_OP_SDIV: return value == 0 ? (S)last_value : (S)last_value / (S)value;
 
		case DSGA_OP_SMOD: return value == 0 ? (S)last_value : (S)last_value % (S)value;
 
		case DSGA_OP_UDIV: return value == 0 ? (U)last_value : (U)last_value / (U)value;
 
		case DSGA_OP_UMOD: return value == 0 ? (U)last_value : (U)last_value % (U)value;
 
		case DSGA_OP_MUL:  return last_value * value;
 
		case DSGA_OP_AND:  return last_value & value;
src/newgrf_station.cpp
Show inline comments
 
@@ -116,19 +116,19 @@ uint32 GetPlatformInfo(Axis axis, byte t
 
		y -= length / 2;
 
		x = Clamp(x, -8, 7);
 
		y = Clamp(y, -8, 7);
 
		SB(retval,  0, 4, y & 0xF);
 
		SB(retval,  4, 4, x & 0xF);
 
	} else {
 
		SB(retval,  0, 4, min(15, y));
 
		SB(retval,  4, 4, min(15, length - y - 1));
 
		SB(retval,  8, 4, min(15, x));
 
		SB(retval, 12, 4, min(15, platforms - x - 1));
 
		SB(retval,  0, 4, std::min(15, y));
 
		SB(retval,  4, 4, std::min(15, length - y - 1));
 
		SB(retval,  8, 4, std::min(15, x));
 
		SB(retval, 12, 4, std::min(15, platforms - x - 1));
 
	}
 
	SB(retval, 16, 4, min(15, length));
 
	SB(retval, 20, 4, min(15, platforms));
 
	SB(retval, 16, 4, std::min(15, length));
 
	SB(retval, 20, 4, std::min(15, platforms));
 
	SB(retval, 24, 4, tile);
 

	
 
	return retval;
 
}
 

	
 

	
 
@@ -421,13 +421,13 @@ uint32 Station::GetNewGRFVariable(const 
 
				default:   return 0;
 
			}
 
		}
 
		const GoodsEntry *ge = &this->goods[c];
 

	
 
		switch (variable) {
 
			case 0x60: return min(ge->cargo.TotalCount(), 4095);
 
			case 0x60: return std::min(ge->cargo.TotalCount(), 4095u);
 
			case 0x61: return ge->HasVehicleEverTriedLoading() ? ge->time_since_pickup : 0;
 
			case 0x62: return ge->HasRating() ? ge->rating : 0xFFFFFFFF;
 
			case 0x63: return ge->cargo.DaysInTransit();
 
			case 0x64: return ge->HasVehicleEverTriedLoading() ? ge->last_speed | (ge->last_age << 8) : 0xFF00;
 
			case 0x65: return GB(ge->status, GoodsEntry::GES_ACCEPTANCE, 1) << 3;
 
			case 0x69: {
 
@@ -441,13 +441,13 @@ uint32 Station::GetNewGRFVariable(const 
 

	
 
	/* Handle cargo variables (deprecated) */
 
	if (variable >= 0x8C && variable <= 0xEC) {
 
		const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
 
		switch (GB(variable - 0x8C, 0, 3)) {
 
			case 0: return g->cargo.TotalCount();
 
			case 1: return GB(min(g->cargo.TotalCount(), 4095), 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
 
			case 1: return GB(std::min(g->cargo.TotalCount(), 4095u), 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
 
			case 2: return g->time_since_pickup;
 
			case 3: return g->rating;
 
			case 4: return g->cargo.Source();
 
			case 5: return g->cargo.DaysInTransit();
 
			case 6: return g->last_speed;
 
			case 7: return g->last_age;
 
@@ -517,13 +517,13 @@ uint32 Waypoint::GetNewGRFVariable(const
 
		default:
 
			cargo = st->goods[this->station_scope.cargo_type].cargo.TotalCount();
 
			break;
 
	}
 

	
 
	if (HasBit(this->station_scope.statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->train_station.w + st->train_station.h);
 
	cargo = min(0xfff, cargo);
 
	cargo = std::min(0xfffu, cargo);
 

	
 
	if (cargo > this->station_scope.statspec->cargo_threshold) {
 
		if (group->num_loading > 0) {
 
			uint set = ((cargo - this->station_scope.statspec->cargo_threshold) * group->num_loading) / (4096 - this->station_scope.statspec->cargo_threshold);
 
			return group->loading[set];
 
		}
src/newgrf_text.cpp
Show inline comments
 
@@ -14,13 +14,12 @@
 
 * as way to identifying current user lang, while newgrf uses bit shift codes
 
 * not related to ISO.  So equivalence functionality had to be set.
 
 */
 

	
 
#include "stdafx.h"
 

	
 
#include <algorithm>
 
#include <array>
 

	
 
#include "newgrf.h"
 
#include "strings_func.h"
 
#include "newgrf_storage.h"
 
#include "newgrf_text.h"
 
@@ -176,13 +175,13 @@ struct UnmappedChoiceList {
 
				auto str = this->strings[idx].str();
 

	
 
				/* "<CASEn>" */
 
				*d++ = i + 1;
 

	
 
				/* "<LENn>": Limit the length of the string to 0xFFFE to leave space for the '\0'. */
 
				size_t len = min<size_t>(0xFFFE, str.size());
 
				size_t len = std::min<size_t>(0xFFFE, str.size());
 
				*d++ = GB(len + 1, 8, 8);
 
				*d++ = GB(len + 1, 0, 8);
 

	
 
				/* "<STRINGn>" */
 
				dest.write(str.c_str(), len);
 
				*d++ = '\0';
 
@@ -219,13 +218,13 @@ struct UnmappedChoiceList {
 
			/* "<STRINGs>" */
 
			for (int i = 0; i < count; i++) {
 
				int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
 
				const auto &str = this->strings[this->strings.find(idx) != this->strings.end() ? idx : 0].str();
 
				/* Limit the length of the string we copy to 0xFE. The length is written above
 
				 * as a byte and we need room for the final '\0'. */
 
				size_t len = min<size_t>(0xFE, str.size());
 
				size_t len = std::min<size_t>(0xFE, str.size());
 
				dest.write(str.c_str(), len);
 
				*d++ = '\0';
 
			}
 
		}
 
	}
 
};
 
@@ -933,13 +932,13 @@ uint RemapNewGRFStringControlCode(uint s
 
			case SCC_NEWGRF_PRINT_WORD_DATE_SHORT:  *argv = _newgrf_textrefstack.PopUnsignedWord() + DAYS_TILL_ORIGINAL_BASE_YEAR; break;
 

	
 
			case SCC_NEWGRF_DISCARD_WORD:           _newgrf_textrefstack.PopUnsignedWord(); break;
 

	
 
			case SCC_NEWGRF_ROTATE_TOP_4_WORDS:     _newgrf_textrefstack.RotateTop4Words(); break;
 
			case SCC_NEWGRF_PUSH_WORD:              _newgrf_textrefstack.PushWord(Utf8Consume(str)); break;
 
			case SCC_NEWGRF_UNPRINT:                *buff = max(*buff - Utf8Consume(str), buf_start); break;
 
			case SCC_NEWGRF_UNPRINT:                *buff = std::max(*buff - Utf8Consume(str), buf_start); break;
 

	
 
			case SCC_NEWGRF_PRINT_WORD_CARGO_LONG:
 
			case SCC_NEWGRF_PRINT_WORD_CARGO_SHORT:
 
			case SCC_NEWGRF_PRINT_WORD_CARGO_TINY:
 
				argv[0] = GetCargoTranslation(_newgrf_textrefstack.PopUnsignedWord(), _newgrf_textrefstack.grffile);
 
				argv[1] = _newgrf_textrefstack.PopUnsignedWord();
src/news_gui.cpp
Show inline comments
 
@@ -535,13 +535,13 @@ struct NewsWindow : Window {
 

	
 
	void OnRealtimeTick(uint delta_ms) override
 
	{
 
		int count = this->timer.CountElapsed(delta_ms);
 
		if (count > 0) {
 
			/* Scroll up newsmessages from the bottom */
 
			int newtop = max(this->top - 2 * count, _screen.height - this->height - this->status_height - this->chat_height);
 
			int newtop = std::max(this->top - 2 * count, _screen.height - this->height - this->status_height - this->chat_height);
 
			this->SetWindowTop(newtop);
 
		}
 

	
 
		/* Decrement the news timer. We don't need to action an elapsed event here,
 
		 * so no need to use TimerElapsed(). */
 
		if (NewsWindow::duration > 0) NewsWindow::duration -= delta_ms;
 
@@ -553,14 +553,14 @@ private:
 
	 * @param newtop new top coordinate
 
	 */
 
	void SetWindowTop(int newtop)
 
	{
 
		if (this->top == newtop) return;
 

	
 
		int mintop = min(newtop, this->top);
 
		int maxtop = max(newtop, this->top);
 
		int mintop = std::min(newtop, this->top);
 
		int maxtop = std::max(newtop, this->top);
 
		if (this->viewport != nullptr) this->viewport->top += newtop - this->top;
 
		this->top = newtop;
 

	
 
		AddDirtyBlock(this->left, mintop, this->left + this->width, maxtop + this->height);
 
	}
 

	
 
@@ -1145,13 +1145,13 @@ struct MessageHistoryWindow : Window {
 
			/* Months are off-by-one, so it's actually 8. Not using
 
			 * month 12 because the 1 is usually less wide. */
 
			SetDParam(0, ConvertYMDToDate(ORIGINAL_MAX_YEAR, 7, 30));
 
			this->date_width = GetStringBoundingBox(STR_SHORT_DATE).width;
 

	
 
			size->height = 4 * resize->height + this->top_spacing + this->bottom_spacing; // At least 4 lines are visible.
 
			size->width = max(200u, size->width); // At least 200 pixels wide.
 
			size->width = std::max(200u, size->width); // At least 200 pixels wide.
 
		}
 
	}
 

	
 
	void OnPaint() override
 
	{
 
		this->OnInvalidateData(0);
src/object_cmd.cpp
Show inline comments
 
@@ -549,20 +549,20 @@ static void AddAcceptedCargo_Object(Tile
 

	
 
	/* HQ level (depends on company performance) in the range 1..5. */
 
	uint level = GetCompanyHQSize(tile) + 1;
 

	
 
	/* Top town building generates 10, so to make HQ interesting, the top
 
	 * type makes 20. */
 
	acceptance[CT_PASSENGERS] += max(1U, level);
 
	acceptance[CT_PASSENGERS] += std::max(1U, level);
 
	SetBit(*always_accepted, CT_PASSENGERS);
 

	
 
	/* Top town building generates 4, HQ can make up to 8. The
 
	 * proportion passengers:mail is different because such a huge
 
	 * commercial building generates unusually high amount of mail
 
	 * correspondence per physical visitor. */
 
	acceptance[CT_MAIL] += max(1U, level / 2);
 
	acceptance[CT_MAIL] += std::max(1U, level / 2);
 
	SetBit(*always_accepted, CT_MAIL);
 
}
 

	
 
static void AddProducedCargo_Object(TileIndex tile, CargoArray &produced)
 
{
 
	if (!IsObjectType(tile, OBJECT_HQ)) return;
src/object_gui.cpp
Show inline comments
 
@@ -122,13 +122,13 @@ public:
 
	{
 
		switch (widget) {
 
			case WID_BO_CLASS_LIST: {
 
				for (uint i = 0; i < ObjectClass::GetClassCount(); i++) {
 
					ObjectClass *objclass = ObjectClass::Get((ObjectClassID)i);
 
					if (objclass->GetUISpecCount() == 0) continue;
 
					size->width = max(size->width, GetStringBoundingBox(objclass->name).width);
 
					size->width = std::max(size->width, GetStringBoundingBox(objclass->name).width);
 
				}
 
				size->width += padding.width;
 
				this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
 
				resize->height = this->line_height;
 
				size->height = 5 * this->line_height;
 
				break;
 
@@ -158,26 +158,26 @@ public:
 

	
 
				/* Get the height and view information. */
 
				for (int i = 0; i < NUM_OBJECTS; i++) {
 
					const ObjectSpec *spec = ObjectSpec::Get(i);
 
					if (!spec->IsEverAvailable()) continue;
 
					two_wide |= spec->views >= 2;
 
					height[spec->views / 4] = max<int>(ObjectSpec::Get(i)->height, height[spec->views / 4]);
 
					height[spec->views / 4] = std::max<int>(ObjectSpec::Get(i)->height, height[spec->views / 4]);
 
				}
 

	
 
				/* Determine the pixel heights. */
 
				for (size_t i = 0; i < lengthof(height); i++) {
 
					height[i] *= ScaleGUITrad(TILE_HEIGHT);
 
					height[i] += ScaleGUITrad(TILE_PIXELS) + 2 * OBJECT_MARGIN;
 
				}
 

	
 
				/* Now determine the size of the minimum widgets. When there are two columns, then
 
				 * we want these columns to be slightly less wide. When there are two rows, then
 
				 * determine the size of the widgets based on the maximum size for a single row
 
				 * of widgets, or just the twice the widget height of the two row ones. */
 
				size->height = max(height[0], height[1] * 2 + 2);
 
				size->height = std::max(height[0], height[1] * 2 + 2);
 
				if (two_wide) {
 
					size->width  = (3 * ScaleGUITrad(TILE_PIXELS) + 2 * OBJECT_MARGIN) * 2 + 2;
 
				} else {
 
					size->width  = 4 * ScaleGUITrad(TILE_PIXELS) + 2 * OBJECT_MARGIN;
 
				}
 

	
 
@@ -271,13 +271,13 @@ public:
 
					if (spec->grf_prop.grffile == nullptr) {
 
						extern const DrawTileSprites _objects[];
 
						const DrawTileSprites *dts = &_objects[spec->grf_prop.local_id];
 
						DrawOrigTileSeqInGUI((r.right - r.left) / 2 - 1, r.bottom - r.top - OBJECT_MARGIN - ScaleGUITrad(TILE_PIXELS), dts, PAL_NONE);
 
					} else {
 
						DrawNewObjectTileInGUI((r.right - r.left) / 2 - 1, r.bottom - r.top - OBJECT_MARGIN - ScaleGUITrad(TILE_PIXELS), spec,
 
								min(_selected_object_view, spec->views - 1));
 
								std::min<int>(_selected_object_view, spec->views - 1));
 
					}
 
					_cur_dpi = old_dpi;
 
				}
 
				break;
 
			}
 

	
 
@@ -329,13 +329,13 @@ public:
 
	 */
 
	void SelectOtherObject(int object_index)
 
	{
 
		_selected_object_index = object_index;
 
		if (_selected_object_index != -1) {
 
			const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
 
			_selected_object_view = min(_selected_object_view, spec->views - 1);
 
			_selected_object_view = std::min<int>(_selected_object_view, spec->views - 1);
 
			this->ReInit();
 
		} else {
 
			_selected_object_view = 0;
 
		}
 

	
 
		if (_selected_object_index != -1) {
src/openttd.cpp
Show inline comments
 
@@ -287,14 +287,14 @@ static void ParseResolution(Dimension *r
 
	const char *t = strchr(s, 'x');
 
	if (t == nullptr) {
 
		ShowInfoF("Invalid resolution '%s'", s);
 
		return;
 
	}
 

	
 
	res->width  = max(strtoul(s, nullptr, 0), 64UL);
 
	res->height = max(strtoul(t + 1, nullptr, 0), 64UL);
 
	res->width  = std::max(strtoul(s, nullptr, 0), 64UL);
 
	res->height = std::max(strtoul(t + 1, nullptr, 0), 64UL);
 
}
 

	
 

	
 
/**
 
 * Uninitializes drivers, frees allocated memory, cleans pools, ...
 
 * Generally, prepares the game for shutting down

Changeset was too big and was cut off... Show full diff anyway

0 comments (0 inline, 0 general)