Changeset - r15040:2d5282cc0907
[Not reviewed]
master
0 15 0
frosch - 14 years ago 2010-04-18 14:56:05
frosch@openttd.org
(svn r19670) -Codechange: Add CeilDiv() and RoundDiv() to simplify integer divisions with rounding.
15 files changed with 50 insertions and 30 deletions:
0 comments (0 inline, 0 general)
src/aircraft_cmd.cpp
Show inline comments
 
@@ -1058,13 +1058,13 @@ static bool AircraftController(Aircraft 
 
			assert(curz <= z);
 
			int t = max(1U, dist - 4);
 
			int delta = z - curz;
 

	
 
			/* Only start lowering when we're sufficiently close for a 1:1 glide */
 
			if (delta >= t) {
 
				z -= ((z - curz) + t - 1) / t;
 
				z -= CeilDiv(z - curz, t);
 
			}
 
			if (z < curz) z = curz;
 
		}
 

	
 
		/* We've landed. Decrease speed when we're reaching end of runway. */
 
		if (amd->flag & AMED_BRAKE) {
src/autoreplace_cmd.cpp
Show inline comments
 
@@ -409,13 +409,13 @@ static CommandCost ReplaceChain(Vehicle 
 
	assert(old_head->IsPrimaryVehicle());
 

	
 
	CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
 

	
 
	if (old_head->type == VEH_TRAIN) {
 
		/* Store the length of the old vehicle chain, rounded up to whole tiles */
 
		uint16 old_total_length = (Train::From(old_head)->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE * TILE_SIZE;
 
		uint16 old_total_length = CeilDiv(Train::From(old_head)->tcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
 

	
 
		int num_units = 0; ///< Number of units in the chain
 
		for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
 

	
 
		Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
 
		Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
src/core/math_func.hpp
Show inline comments
 
@@ -315,7 +315,29 @@ static FORCEINLINE uint ToPercent16(uint
 
	return i * 101 >> 16;
 
}
 

	
 
int LeastCommonMultiple(int a, int b);
 
int GreatestCommonDivisor(int a, int b);
 

	
 
/**
 
 * Computes ceil(a / b) for non-negative a and b.
 
 * @param a Numerator
 
 * @param b Denominator
 
 * @return Quotient, rounded up
 
 */
 
static FORCEINLINE uint CeilDiv(uint a, uint b)
 
{
 
	return (a + b - 1) / b;
 
}
 

	
 
/**
 
 * Computes round(a / b) for non-negative a and b.
 
 * @param a Numerator
 
 * @param b Denominator
 
 * @return Quotient, rounded to nearest
 
 */
 
static FORCEINLINE uint RoundDiv(uint a, uint b)
 
{
 
	return (a + b / 2) / b;
 
}
 

	
 
#endif /* MATH_FUNC_HPP */
src/depot_gui.cpp
Show inline comments
 
@@ -256,13 +256,13 @@ struct DepotWindow : Window {
 
				free_wagon = u->IsFreeWagon();
 

	
 
				uint x_space = free_wagon ? TRAININFO_DEFAULT_VEHICLE_WIDTH : 0;
 
				DrawTrainImage(u, image_left + (rtl ? 0 : x_space), image_right - (rtl ? x_space : 0), sprite_y - 1, this->sel, free_wagon ? 0 : this->hscroll.GetPosition());
 

	
 
				/* Number of wagons relative to a standard length wagon (rounded up) */
 
				SetDParam(0, (u->tcache.cached_total_length + 7) / 8);
 
				SetDParam(0, CeilDiv(u->tcache.cached_total_length, 8));
 
				DrawString(rtl ? left + WD_FRAMERECT_LEFT : right - this->count_width, rtl ? left + this->count_width : right - WD_FRAMERECT_RIGHT, y + (this->resize.step_height - FONT_HEIGHT_SMALL) / 2, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT); // Draw the counter
 
				break;
 
			}
 

	
 
			case VEH_ROAD:     DrawRoadVehImage( v, image_left, image_right, sprite_y, this->sel); break;
 
			case VEH_SHIP:     DrawShipImage(    v, image_left, image_right, sprite_y, this->sel); break;
 
@@ -689,13 +689,13 @@ struct DepotWindow : Window {
 
				max_width = max(max_width, width);
 
			}
 
			/* Always have 1 empty row, so people can change the setting of the train */
 
			this->vscroll.SetCount(this->vehicle_list.Length() + this->wagon_list.Length() + 1);
 
			this->hscroll.SetCount(max_width);
 
		} else {
 
			this->vscroll.SetCount((this->vehicle_list.Length() + this->hscroll.GetCapacity() - 1) / this->hscroll.GetCapacity());
 
			this->vscroll.SetCount(CeilDiv(this->vehicle_list.Length(), this->hscroll.GetCapacity()));
 
		}
 

	
 
		/* Setup disabled buttons. */
 
		TileIndex tile = this->window_number;
 
		this->SetWidgetsDisabledState(!IsTileOwner(tile, _local_company),
 
			DEPOT_WIDGET_STOP_ALL,
src/economy.cpp
Show inline comments
 
@@ -1162,13 +1162,13 @@ static void LoadUnloadVehicle(Vehicle *v
 
		if (v->cargo_cap == 0) continue;
 

	
 
		const Engine *e = Engine::Get(v->engine_type);
 
		byte load_amount = e->info.load_amount;
 

	
 
		/* The default loadamount for mail is 1/4 of the load amount for passengers */
 
		if (v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft()) load_amount = (load_amount + 3) / 4;
 
		if (v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft()) load_amount = CeilDiv(load_amount, 4);
 

	
 
		if (_settings_game.order.gradual_loading && HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
 
			uint16 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
 
			if (cb_load_amount != CALLBACK_FAILED && GB(cb_load_amount, 0, 8) != 0) load_amount = GB(cb_load_amount, 0, 8);
 
		}
 

	
src/gfx.cpp
Show inline comments
 
@@ -547,14 +547,13 @@ static int DrawString(int left, int righ
 
				/* right + 1 = left + w */
 
				left = initial_left + offset;
 
				right = left + w - 1;
 
				break;
 

	
 
			case SA_CENTER:
 
				/* The second + 1 is to round to the closest number */
 
				left  = (initial_right + 1 + initial_left - w + 1) / 2;
 
				left  = RoundDiv(initial_right + 1 + initial_left - w, 2);
 
				/* right + 1 = left + w */
 
				right = left + w - 1;
 
				break;
 

	
 
			case SA_RIGHT:
 
				left = initial_right + 1 - w - offset;
 
@@ -821,13 +820,13 @@ int DrawStringMultiLine(int left, int ri
 
		if (maxh < mt) return top;
 

	
 
		num = maxh / mt - 1;
 
		total_height = (num + 1) * mt;
 
	}
 

	
 
	int y = (align == SA_CENTER) ? (bottom + top - total_height + 1) / 2 : top;
 
	int y = (align == SA_CENTER) ? RoundDiv(bottom + top - total_height, 2) : top;
 
	const char *src = buffer;
 

	
 
	for (;;) {
 
		char buf2[DRAW_STRING_BUFFER];
 
		strecpy(buf2, src, lastof(buf2));
 
		DrawString(left, right, y, buf2, lastof(buf2), colour, align, underline, false);
 
@@ -1321,14 +1320,14 @@ byte GetDigitWidth(FontSize size)
 
	return width;
 
}
 

	
 

	
 
void ScreenSizeChanged()
 
{
 
	_dirty_bytes_per_line = (_screen.width + DIRTY_BLOCK_WIDTH - 1) / DIRTY_BLOCK_WIDTH;
 
	_dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * ((_screen.height + DIRTY_BLOCK_HEIGHT - 1) / DIRTY_BLOCK_HEIGHT));
 
	_dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
 
	_dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
 

	
 
	/* check the dirty rect */
 
	if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
 
	if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
 

	
 
	/* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
src/industry_cmd.cpp
Show inline comments
 
@@ -2329,14 +2329,14 @@ static void ChangeIndustryProduction(Ind
 
	}
 

	
 
	/* Recalculate production_rate
 
	 * For non-smooth economy these should always be synchronized with prod_level */
 
	if (recalculate_multipliers) {
 
		/* Rates are rounded up, so e.g. oilrig always produces some passengers */
 
		i->production_rate[0] = min((indspec->production_rate[0] * i->prod_level + PRODLEVEL_DEFAULT - 1) / PRODLEVEL_DEFAULT, 0xFF);
 
		i->production_rate[1] = min((indspec->production_rate[1] * i->prod_level + PRODLEVEL_DEFAULT - 1) / PRODLEVEL_DEFAULT, 0xFF);
 
		i->production_rate[0] = min(CeilDiv(indspec->production_rate[0] * i->prod_level, PRODLEVEL_DEFAULT), 0xFF);
 
		i->production_rate[1] = min(CeilDiv(indspec->production_rate[1] * i->prod_level, PRODLEVEL_DEFAULT), 0xFF);
 
	}
 

	
 
	/* Close if needed and allowed */
 
	if (closeit && !CheckIndustryCloseDownProtection(i->type)) {
 
		i->prod_level = PRODLEVEL_CLOSURE;
 
		str = indspec->closure_text;
src/map_func.h
Show inline comments
 
@@ -9,12 +9,13 @@
 

	
 
/** @file map_func.h Functions related to maps. */
 

	
 
#ifndef MAP_FUNC_H
 
#define MAP_FUNC_H
 

	
 
#include "core/math_func.hpp"
 
#include "tile_type.h"
 
#include "map_type.h"
 
#include "direction_func.h"
 

	
 
extern uint _map_tile_mask;
 

	
 
@@ -123,15 +124,14 @@ static inline uint MapMaxY()
 
 * @param n the value to scale
 
 * @return the scaled size
 
 */
 
static inline uint ScaleByMapSize(uint n)
 
{
 
	/* Subtract 12 from shift in order to prevent integer overflow
 
	 * for large values of n. It's safe since the min mapsize is 64x64.
 
	 * Add (1<<4)-1 to round upwards. */
 
	return ((n << (MapLogX() + MapLogY() - 12)) + (1 << 4) - 1) >> 4;
 
	 * for large values of n. It's safe since the min mapsize is 64x64. */
 
	return CeilDiv(n << (MapLogX() + MapLogY() - 12), 1 << 4);
 
}
 

	
 

	
 
/**
 
 * Scales the given value by the maps circumference, where the given
 
 * value is for a 256 by 256 map
 
@@ -139,15 +139,14 @@ static inline uint ScaleByMapSize(uint n
 
 * @return the scaled size
 
 */
 
static inline uint ScaleByMapSize1D(uint n)
 
{
 
	/* Normal circumference for the X+Y is 256+256 = 1<<9
 
	 * Note, not actually taking the full circumference into account,
 
	 * just half of it.
 
	 * (1<<9) - 1 is there to scale upwards. */
 
	return ((n << MapLogX()) + (n << MapLogY()) + (1 << 9) - 1) >> 9;
 
	 * just half of it. */
 
	return CeilDiv((n << MapLogX()) + (n << MapLogY()), 1 << 9);
 
}
 

	
 
/**
 
 * An offset value between to tiles.
 
 *
 
 * This value is used fro the difference between
src/pathfinder/yapf/yapf_costrail.hpp
Show inline comments
 
@@ -256,13 +256,13 @@ public:
 
	{
 
		int cost = 0;
 
		const Train *v = Yapf().GetVehicle();
 
		assert(v != NULL);
 
		assert(v->type == VEH_TRAIN);
 
		assert(v->tcache.cached_total_length != 0);
 
		int missing_platform_length = (v->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE - platform_length;
 
		int missing_platform_length = CeilDiv(v->tcache.cached_total_length, TILE_SIZE) - platform_length;
 
		if (missing_platform_length < 0) {
 
			/* apply penalty for longer platform than needed */
 
			cost += Yapf().PfGetSettings().rail_longer_platform_penalty + Yapf().PfGetSettings().rail_longer_platform_per_tile_penalty * -missing_platform_length;
 
		} else if (missing_platform_length > 0) {
 
			/* apply penalty for shorter platform than needed */
 
			cost += Yapf().PfGetSettings().rail_shorter_platform_penalty + Yapf().PfGetSettings().rail_shorter_platform_per_tile_penalty * missing_platform_length;
src/smallmap_gui.cpp
Show inline comments
 
@@ -981,13 +981,13 @@ public:
 

	
 
	/** Compute maximal required height of the legends.
 
	 * @return Maximally needed height for displaying the smallmap legends in pixels.
 
	 */
 
	inline uint GetMaxLegendHeight() const
 
	{
 
		uint num_rows = max(this->min_number_of_fixed_rows, (_smallmap_industry_count + this->min_number_of_columns - 1) / this->min_number_of_columns);
 
		uint num_rows = max(this->min_number_of_fixed_rows, CeilDiv(_smallmap_industry_count, this->min_number_of_columns));
 
		return WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + num_rows * FONT_HEIGHT_SMALL;
 
	}
 

	
 
	/** Compute minimal required width of the legends.
 
	 * @return Minimally needed width for displaying the smallmap legends in pixels.
 
	 */
 
@@ -1007,13 +1007,13 @@ public:
 
	/** Compute height given a width.
 
	 * @return Needed height for displaying the smallmap legends in pixels.
 
	 */
 
	uint GetLegendHeight(uint width) const
 
	{
 
		uint num_columns = this->GetNumberColumnsLegend(width);
 
		uint num_rows = max(this->min_number_of_fixed_rows, (_smallmap_industry_count + num_columns - 1) / num_columns);
 
		uint num_rows = max(this->min_number_of_fixed_rows, CeilDiv(_smallmap_industry_count, num_columns));
 
		return WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + num_rows * FONT_HEIGHT_SMALL;
 
	}
 

	
 
	virtual void SetStringParameters(int widget) const
 
	{
 
		switch (widget) {
 
@@ -1064,13 +1064,13 @@ public:
 
				if (!FillDrawPixelInfo(&new_dpi, r.left + 1, r.top + 1, r.right - r.left - 1, r.bottom - r.top - 1)) return;
 
				this->DrawSmallMap(&new_dpi);
 
			} break;
 

	
 
			case SM_WIDGET_LEGEND: {
 
				uint columns = this->GetNumberColumnsLegend(r.right - r.left + 1);
 
				uint number_of_rows = max(this->map_type == SMT_INDUSTRY ? (_smallmap_industry_count + columns - 1) / columns : 0, this->min_number_of_fixed_rows);
 
				uint number_of_rows = max(this->map_type == SMT_INDUSTRY ? CeilDiv(_smallmap_industry_count, columns) : 0, this->min_number_of_fixed_rows);
 
				bool rtl = _dynlang.text_dir == TD_RTL;
 
				uint y_org = r.top + WD_FRAMERECT_TOP;
 
				uint x = rtl ? r.right - this->column_width - WD_FRAMERECT_RIGHT : r.left + WD_FRAMERECT_LEFT;
 
				uint y = y_org;
 
				uint i = 0; // Row counter for industry legend.
 
				uint row_height = FONT_HEIGHT_SMALL;
 
@@ -1192,13 +1192,13 @@ public:
 
				/* If industry type small map*/
 
				if (this->map_type == SMT_INDUSTRY) {
 
					/* If click on industries label, find right industry type and enable/disable it */
 
					const NWidgetBase *wi = this->GetWidget<NWidgetBase>(SM_WIDGET_LEGEND); // Label panel
 
					uint line = (pt.y - wi->pos_y - WD_FRAMERECT_TOP) / FONT_HEIGHT_SMALL;
 
					uint columns = this->GetNumberColumnsLegend(wi->current_x);
 
					uint number_of_rows = max((_smallmap_industry_count + columns - 1) / columns, this->min_number_of_fixed_rows);
 
					uint number_of_rows = max(CeilDiv(_smallmap_industry_count, columns), this->min_number_of_fixed_rows);
 
					if (line >= number_of_rows) break;
 

	
 
					bool rtl = _dynlang.text_dir == TD_RTL;
 
					int x = pt.x - wi->pos_x;
 
					if (rtl) x = wi->current_x - x;
 
					uint column = (x - WD_FRAMERECT_LEFT) / this->column_width;
src/station_gui.cpp
Show inline comments
 
@@ -1102,13 +1102,13 @@ struct StationViewWindow : public Window
 
		uint32 cargo_mask = 0;
 
		for (CargoID i = 0; i < NUM_CARGO; i++) {
 
			if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) SetBit(cargo_mask, i);
 
		}
 
		Rect s = {r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, r.right - WD_FRAMERECT_RIGHT, INT32_MAX};
 
		int bottom = DrawCargoListText(cargo_mask, s, STR_STATION_VIEW_ACCEPTS_CARGO);
 
		return (bottom - r.top - WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL - 1) / FONT_HEIGHT_NORMAL;
 
		return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
 
	}
 

	
 
	/** Draw cargo ratings in the #SVW_ACCEPTLIST widget.
 
	 * @param r Rectangle of the widget.
 
	 * @return Number of lines needed for drawing the cargo ratings.
 
	 */
 
@@ -1128,13 +1128,13 @@ struct StationViewWindow : public Window
 
			SetDParam(0, cs->name);
 
			SetDParam(2, ToPercent8(ge->rating));
 
			SetDParam(1, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
 
			DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_RATING);
 
			y += FONT_HEIGHT_NORMAL;
 
		}
 
		return (y - r.top - WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL - 1) / FONT_HEIGHT_NORMAL;
 
		return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
 
	}
 

	
 
	void HandleCargoWaitingClick(int row)
 
	{
 
		if (row == 0) return;
 

	
src/terraform_gui.cpp
Show inline comments
 
@@ -646,14 +646,14 @@ struct ScenarioEditorLandscapeGeneration
 
	}
 

	
 
	virtual void DrawWidget(const Rect &r, int widget) const
 
	{
 
		if (widget != ETTW_DOTS) return;
 

	
 
		int center_x = (r.left + r.right + 1) / 2;
 
		int center_y = (r.top + r.bottom + 1) / 2;
 
		int center_x = RoundDiv(r.left + r.right, 2);
 
		int center_y = RoundDiv(r.top + r.bottom, 2);
 

	
 
		int n = _terraform_size * _terraform_size;
 
		const int8 *coords = &_multi_terraform_coords[0][0];
 

	
 
		assert(n != 0);
 
		do {
src/timetable_cmd.cpp
Show inline comments
 
@@ -276,13 +276,13 @@ void UpdateVehicleTimetable(Vehicle *v, 
 
		/* Modify station waiting time only if our new value is larger (this is
 
		 * always the case when we cleared the timetable). */
 
		if (!v->current_order.IsType(OT_CONDITIONAL) && (travelling || time_taken > v->current_order.wait_time)) {
 
			/* Round the time taken up to the nearest day, as this will avoid
 
			 * confusion for people who are timetabling in days, and can be
 
			 * adjusted later by people who aren't. */
 
			time_taken = (((time_taken - 1) / DAY_TICKS) + 1) * DAY_TICKS;
 
			time_taken = CeilDiv(time_taken, DAY_TICKS) * DAY_TICKS;
 

	
 
			ChangeTimetable(v, v->cur_order_index, time_taken, travelling);
 
		}
 

	
 
		if (v->cur_order_index == 0 && travelling) {
 
			/* If we just started we would have returned earlier and have not reached
src/toolbar_gui.cpp
Show inline comments
 
@@ -1110,13 +1110,13 @@ class NWidgetMainToolbarContainer : publ
 
		};
 
		static const byte arrange_all[] = {
 
			0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
 
		};
 

	
 
		/* If at least BIGGEST_ARRANGEMENT fit, just spread all the buttons nicely */
 
		uint full_buttons = max((width + this->smallest_x - 1) / this->smallest_x, SMALLEST_ARRANGEMENT);
 
		uint full_buttons = max(CeilDiv(width, this->smallest_x), SMALLEST_ARRANGEMENT);
 
		if (full_buttons > BIGGEST_ARRANGEMENT) {
 
			button_count = arrangable_count = lengthof(arrange_all);
 
			spacer_count = this->spacers;
 
			return arrange_all;
 
		}
 

	
src/viewport.cpp
Show inline comments
 
@@ -2475,13 +2475,13 @@ static void CalcRaildirsDrawstyle(TileHi
 
		if (distance != 1) {
 
			int heightdiff = CalcHeightdiff(b, distance, t0, t1);
 
			/* If we are showing a tooltip for horizontal or vertical drags,
 
			 * 2 tiles have a length of 1. To bias towards the ceiling we add
 
			 * one before division. It feels more natural to count 3 lengths as 2 */
 
			if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
 
				distance = (distance + 1) / 2;
 
				distance = CeilDiv(distance, 2);
 
			}
 

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

	
0 comments (0 inline, 0 general)