1 /*
2  * Copyright (c) 1997 - 2001 Hj. Malthaner
3  *
4  * This file is part of the Simutrans project under the artistic license.
5  * (see license.txt)
6  */
7 
8 /*
9  * zentrale Datenstruktur von Simutrans
10  * von Hj. Malthaner 1998
11  */
12 
13 #ifndef simworld_h
14 #define simworld_h
15 
16 #include "simconst.h"
17 #include "simtypes.h"
18 #include "simunits.h"
19 
20 #include "convoihandle_t.h"
21 #include "halthandle_t.h"
22 
23 #include "tpl/weighted_vector_tpl.h"
24 #include "tpl/vector_tpl.h"
25 #include "tpl/slist_tpl.h"
26 
27 #include "dataobj/settings.h"
28 #include "network/pwd_hash.h"
29 #include "dataobj/loadsave.h"
30 #include "dataobj/rect.h"
31 
32 #include "simplan.h"
33 
34 #include "simdebug.h"
35 
36 struct sound_info;
37 class stadt_t;
38 class fabrik_t;
39 class gebaeude_t;
40 class zeiger_t;
41 class grund_t;
42 class planquadrat_t;
43 class main_view_t;
44 class interaction_t;
45 class sync_steppable;
46 class tool_t;
47 class scenario_t;
48 class message_t;
49 class way_desc_t;
50 class network_world_command_t;
51 class goods_desc_t;
52 class memory_rw_t;
53 class viewport_t;
54 class records_t;
55 
56 struct checklist_t
57 {
58 	uint32 random_seed;
59 	uint16 halt_entry;
60 	uint16 line_entry;
61 	uint16 convoy_entry;
62 
checklist_tchecklist_t63 	checklist_t() : random_seed(0), halt_entry(0), line_entry(0), convoy_entry(0) { }
checklist_tchecklist_t64 	checklist_t(uint32 _random_seed, uint16 _halt_entry, uint16 _line_entry, uint16 _convoy_entry)
65 		: random_seed(_random_seed), halt_entry(_halt_entry), line_entry(_line_entry), convoy_entry(_convoy_entry) { }
66 
67 	bool operator == (const checklist_t &other) const
68 	{
69 		return ( random_seed==other.random_seed && halt_entry==other.halt_entry && line_entry==other.line_entry && convoy_entry==other.convoy_entry );
70 	}
71 	bool operator != (const checklist_t &other) const { return !( (*this)==other ); }
72 
73 	void rdwr(memory_rw_t *buffer);
74 	int print(char *buffer, const char *entity) const;
75 };
76 
77 
78 /**
79  * Threaded function caller.
80  */
81 typedef void (karte_t::*xy_loop_func)(sint16, sint16, sint16, sint16);
82 
83 
84 /**
85  * The map is the central part of the simulation. It stores all data and objects.
86  * @brief Stores all data and objects of the simulated world.
87  * @author Hj. Malthaner
88  */
89 class karte_t
90 {
91 	friend karte_t* world();  // to access the single instance
92 	friend class karte_ptr_t; // to access the single instance
93 
94 	static karte_t* world; ///< static single instance
95 
96 public:
97 	/**
98 	 * Height of a point of the map with "perlin noise"
99 	 *
100 	 * @param frequency in 0..1.0 roughness, the higher the rougher
101 	 * @param amplitude in 0..160.0 top height of mountains, may not exceed 160.0!!!
102 	 * @author Hj. Malthaner
103 	 */
104 	static sint32 perlin_hoehe(settings_t const*, koord k, koord size);
105 
106 	/**
107 	 * Loops over tiles setting heights from perlin noise
108 	 */
109 	void perlin_hoehe_loop(sint16, sint16, sint16, sint16);
110 
111 	enum player_cost {
112 		WORLD_CITICENS=0,		//!< total people
113 		WORLD_GROWTH,			//!< growth (just for convenience)
114 		WORLD_TOWNS,			//!< number of all cities
115 		WORLD_FACTORIES,		//!< number of all consuming only factories
116 		WORLD_CONVOIS,			//!< total number of convois
117 		WORLD_CITYCARS,			//!< number of citycars generated
118 		WORLD_PAS_RATIO,		//!< percentage of passengers that started successful
119 		WORLD_PAS_GENERATED,	//!< total number generated
120 		WORLD_MAIL_RATIO,		//!< percentage of mail that started successful
121 		WORLD_MAIL_GENERATED,	//!< all letters generated
122 		WORLD_GOODS_RATIO,		//!< ratio of chain completeness
123 		WORLD_TRANSPORTED_GOODS,//!< all transported goods
124 		MAX_WORLD_COST
125 	};
126 
127 	#define MAX_WORLD_HISTORY_YEARS  (12) // number of years to keep history
128 	#define MAX_WORLD_HISTORY_MONTHS  (12) // number of months to keep history
129 
130 	enum { NORMAL=0, PAUSE_FLAG = 0x01, FAST_FORWARD=0x02, FIX_RATIO=0x04 };
131 
132 	/**
133 	 * Missing things during loading:
134 	 * factories, vehicles, roadsigns or catenary may be severe
135 	 */
136 	enum missing_level_t { NOT_MISSING=0, MISSING_FACTORY=1, MISSING_VEHICLE=2, MISSING_SIGN=3, MISSING_WAYOBJ=4, MISSING_ERROR=4, MISSING_BRIDGE, MISSING_BUILDING, MISSING_WAY };
137 
138 private:
139 	/**
140 	 * @name Map properties
141 	 * Basic map properties are stored in this variables.
142 	 * @{
143 	 */
144 	/**
145 	 * @brief Map settings are stored here.
146 	 */
147 	settings_t settings;
148 
149 	/**
150 	 * For performance reasons we have the map grid size cached locally, comes from the environment (Einstellungen)
151 	 * @brief Cached map grid size.
152 	 * @note Valid coords are (0..x-1,0..y-1)
153 	 */
154 	koord cached_grid_size;
155 
156 	/**
157 	 * For performance reasons we have the map size cached locally, comes from the environment (Einstellungen).
158 	 * @brief Cached map size.
159 	 * @note Valid coords are (0..x-1,0..y-1)
160 	 * @note These values are one less than the size values of the grid.
161 	 */
162 	koord cached_size;
163 
164 	/**
165 	 * @brief The maximum of the two dimensions.
166 	 * Maximum size for waiting bars etc.
167 	 */
168 	int cached_size_max;
169 	/** @} */
170 
171 	/**
172 	 * All cursor interaction goes via this function, it will call save_mouse_funk first with
173 	 * init, then with the position and with exit, when another tool is selected without click
174 	 * @see simtool.cc for practical examples of such functions.
175 	 */
176 	tool_t *selected_tool[MAX_PLAYER_COUNT];
177 
178 	/**
179 	 * Redraw whole map.
180 	 */
181 	bool dirty;
182 
183 	/*
184 	 * Redraw background.
185 	 */
186 	bool background_dirty;
187 
188 	/**
189 	 * True during destroying of the map.
190 	 */
191 	bool destroying;
192 
193 	/**
194 	 * The rotation of the map when first loaded.
195 	 */
196 	uint8 loaded_rotation;
197 
198 	/**
199 	 * The one and only camera looking at our world.
200 	 */
201 	viewport_t *viewport;
202 
203 	/**
204 	 * @name Mouse pointer and cursor management
205 	 * @author Hj. Malthaner
206 	 * @{
207 	 */
208 
209 	/**
210 	 * @brief Map mouse cursor tool.
211 	 */
212 	zeiger_t *zeiger;
213 	/** @} */
214 
215 	/**
216 	 * Time when last mouse moved to check for ambient sound events.
217 	 */
218 	uint32 mouse_rest_time;
219 
220 	/**
221 	 * Waiting time before next event.
222 	 */
223 	uint32 sound_wait_time;
224 
225 	/**
226 	 * Gets an ambient sound id appropriate for the given tile.
227 	 * Returns NO_SOUND if no appropriate sound is found.
228 	 */
229 	sint16 get_sound_id(grund_t *gr);
230 
231 	/**
232 	 * If true, this map cannot be saved.
233 	 */
234 	bool nosave;
235 	bool nosave_warning;
236 
237 	/**
238 	 * Water level height.
239 	 * @author Hj. Malthaner
240 	 */
241 	sint8 groundwater;
242 
243 	/**
244 	 * Current snow height.
245 	 * @note Might change during the game.
246 	 * @author prissi
247 	 */
248 	sint16 snowline;
249 
250 	/**
251 	 * Changes the season and/or snowline height
252 	 * @author prissi
253 	 */
254 	void recalc_season_snowline(bool set_pending);
255 
256 	/**
257 	 * >0 means a season change is needed
258 	 */
259 	sint8 pending_season_change;
260 	sint8 pending_snowline_change;
261 
262 	/**
263 	 * Recalculates sleep time etc.
264 	 */
265 	void update_frame_sleep_time();
266 
267 	/**
268 	 * Table for fast conversion from height to climate.
269 	 * @author prissi
270 	 */
271 	uint8 height_to_climate[128];
272 
273 	/**
274 	 * Array containing the convois.
275 	 */
276 	vector_tpl<convoihandle_t> convoi_array;
277 
278 	/**
279 	 * Array containing the factories.
280 	 */
281 	slist_tpl<fabrik_t *> fab_list;
282 
283 	/**
284 	 * Stores a list of goods produced by factories currently in the game;
285 	 */
286 	vector_tpl<const goods_desc_t*> goods_in_game;
287 
288 	weighted_vector_tpl<gebaeude_t *> attractions;
289 
290 	slist_tpl<koord> labels;
291 
292 	/**
293 	 * Stores the cities.
294 	 */
295 	weighted_vector_tpl<stadt_t*> stadt;
296 
297 	sint64 last_month_bev;
298 
299 	/**
300 	 * The recorded history so far.
301 	 */
302 	sint64 finance_history_year[MAX_WORLD_HISTORY_YEARS][MAX_WORLD_COST];
303 
304 	/**
305 	 * The recorded history so far.
306 	 */
307 	sint64 finance_history_month[MAX_WORLD_HISTORY_MONTHS][MAX_WORLD_COST];
308 
309 	/**
310 	 * World record speed manager.
311 	 * Keeps track of the fastest vehicles in game.
312 	 */
313 	records_t *records;
314 
315 	/**
316 	 * Attached view to this world.
317 	 */
318 	main_view_t *view;
319 
320 	/**
321 	 * Event manager of this world.
322 	 */
323 	interaction_t *eventmanager;
324 
325 	/**
326 	 * Checks whether the heights of the corners of the tile at (@p x, @p y) can be raised.
327 	 * If the desired height of a corner is lower than its current height, this corner is ignored.
328 	 * @param player player who wants to lower
329 	 * @param x coordinate
330 	 * @param y coordinate
331 	 * @param keep_water returns false if water tiles would be raised above water
332 	 * @param hsw desired height of sw-corner
333 	 * @param hse desired height of se-corner
334 	 * @param hse desired height of ne-corner
335 	 * @param hnw desired height of nw-corner
336 	 * @returns NULL if raise_to operation can be performed, an error message otherwise
337 	 */
338 	const char* can_raise_to(const player_t* player, sint16 x, sint16 y, bool keep_water, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw) const;
339 
340 	/**
341 	 * Raises heights of the corners of the tile at (@p x, @p y).
342 	 * New heights for each corner given.
343 	 * @pre can_raise_to should be called before this method.
344 	 * @see can_raise_to
345 	 * @returns count of full raise operations (4 corners raised one level)
346 	 * @note Clear tile, reset water/land type, calc minimap pixel.
347 	 */
348 	int  raise_to(sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
349 
350 	/**
351 	 * Checks whether the heights of the corners of the tile at (@p x, @p y) can be lowered.
352 	 * If the desired height of a corner is higher than its current height, this corner is ignored.
353 	 * @param player player who wants to lower
354 	 * @param x coordinate
355 	 * @param y coordinate
356 	 * @param hsw desired height of sw-corner
357 	 * @param hse desired height of se-corner
358 	 * @param hse desired height of ne-corner
359 	 * @param hnw desired height of nw-corner
360 	 * @returns NULL if lower_to operation can be performed, an error message otherwise
361 	 */
362 	const char* can_lower_to(const player_t* player, sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw) const;
363 
364 	/**
365 	 * Lowers heights of the corners of the tile at (@p x, @p y).
366 	 * New heights for each corner given.
367 	 * @pre can_lower_to should be called before this method.
368 	 * @see can_lower_to
369 	 * @returns count of full lower operations (4 corners lowered one level)
370 	 * @note Clear tile, reset water/land type, calc minimap pixel.
371 	 */
372 	int  lower_to(sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
373 
374 	/**
375 	 * Raise grid point (@p x,@p y). Changes grid_hgts only, used during map creation/enlargement.
376 	 * @see clean_up
377 	 */
378 	void raise_grid_to(sint16 x, sint16 y, sint8 h);
379 
380 	/**
381 	 * Lower grid point (@p x,@p y). Changes grid_hgts only, used during map creation/enlargement.
382 	 * @see clean_up
383 	 */
384 	void lower_grid_to(sint16 x, sint16 y, sint8 h);
385 
386 	/**
387 	 * The fractal generation of the map is not perfect.
388 	 * cleanup_karte() eliminates errors.
389 	 * @author Hj. Malthaner
390 	 */
391 	void cleanup_karte( int xoff, int yoff );
392 
393 	/**
394 	 * @name Map data structures
395 	 *       This variables represent the simulated map.
396 	 * @{
397 	 */
398 
399 	/**
400 	 * Array containing all the map tiles.
401 	 * @see cached_size
402 	 */
403 	planquadrat_t *plan;
404 
405 	/**
406 	 * Array representing the height of each point of the grid.
407 	 * @see cached_grid_size
408 	 */
409 	sint8 *grid_hgts;
410 
411 	/**
412 	 * Array representing the height of water on each point of the grid.
413 	 * @see cached_grid_size
414 	 */
415 	sint8 *water_hgts;
416 	/** @} */
417 
418 	/**
419 	 * @name Player management
420 	 *       Variables related to the player management in game.
421 	 * @author Hj. Malthaner
422 	 * @{
423 	 */
424 	/**
425 	 * The players of the game.
426 	 * @note Standard human player has index 0, public player 1.
427 	 */
428 	player_t *players[MAX_PLAYER_COUNT];
429 
430 	/**
431 	 * Active player.
432 	 */
433 	player_t *active_player;
434 
435 	/**
436 	 * Active player index.
437 	 */
438 	uint8 active_player_nr;
439 
440 	/**
441 	 * Locally stored password hashes, will be used after reconnect to a server.
442 	 */
443 	pwd_hash_t player_password_hash[MAX_PLAYER_COUNT];
444 	/** @} */
445 
446 	/*
447 	 * Counter for schedules.
448 	 * If a new schedule is active, this counter will increment
449 	 * stations check this counter and will reroute their goods if changed.
450 	 * @author prissi
451 	 */
452 	uint8 schedule_counter;
453 
454 	/**
455 	 * @name Display timing and scheduling
456 	 *       These variables store system display timings in the past frames
457 	 *       and allow for adequate adjustments to adapt to the system performance
458 	 *       and available resources (also in network mode).
459 	 * @{
460 	 */
461 
462 	/**
463 	 * ms since creation.
464 	 * @note The time is in ms (milliseconds)
465 	 * @author Hj. Malthaner
466 	 */
467 	uint32 ticks;
468 
469 	/**
470 	 * Ticks counter at last steps.
471 	 * @note The time is in ms (milliseconds)
472 	 * @author Hj. Malthaner
473 	 */
474 	uint32 last_step_ticks;
475 
476 	/**
477 	 * From now on is next month.
478 	 * @note The time is in ms (milliseconds)
479 	 * @author Hj. Malthaner
480 	 */
481 	uint32 next_month_ticks;
482 
483 	/**
484 	 * Default time stretching factor.
485 	 */
486 	uint32 time_multiplier;
487 
488 	uint8 step_mode;
489 
490 	/// @note variable used in interactive()
491 	uint32 sync_steps;
492 
493 	// The maximum sync_steps that a client can safely advance to.
494 	uint32 sync_steps_barrier;
495 #define LAST_CHECKLISTS_COUNT 64
496 	/// @note variable used in interactive()
497 	checklist_t last_checklists[LAST_CHECKLISTS_COUNT];
498 #define LCHKLST(x) (last_checklists[(x) % LAST_CHECKLISTS_COUNT])
499 	/// @note variable used in interactive()
500 	uint8  network_frame_count;
501 	/**
502 	 * @note Variable used in interactive().
503 	 * @note Set in reset_timer().
504 	 */
505 	sint32 fix_ratio_frame_time;
506 
507 	/**
508 	 * For performance comparison.
509 	 * @author Hj. Malthaner
510 	 */
511 	uint32 realFPS;
512 
513 	/**
514 	 * For performance comparison.
515 	 * @author Hj. Malthaner
516 	 */
517 	uint32 simloops;
518 
519 	/// To calculate the fps and the simloops.
520 	uint32 last_frame_ms[32];
521 
522 	/// To calculate the fps and the simloops.
523 	uint32 last_step_nr[32];
524 
525 	/// To calculate the fps and the simloops.
526 	uint8 last_frame_idx;
527 
528 	/**
529 	 * ms, when the last time events were handled.
530 	 * To calculate the fps and the simloops.
531 	 */
532 	uint32 last_interaction;
533 
534 	/**
535 	 * ms, when the last step was done.
536 	 * To calculate the fps and the simloops.
537 	 */
538 	uint32 last_step_time;
539 
540 	/**
541 	* ms, when the next step is to be done.
542 	* To calculate the fps and the simloops.
543 	*/
544 	uint32 next_step_time;
545 
546 	/**
547 	* ms, when the next check if we need to start next song
548 	*/
549 	uint32 next_midi_time;
550 
551 	/// To calculate the fps and the simloops.
552 	uint32 idle_time;
553 	/** @} */
554 
555 	/**
556 	 * Current accumulated month number, counting January of year 0 as 0.
557 	 * @note last_month + (last_year*12);
558 	 */
559 	sint32 current_month;
560 
561 	/**
562 	 * Last month 0..11
563 	 */
564 	sint32 last_month;
565 
566 	/**
567 	 * Last year.
568 	 */
569 	sint32 last_year;
570 
571 	/**
572 	 * Current season.
573 	 * @note 0=winter, 1=spring, 2=summer, 3=autumn
574 	 */
575 	uint8 season;
576 
577 	/**
578 	 * Number of steps since creation.
579 	 */
580 	sint32 steps;
581 
582 	/**
583 	 * Flag, that now no sound will play.
584 	 */
585 	bool is_sound;
586 
587 	/**
588 	 * Flag for ending simutrans (true -> end simutrans).
589 	 */
590 	bool finish_loop;
591 
592 	/**
593 	 * May change due to timeline.
594 	 */
595 	const way_desc_t *city_road;
596 
597 	/**
598 	 * What game objectives.
599 	 */
600 	scenario_t *scenario;
601 
602 	/**
603 	 * Holds all the text messages in the messagebox (chat, new vehicle etc).
604 	 */
605 	message_t *msg;
606 
607 	/**
608 	 * Array indexed per way type. Used to determine the speedbonus.
609 	 */
610 	sint32 average_speed[8];
611 
612 	/**
613 	 * Used to distribute the workload when changing seasons to several steps.
614 	 */
615 	uint32 tile_counter;
616 
617 	/**
618 	 * To identify different stages of the same game.
619 	 */
620 	uint32 map_counter;
621 
622 	/**
623 	 * the maximum allowed world height.
624 	 */
625 	sint8 world_maximum_height;
626 
627 	/**
628 	 * the minimum allowed world height.
629 	 */
630 	sint8 world_minimum_height;
631 
632 	/**
633 	 * Recalculated speed bonus for different vehicles.
634 	 */
635 	void recalc_average_speed();
636 
637 	/**
638 	 * Monthly actions.
639 	 */
640 	void new_month();
641 
642 	/**
643 	 * Yearly actions.
644 	 */
645 	void new_year();
646 
647 	/**
648 	 * Internal saving method.
649 	 * @author Hj. Malthaner
650 	 */
651 	void save(loadsave_t *file,bool silent);
652 
653 	/**
654 	 * Internal loading method.
655 	 * @author Hj. Malthaner
656 	 */
657 	void load(loadsave_t *file);
658 
659 	/**
660 	 * Removes all objects, deletes all data structures and frees all accessible memory.
661 	 * @author Hj. Malthaner
662 	 */
663 	void destroy();
664 
665 	/**
666 	 * Restores history for older savegames.
667 	 */
668 	void restore_history(bool restore_transported_only);
669 
670 	/**
671 	 * Will create rivers.
672 	 */
673 	void create_rivers(sint16 number);
674 
675 	/**
676 	 * Will create lakes.
677 	 */
678 	void create_lakes( int xoff, int yoff );
679 
680 	/**
681 	 * Will create beaches.
682 	 */
683 	void create_beaches( int xoff, int yoff );
684 
685 	/**
686 	 * Distribute groundobjs and cities on the map but not
687 	 * in the rectangle from (0,0) till (old_x, old_y).
688 	 * It's now an extra function so we don't need the code twice.
689 	 * @author Gerd Wachsmuth
690 	 */
691 	void distribute_groundobjs_cities(int new_cities, sint32 new_mean_citizen_count, sint16 old_x, sint16 old_y );
692 
693 	/**
694 	 * The last time when a server announce was performed (in ms).
695 	 */
696 	uint32 server_last_announce_time;
697 
698 	enum { SYNCX_FLAG = 0x01, GRIDS_FLAG = 0x02 };
699 
700 	void world_xy_loop(xy_loop_func func, uint8 flags);
701 	static void *world_xy_loop_thread(void *);
702 
703 	/**
704 	 * Loops over plans after load.
705 	 */
706 	void plans_finish_rd(sint16, sint16, sint16, sint16);
707 
708 	/**
709 	 * Updates all images.
710 	 */
711 	void update_map_intern(sint16, sint16, sint16, sint16);
712 
713 public:
714 	/**
715 	 * Announce server and current state to listserver.
716 	 * @param status Specifies what information should be announced
717 	 * or offline (the latter only in cases where it is shutting down)
718 	 */
719 	void announce_server(int status);
720 
721 	/// cache the current maximum and minimum height on the map
722 	sint8 max_height, min_height;
723 
724 	/**
725 	 * Returns the messagebox message container.
726 	 */
get_message()727 	message_t *get_message() { return msg; }
728 
729 	/**
730 	 * Set to something useful, if there is a total distance != 0 to show in the bar below.
731 	 */
732 	koord3d show_distance;
733 
734 	/**
735 	 * For warning, when stuff had to be removed/replaced
736 	 * level must be >=1 (1=factory, 2=vehicles, 3=not so important)
737 	 * may be refined later
738 	 */
739 	void add_missing_paks( const char *name, missing_level_t critical_level );
740 
741 	/**
742 	 * Absolute month.
743 	 * @author prissi
744 	 */
get_last_month()745 	inline uint32 get_last_month() const { return last_month; }
746 
747 	/**
748 	 * Returns last year.
749 	 * @author hsiegeln
750 	 */
get_last_year()751 	inline sint32 get_last_year() const { return last_year; }
752 
753 	/**
754 	 * dirty: redraw whole screen.
755 	 * @author Hj. Malthaner
756 	 */
set_dirty()757 	void set_dirty() {dirty=true;}
758 
759 	/**
760 	 * dirty: redraw whole screen.
761 	 * @author Hj. Malthaner
762 	 */
unset_dirty()763 	void unset_dirty() {dirty=false;}
764 
765 	/**
766 	 * dirty: redraw whole screen.
767 	 * @author Hj. Malthaner
768 	 */
is_dirty()769 	bool is_dirty() const {return dirty;}
770 
771 	/**
772 	 * background_dirty: redraw background.
773 	 */
set_background_dirty()774 	void set_background_dirty() { background_dirty = true; }
775 
776 	/**
777 	 * background_dirty: redraw whole screen.
778 	 */
is_background_dirty()779 	bool is_background_dirty() const { return background_dirty; }
780 
781 	/**
782 	 * background_dirty: redraw background.
783 	 */
unset_background_dirty()784 	void unset_background_dirty() { background_dirty = false; }
785 
786 	// do the internal accounting
787 	void buche(sint64 betrag, player_cost type);
788 
789 	// calculates the various entries
790 	void update_history();
791 
get_scenario()792 	scenario_t *get_scenario() const { return scenario; }
793 	void set_scenario(scenario_t *s);
794 
795 	/**
796 	 * Returns the finance history for player.
797 	 * @author hsiegeln
798 	 */
get_finance_history_year(int year,int type)799 	sint64 get_finance_history_year(int year, int type) const { return finance_history_year[year][type]; }
800 
801 	/**
802 	 * Returns the finance history for player.
803 	 * @author hsiegeln
804 	 */
get_finance_history_month(int month,int type)805 	sint64 get_finance_history_month(int month, int type) const { return finance_history_month[month][type]; }
806 
807 	/**
808 	 * Returns pointer to finance history for player.
809 	 * @author hsiegeln
810 	 */
get_finance_history_year()811 	const sint64* get_finance_history_year() const { return *finance_history_year; }
812 
813 	/**
814 	 * Returns pointer to finance history for player.
815 	 * @author hsiegeln
816 	 */
get_finance_history_month()817 	const sint64* get_finance_history_month() const { return *finance_history_month; }
818 
819 	/**
820 	 * Recalcs all map images.
821 	 */
822 	void update_map();
823 
824 	/**
825 	 * Recalcs images after change of underground mode.
826 	 */
827 	void update_underground();
828 
829 	/**
830 	 * @brief Prepares an area of the map to be drawn.
831 	 *
832 	 * New area is the area that will be prepared. Old area is the area that was
833 	 * already prepared. Only the difference between the two rects is prepared.
834 	 */
835 	void prepare_tiles(rect_t const& new_area, rect_t const& old_area);
836 
837 	/**
838 	 * @returns true if world gets destroyed
839 	 */
is_destroying()840 	bool is_destroying() const { return destroying; }
841 
842 	/**
843 	 * Gets the world view.
844 	 */
get_view()845 	main_view_t *get_view() const { return view; }
846 
847 	/**
848 	 * Gets the world viewport.
849 	 */
get_viewport()850 	viewport_t *get_viewport() const { return viewport; }
851 
852 	/**
853 	 * Sets the world view.
854 	 */
set_view(main_view_t * v)855 	void set_view(main_view_t *v) { view = v; }
856 
857 	/**
858 	 * Sets the world event manager.
859 	 */
set_eventmanager(interaction_t * em)860 	void set_eventmanager(interaction_t *em) { eventmanager = em; }
861 
get_settings()862 	settings_t const& get_settings() const { return settings; }
get_settings()863 	settings_t&       get_settings()       { return settings; }
864 
865 	/// returns current speed bonus
get_average_speed(waytype_t typ)866 	sint32 get_average_speed(waytype_t typ) const { return average_speed[ (typ==16 ? 3 : (int)(typ-1)&7 ) ]; }
867 
868 	/// speed record management
869 	sint32 get_record_speed( waytype_t w ) const;
870 	void notify_record( convoihandle_t cnv, sint32 max_speed, koord k );
871 
872 	/// time lapse mode ...
is_paused()873 	bool is_paused() const { return step_mode&PAUSE_FLAG; }
874 	/// stops the game with interaction
875 	void set_pause( bool );
876 
is_fast_forward()877 	bool is_fast_forward() const { return step_mode == FAST_FORWARD; }
878 	void set_fast_forward(bool ff);
879 
880 	/**
881 	 * (un)pause for network games.
882 	 */
883 	void network_game_set_pause(bool pause_, uint32 syncsteps_);
884 
885 	/**
886 	 * @return The active mouse cursor.
887 	 */
888 
get_zeiger()889 	zeiger_t * get_zeiger() const { return zeiger; }
890 
891 	/**
892 	 * Marks an area using the grund_t mark flag.
893 	 * @author prissi
894 	 */
895 	void mark_area( const koord3d center, const koord radius, const bool mark ) const;
896 
897 	/**
898 	 * Player management here
899 	 */
900 	uint8 sp2num(player_t *player);
get_player(uint8 n)901 	player_t * get_player(uint8 n) const { return players[n&15]; }
get_active_player()902 	player_t* get_active_player() const { return active_player; }
get_active_player_nr()903 	uint8 get_active_player_nr() const { return active_player_nr; }
904 	void switch_active_player(uint8 nr, bool silent);
905 	const char *init_new_player( uint8 nr, uint8 type );
906 	void store_player_password_hash( uint8 player_nr, const pwd_hash_t& hash );
get_player_password_hash(uint8 player_nr)907 	const pwd_hash_t& get_player_password_hash( uint8 player_nr ) const { return player_password_hash[player_nr]; }
908 	void clear_player_password_hashes();
909 	void rdwr_player_password_hashes(loadsave_t *file);
910 	void remove_player(uint8 player_nr);
911 
912 	/**
913 	* Get the default public service player.
914 	* @return the default public service player
915 	*/
916 	player_t *get_public_player() const;
917 
918 	/**
919 	 * Network safe initiation of new and deletion of players, change freeplay.
920 	 * @param param Player type (human / ai) of new players.
921 	 */
922 	void call_change_player_tool(uint8 cmd, uint8 player_nr, uint16 param, bool scripted_call=false);
923 
924 	enum change_player_tool_cmds { new_player=1, toggle_freeplay=2, delete_player=3 };
925 	/**
926 	 * @param exec If false checks whether execution is allowed, if true executes tool.
927 	 * @returns Whether execution is allowed.
928 	 */
929 	bool change_player_tool(uint8 cmd, uint8 player_nr, uint16 param, bool public_player_unlocked, bool exec);
930 
931 	/**
932 	 * If a schedule is changed, it will increment the schedule counter
933 	 * every step the haltestelle will check and reroute the goods if needed.
934 	 */
get_schedule_counter()935 	uint8 get_schedule_counter() const { return schedule_counter; }
936 
937 	/**
938 	 * If a schedule is changed, it will increment the schedule counter
939 	 * every step the haltestelle will check and reroute the goods if needed.
940 	 */
941 	void set_schedule_counter();
942 
943 	/**
944 	 * @note Often used, therefore found here.
945 	 */
use_timeline()946 	bool use_timeline() const { return settings.get_use_timeline(); }
947 
948 	void reset_timer();
949 	void reset_interaction();
950 	void step_year();
951 
952 	/**
953 	 * Jump one or more months ahead.
954 	 * @note Updating history!
955 	 */
956 	void step_month( sint16 months=1 );
957 
958 	/**
959 	 * @return Either 0 or the current year*16 + month
960 	 */
get_timeline_year_month()961 	uint16 get_timeline_year_month() const { return settings.get_use_timeline() ? current_month : 0; }
962 
963 	/**
964 	 * Number of ticks per day in bits.
965 	 * @see ticks_per_world_month
966 	 * @author Hj. Malthaner
967 	 */
968 	uint32 ticks_per_world_month_shift;
969 
970 	/**
971 	 * Number of ticks per MONTH!
972 	 * @author Hj. Malthaner
973 	 */
974 	uint32 ticks_per_world_month;
975 
set_ticks_per_world_month_shift(uint32 bits)976 	void set_ticks_per_world_month_shift(uint32 bits) {ticks_per_world_month_shift = bits; ticks_per_world_month = (1 << ticks_per_world_month_shift); }
977 
978 	/**
979 	 * Converts speed (yards per tick) into tiles per month
980 	 *       * A derived quantity:
981 	 * speed * ticks_per_world_month / yards_per_tile
982 	 * == speed << ticks_per_world_month_shift  (pak-set dependent, 18 in old games)
983 	 *          >> yards_per_tile_shift (which is 12 + 8 = 20, see above)
984 	 * This is hard to do with full generality, because shift operators
985 	 * take positive numbers!
986 	 *
987 	 * @author neroden
988 	 */
speed_to_tiles_per_month(uint32 speed)989 	uint32 speed_to_tiles_per_month(uint32 speed) const
990 	{
991 		const int left_shift = ticks_per_world_month_shift - YARDS_PER_TILE_SHIFT;
992 		if (left_shift >= 0) {
993 			return speed << left_shift;
994 		} else {
995 			const int right_shift = -left_shift;
996 			// round to nearest
997 			return (speed + (1<<(right_shift -1)) ) >> right_shift;
998 		}
999 	}
1000 
1001 	/**
1002 	 * Scales value proportionally with month length.
1003 	 * Used to scale monthly maintenance costs and factory production.
1004 	 * @returns value << ( ticks_per_world_month_shift -18 )
1005 	 */
scale_with_month_length(sint64 value)1006 	sint64 scale_with_month_length(sint64 value)
1007 	{
1008 		const int left_shift = ticks_per_world_month_shift - 18;
1009 		if(left_shift >= 0) {
1010 			return value << left_shift;
1011 		}
1012 		else {
1013 			return value >> (-left_shift);
1014 		}
1015 	}
1016 
1017 	/**
1018 	 * Scales value inverse proportionally with month length.
1019 	 * Used to scale monthly maintenance costs, city growth, and factory production.
1020 	 * @returns value << ( 18 - ticks_per_world_month_shift )
1021 	 */
inverse_scale_with_month_length(sint64 value)1022 	sint64 inverse_scale_with_month_length(sint64 value)
1023 	{
1024 		const int left_shift = (int)ticks_per_world_month_shift-18;
1025 		if(  left_shift < 0  ) {
1026 			return value << (-left_shift);
1027 		}
1028 		else {
1029 			return value >> left_shift;
1030 		}
1031 	}
1032 
1033 	sint32 get_time_multiplier() const;
1034 	void change_time_multiplier( sint32 delta );
1035 
1036 	/**
1037 	 * @return 0=winter, 1=spring, 2=summer, 3=autumn
1038 	 * @author prissi
1039 	 */
get_season()1040 	uint8 get_season() const { return season; }
1041 
1042 	/**
1043 	 * Time since map creation or the last load in ms.
1044 	 * @author Hj. Malthaner
1045 	 */
get_ticks()1046 	uint32 get_ticks() const { return ticks; }
1047 
1048 
get_next_month_ticks()1049 	uint32 get_next_month_ticks() const { return next_month_ticks; }
1050 
1051 	/**
1052 	 * Absolute month (count start year zero).
1053 	 * @author prissi
1054 	 */
get_current_month()1055 	uint32 get_current_month() const { return current_month; }
1056 
1057 	/**
1058 	 * prissi: current city road.
1059 	 * @note May change due to timeline.
1060 	 */
get_city_road()1061 	const way_desc_t* get_city_road() const { return city_road; }
1062 
1063 	/**
1064 	 * Number of steps elapsed since the map was generated.
1065 	 * @author Hj. Malthaner
1066 	 */
get_steps()1067 	sint32 get_steps() const { return steps; }
1068 
1069 	/**
1070 	 * Idle time. Nur zur Anzeige verwenden!
1071 	 * @author Hj. Malthaner
1072 	 */
get_idle_time()1073 	uint32 get_idle_time() const { return idle_time; }
1074 
1075 	/**
1076 	 * Number of frames displayed in the last real time second.
1077 	 * @author prissi
1078 	 */
get_realFPS()1079 	uint32 get_realFPS() const { return realFPS; }
1080 
1081 	/**
1082 	 * Number of simulation loops in the last second. Can be very inaccurate!
1083 	 * @author Hj. Malthaner
1084 	 */
get_simloops()1085 	uint32 get_simloops() const { return simloops; }
1086 
1087 	/**
1088 	 * Returns the current waterline height.
1089 	 * @author Hj. Malthaner
1090 	 */
get_groundwater()1091 	sint8 get_groundwater() const { return groundwater; }
1092 
1093 	/**
1094 	 * Returns the minimum allowed height on the map.
1095 	 */
get_minimumheight()1096 	sint8 get_minimumheight() const { return world_minimum_height; }
1097 
1098 	/**
1099 	 * Returns the maximum allowed world height.
1100 	 * @author Hj. Malthaner
1101 	 */
get_maximumheight()1102 	sint8 get_maximumheight() const { return world_maximum_height; }
1103 
1104 	/**
1105 	 * Returns the current snowline height.
1106 	 * @author prissi
1107 	 */
get_snowline()1108 	sint16 get_snowline() const { return snowline; }
1109 
1110 	/**
1111 	 * Initializes the height_to_climate field from settings.
1112 	 */
1113 	void init_height_to_climate();
1114 
1115 	/**
1116 	 * Returns the climate for a given height, ruled by world creation settings.
1117 	 * Used to determine climate when terraforming, loading old games, etc.
1118 	 */
get_climate_at_height(sint16 height)1119 	climate get_climate_at_height(sint16 height) const
1120 	{
1121 		const sint16 h=height-groundwater;
1122 		if(h<0) {
1123 			return water_climate;
1124 		}
1125 		else if(  (uint)h >= lengthof(height_to_climate)  ) {
1126 			return arctic_climate;
1127 		}
1128 		return (climate)height_to_climate[h];
1129 	}
1130 
1131 	/**
1132 	 * returns the current climate for a given koordinate
1133 	 * @author Kieron Green
1134 	 */
get_climate(koord k)1135 	inline climate get_climate(koord k) const {
1136 		const planquadrat_t *plan = access(k);
1137 		return plan ? plan->get_climate() : water_climate;
1138 	}
1139 
1140 	/**
1141 	 * sets the current climate for a given koordinate
1142 	 * @author Kieron Green
1143 	 */
set_climate(koord k,climate cl,bool recalc)1144 	inline void set_climate(koord k, climate cl, bool recalc) {
1145 		planquadrat_t *plan = access(k);
1146 		if(  plan  ) {
1147 			plan->set_climate(cl);
1148 			if(  recalc  ) {
1149 				recalc_transitions(k);
1150 				for(  int i = 0;  i < 8;  i++  ) {
1151 					recalc_transitions( k + koord::neighbours[i] );
1152 				}
1153 			}
1154 		}
1155 	}
1156 
set_mouse_rest_time(uint32 new_val)1157 	void set_mouse_rest_time(uint32 new_val) { mouse_rest_time = new_val; };
set_sound_wait_time(uint32 new_val)1158 	void set_sound_wait_time(uint32 new_val) { sound_wait_time = new_val; };
1159 
1160 private:
1161 	/**
1162 	 * Dummy method, to generate compiler error if someone tries to call get_climate( int ),
1163 	 * as the int parameter will silently be cast to koord...
1164 	 */
1165 	climate get_climate(sint16) const;
1166 
1167 	/**
1168 	 * iterates over the map starting from k setting the water height
1169 	 * lakes are left where there is no drainage
1170 	 * @author Kieron Green
1171 	 */
1172 	void drain_tile(koord k, sint8 water_height);
1173 	bool can_flood_to_depth(koord k, sint8 new_water_height, sint8 *stage, sint8 *our_stage) const;
1174 
1175 public:
1176 	void flood_to_depth(sint8 new_water_height, sint8 *stage);
1177 
1178 	/**
1179 	 * Set a new tool as current: calls local_set_tool or sends to server.
1180 	 */
1181 	void set_tool( tool_t *tool_in, player_t* player );
1182 
1183 	/**
1184 	 * Set a new tool on our client, calls init.
1185 	 */
1186 	void local_set_tool( tool_t *tool_in, player_t* player );
get_tool(uint8 nr)1187 	tool_t *get_tool(uint8 nr) const { return selected_tool[nr]; }
1188 
1189 	/**
1190 	 * Calls the work method of the tool.
1191 	 * Takes network and scenarios into account.
1192 	 */
1193 	const char* call_work(tool_t *t, player_t *pl, koord3d pos, bool &suspended);
1194 
1195 	/**
1196 	 * Returns the (x,y) map size.
1197 	 * @brief Map size.
1198 	 * @note Valid coords are (0..x-1,0..y-1)
1199 	 * @note These values are exactly one less then get_grid_size ones.
1200 	 * @see get_grid_size()
1201 	 */
get_size()1202 	inline koord const &get_size() const { return cached_grid_size; }
1203 
1204 	/**
1205 	 * Maximum size for waiting bars etc.
1206 	 */
get_size_max()1207 	inline int get_size_max() const { return cached_size_max; }
1208 
1209 	/**
1210 	 * @return True if the specified coordinate is inside the world tiles(planquadrat_t) limits, false otherwise.
1211 	 * @param x X coordinate.
1212 	 * @param y Y coordinate.
1213 	 * @note Inline because called very frequently!
1214 	 */
is_within_limits(sint16 x,sint16 y)1215 	inline bool is_within_limits(sint16 x, sint16 y) const {
1216 	// prissi: since negative values will make the whole result negative, we can use bitwise or
1217 	// faster, since pentiums and other long pipeline processors do not like jumps
1218 		return (x|y|(cached_size.x-x)|(cached_size.y-y))>=0;
1219 //		return x>=0 &&  y>=0  &&  cached_groesse_karte_x>=x  &&  cached_groesse_karte_y>=y;
1220 	}
1221 
1222 	/**
1223 	 * @return True if the specified coordinate is inside the world tiles(planquadrat_t) limits, false otherwise.
1224 	 * @param k (x,y) coordinate.
1225 	 * @note Inline because called very frequently!
1226 	 */
is_within_limits(koord k)1227 	inline bool is_within_limits(koord k) const { return is_within_limits(k.x, k.y); }
1228 
1229 	/**
1230 	 * @return True if the specified coordinate is inside the world height grid limits, false otherwise.
1231 	 * @param x X coordinate.
1232 	 * @param y Y coordinate.
1233 	 * @note Inline because called very frequently!
1234 	 */
is_within_grid_limits(sint16 x,sint16 y)1235 	inline bool is_within_grid_limits(sint16 x, sint16 y) const {
1236 	// prissi: since negative values will make the whole result negative, we can use bitwise or
1237 	// faster, since pentiums and other long pipeline processors do not like jumps
1238 		return (x|y|(cached_grid_size.x-x)|(cached_grid_size.y-y))>=0;
1239 //		return x>=0 &&  y>=0  &&  cached_groesse_gitter_x>=x  &&  cached_groesse_gitter_y>=y;
1240 	}
1241 
1242 	/**
1243 	 * @return True if the specified coordinate is inside the world height grid limits, false otherwise.
1244 	 * @param k (x,y) coordinate.
1245 	 * @note Inline because called very frequently!
1246 	 */
is_within_grid_limits(const koord & k)1247 	inline bool is_within_grid_limits(const koord &k) const { return is_within_grid_limits(k.x, k.y); }
1248 
1249 	/**
1250 	 * @return True if the specified coordinate is inside the world height grid limits, false otherwise.
1251 	 * @param x X coordinate.
1252 	 * @param y Y coordinate.
1253 	 * @note Inline because called very frequently!
1254 	 */
is_within_grid_limits(uint16 x,uint16 y)1255 	inline bool is_within_grid_limits(uint16 x, uint16 y) const {
1256 		return (x<=(unsigned)cached_grid_size.x && y<=(unsigned)cached_grid_size.y);
1257 	}
1258 
1259 	/**
1260 	 * Returns the closest coordinate to outside_pos that is within the world
1261 	 */
1262 	koord get_closest_coordinate(koord outside_pos);
1263 
1264 	/**
1265 	 * @return grund an pos/hoehe
1266 	 * @note Inline because called very frequently!
1267 	 * @author Hj. Malthaner
1268 	 */
lookup(const koord3d & pos)1269 	inline grund_t *lookup(const koord3d &pos) const
1270 	{
1271 		const planquadrat_t *plan = access(pos.x, pos.y);
1272 		return plan ? plan->get_boden_in_hoehe(pos.z) : NULL;
1273 	}
1274 
1275 	/**
1276 	 * This function takes grid coordinates as a parameter and a desired height (koord3d).
1277 	 * Will return the ground_t object that intersects with it in it's north corner if possible.
1278 	 * If that tile doesn't exist, returns the one that intersects with it in other corner.
1279 	 * @param pos Grid coordinates to check for, the z points to the desired height.
1280 	 * @see lookup_kartenboden_gridcoords
1281 	 * @see corner_to_operate
1282 	 * @note Inline because called very frequently!
1283 	 */
lookup_gridcoords(const koord3d & pos)1284 	inline grund_t *lookup_gridcoords(const koord3d &pos) const
1285 	{
1286 		if ( ( pos.x != cached_grid_size.x )  &&  ( pos.y != cached_grid_size.y ) ){
1287 			return lookup(koord3d(pos.x, pos.y, pos.z));
1288 		}
1289 
1290 		if ( ( pos.x == cached_grid_size.x )  &&  ( pos.y == cached_grid_size.y ) ) {
1291 			return lookup(koord3d(pos.x-1, pos.y-1, pos.z));
1292 		}
1293 		else if ( pos.x == cached_grid_size.x ) {
1294 			return lookup(koord3d(pos.x-1, pos.y, pos.z));
1295 		}
1296 		return lookup(koord3d(pos.x, pos.y-1, pos.z));
1297 	}
1298 
1299 	/**
1300 	 * This function takes 2D grid coordinates as a parameter, will return the ground_t object that
1301 	 * intersects with it in it's north corner if possible. If that tile doesn't exist, returns
1302 	 * the one that intersects with it in other corner.
1303 	 * @param pos Grid coordinates to check for.
1304 	 * @see corner_to_operate
1305 	 * @see lookup_gridcoords
1306 	 * @return The requested tile, or the immediately adjacent in case of lower border.
1307 	 * @note Inline because called very frequently!
1308 	 */
lookup_kartenboden_gridcoords(const koord & pos)1309 	inline grund_t *lookup_kartenboden_gridcoords(const koord &pos) const
1310 	{
1311 		if ( ( pos.x != cached_grid_size.x )  &&  ( pos.y != cached_grid_size.y ) ){
1312 			return lookup_kartenboden(pos);
1313 		}
1314 
1315 		if ( ( pos.x == cached_grid_size.x )  &&  ( pos.y == cached_grid_size.y ) ) {
1316 			return access(koord(pos.x-1, pos.y-1))->get_kartenboden();
1317 		}
1318 		else if ( pos.x == cached_grid_size.x ) {
1319 			return access(koord(pos.x-1, pos.y))->get_kartenboden();
1320 		}
1321 		return access(koord(pos.x, pos.y-1))->get_kartenboden();
1322 	}
1323 
1324 	/**
1325 	 * @return The corner that needs to be raised/lowered on the given coordinates.
1326 	 * @param pos Grid coordinate to check.
1327 	 * @note Inline because called very frequently!
1328 	 * @note Will always return north-west except on border tiles.
1329 	 * @pre pos has to be a valid grid coordinate, undefined otherwise.
1330 	 */
get_corner_to_operate(const koord & pos)1331 	inline slope_t::type get_corner_to_operate(const koord &pos) const
1332 	{
1333 		// Normal tile
1334 		if ( ( pos.x != cached_grid_size.x )  &&  ( pos.y != cached_grid_size.y ) ){
1335 			return slope4_t::corner_NW;
1336 		}
1337 		// Border on south-east
1338 		if ( is_within_limits(pos.x-1, pos.y) ) {
1339 			return(slope4_t::corner_NE);
1340 		}
1341 		// Border on south-west
1342 		if ( is_within_limits(pos.x, pos.y-1) ) {
1343 			return(slope4_t::corner_SW);
1344 		}
1345 		// Border on south
1346 		return (slope4_t::corner_SE);
1347 	}
1348 
1349 
1350 private:
1351 	/**
1352 	 * @return grund at the bottom (where house will be build)
1353 	 * @note Inline because called very frequently! - nocheck for more speed
1354 	 */
lookup_kartenboden_nocheck(const sint16 x,const sint16 y)1355 	inline grund_t *lookup_kartenboden_nocheck(const sint16 x, const sint16 y) const
1356 	{
1357 		return plan[x+y*cached_grid_size.x].get_kartenboden();
1358 	}
1359 
lookup_kartenboden_nocheck(const koord & pos)1360 	inline grund_t *lookup_kartenboden_nocheck(const koord &pos) const { return lookup_kartenboden_nocheck(pos.x, pos.y); }
1361 public:
1362 	/**
1363 	 * @return grund at the bottom (where house will be build)
1364 	 * @note Inline because called very frequently!
1365 	 */
lookup_kartenboden(const sint16 x,const sint16 y)1366 	inline grund_t *lookup_kartenboden(const sint16 x, const sint16 y) const
1367 	{
1368 		return is_within_limits(x, y) ? plan[x+y*cached_grid_size.x].get_kartenboden() : NULL;
1369 	}
1370 
lookup_kartenboden(const koord & pos)1371 	inline grund_t *lookup_kartenboden(const koord &pos) const { return lookup_kartenboden(pos.x, pos.y); }
1372 
1373 	/**
1374 	 * @return The natural slope at a position.
1375 	 * @note Uses the corner height for the best slope.
1376 	 * @author prissi
1377 	 */
1378 	uint8	recalc_natural_slope( const koord k, sint8 &new_height ) const;
1379 
1380 	/**
1381 	 * Returns the natural slope a a position using the grid.
1382 	 * @note No checking, and only using the grind for calculation.
1383 	 */
1384 	uint8	calc_natural_slope( const koord k ) const;
1385 
1386 	 /**
1387 	  * Initialize map.
1388 	  * @param sets Game settings.
1389 	  * @param preselected_players Defines which players the user has selected before he started the game.
1390 	  * @author Hj. Malthaner
1391 	  */
1392 	void init(settings_t*, sint8 const* heights);
1393 
1394 	void init_tiles();
1395 
1396 	void enlarge_map(settings_t const*, sint8 const* h_field);
1397 
1398 	karte_t();
1399 
1400 	~karte_t();
1401 
1402 
1403 
1404 	/**
1405 	 * File version used when loading (or current if generated)
1406 	 * @note Useful for finish_rd
1407 	 */
1408 	uint32 load_version;
1409 
1410 	/**
1411 	 * Checks if the planquadrat (tile) at coordinate (x,y)
1412 	 * can be lowered at the specified height.
1413 	 * @author V. Meyer
1414 	 */
1415 	const char* can_lower_plan_to(const player_t *player, sint16 x, sint16 y, sint8 h) const;
1416 
1417 	/**
1418 	 * Checks if the planquadrat (tile) at coordinate (x,y)
1419 	 * can be raised at the specified height.
1420 	 * @author V. Meyer
1421 	 */
1422 	const char* can_raise_plan_to(const player_t *player, sint16 x, sint16 y, sint8 h) const;
1423 
1424 	/**
1425 	 * Checks if the whole planquadrat (tile) at coordinates (x,y) height can
1426 	 * be changed ( for example, water height can't be changed ).
1427 	 * @author Hj. Malthaner
1428 	 */
1429 	bool is_plan_height_changeable(sint16 x, sint16 y) const;
1430 
1431 	/**
1432 	 * Increases the height of the grid coordinate (x, y) by one.
1433 	 * @param pos Grid coordinate.
1434 	 */
1435 	int grid_raise(const player_t *player, koord pos, const char*&err);
1436 
1437 	/**
1438 	 * Decreases the height of the grid coordinate (x, y) by one.
1439 	 * @param pos Grid coordinate.
1440 	 */
1441 	int grid_lower(const player_t *player, koord pos, const char*&err);
1442 
1443 	// mostly used by AI: Ask to flatten a tile
1444 	bool can_flatten_tile(player_t *player, koord k, sint8 hgt, bool keep_water=false, bool make_underwater_hill=false);
1445 	bool flatten_tile(player_t *player, koord k, sint8 hgt, bool keep_water=false, bool make_underwater_hill=false, bool justcheck=false);
1446 
1447 	/**
1448 	 * Class to manage terraform operations.
1449 	 * Can be used for raise only or lower only operations, but not mixed.
1450 	 */
1451 	class terraformer_t {
1452 		/// Structure to save terraforming operations
1453 		struct node_t {
1454 			sint16 x;    ///< x-coordinate
1455 			sint16 y;    ///< y-coordinate
1456 			sint8  h[4]; ///< height of corners, order: sw se ne nw
1457 			uint8  changed;
1458 
node_tnode_t1459 			node_t(sint16 x_, sint16 y_, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw, uint8 c)
1460 			: x(x_), y(y_), changed(c) { h[0]=hsw; h[1]=hse; h[2]=hne; h[3]=hnw; }
1461 
node_tnode_t1462 			node_t() : x(-1), y(-1), changed(0) {}
1463 
1464 			/// compares position
1465 			bool operator== (const node_t& a) const { return (a.x==x)  && (a.y==y); }
1466 
1467 			/// compares position
1468 			static bool comp(const node_t& a, const node_t& b);
1469 		};
1470 
1471 		vector_tpl<node_t> list; ///< list of affected tiles
1472 		uint8 actual_flag;       ///< internal flag to iterate through list
1473 		bool ready;              ///< internal flag to signal iteration ready
1474 		karte_t* welt;
1475 
1476 		void add_node(bool raise, sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
1477 	public:
terraformer_t(karte_t * w)1478 		terraformer_t(karte_t* w) { init(); welt = w; }
1479 
init()1480 		void init() { list.clear(); actual_flag = 1; ready = false; }
1481 
1482 		/**
1483 		 * Add tile to be raised.
1484 		 */
1485 		void add_raise_node(sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
1486 
1487 		/**
1488 		 * Add tile to be lowered.
1489 		 */
1490 		void add_lower_node(sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
1491 
1492 		/**
1493 		 * Generate list of all tiles that will be affected.
1494 		 */
1495 		void iterate(bool raise);
1496 
1497 		/// Check whether raise operation would succeed
1498 		const char* can_raise_all(const player_t *player, bool keep_water=false) const;
1499 		/// Check whether lower operation would succeed
1500 		const char* can_lower_all(const player_t *player) const;
1501 
1502 		/// Do the raise operations
1503 		int raise_all();
1504 		/// Do the lower operations
1505 		int lower_all();
1506 	};
1507 
1508 private:
1509 	/// Internal functions to be used with terraformer_t to propagate terrain changes to neighbouring tiles
1510 	void prepare_raise(terraformer_t& digger, sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
1511 	void prepare_lower(terraformer_t& digger, sint16 x, sint16 y, sint8 hsw, sint8 hse, sint8 hne, sint8 hnw);
1512 
1513 public:
1514 
1515 	// the convois are also handled each step => thus we keep track of them too
1516 	void add_convoi(convoihandle_t);
1517 	void rem_convoi(convoihandle_t);
convoys()1518 	vector_tpl<convoihandle_t> const& convoys() const { return convoi_array; }
1519 
1520 	/**
1521 	 * To access the cities array.
1522 	 * @author Hj. Malthaner
1523 	 */
get_cities()1524 	const weighted_vector_tpl<stadt_t*>& get_cities() const { return stadt; }
1525 	void add_city(stadt_t *s);
1526 
1527 	/**
1528 	 * Removes town from map, houses will be left overs.
1529 	 * @author prissi
1530 	 */
1531 	bool remove_city(stadt_t *s);
1532 
1533 	/* tourist attraction list */
1534 	void add_attraction(gebaeude_t *gb);
1535 	void remove_attraction(gebaeude_t *gb);
get_attractions()1536 	const weighted_vector_tpl<gebaeude_t*> &get_attractions() const {return attractions; }
1537 
add_label(koord k)1538 	void add_label(koord k) { if (!labels.is_contained(k)) labels.append(k); }
remove_label(koord k)1539 	void remove_label(koord k) { labels.remove(k); }
get_label_list()1540 	const slist_tpl<koord>& get_label_list() const { return labels; }
1541 
1542 	bool add_fab(fabrik_t *fab);
1543 	bool rem_fab(fabrik_t *fab);
get_fab_index(fabrik_t * fab)1544 	int get_fab_index(fabrik_t* fab)  const { return fab_list.index_of(fab); }
get_fab(unsigned index)1545 	fabrik_t* get_fab(unsigned index) const { return index < fab_list.get_count() ? fab_list.at(index) : NULL; }
get_fab_list()1546 	const slist_tpl<fabrik_t*>& get_fab_list() const { return fab_list; }
1547 
1548 	/**
1549 	 * Returns a list of goods produced by factories that exist in current game.
1550 	 */
1551 	const vector_tpl<const goods_desc_t*> &get_goods_list();
1552 
1553 	/**
1554 	 * Searches and returns the closest city
1555 	 * but prefers even farther cities if within their city limits
1556 	 * @author Hj. Malthaner
1557 	 */
1558 	stadt_t *find_nearest_city(koord k) const;
1559 
cannot_save()1560 	bool cannot_save() const { return nosave; }
set_nosave()1561 	void set_nosave() { nosave = true; nosave_warning = true; }
set_nosave_warning()1562 	void set_nosave_warning() { nosave_warning = true; }
1563 
1564 	/// rotate plans by 90 degrees
1565 	void rotate90_plans(sint16 x_min, sint16 x_max, sint16 y_min, sint16 y_max);
1566 
1567 	/// rotate map view by 90 degrees
1568 	void rotate90();
1569 
1570 	class sync_list_t {
1571 			friend class karte_t;
1572 		public:
sync_list_t()1573 			sync_list_t() : currently_deleting(NULL), sync_step_running(false) {}
1574 			void add(sync_steppable *obj);
1575 			void remove(sync_steppable *obj);
1576 		private:
1577 			void sync_step(uint32 delta_t);
1578 			/// clears list, does not delete the objects
1579 			void clear();
1580 
1581 			vector_tpl<sync_steppable *> list;  ///< list of sync-steppable objects
1582 			sync_steppable* currently_deleting; ///< deleted durign sync_step, safeguard calls to remove
1583 			bool sync_step_running;
1584 	};
1585 
1586 	sync_list_t sync;              ///< vehicles, transformers, traffic lights
1587 	sync_list_t sync_eyecandy;     ///< animated buildings
1588 	sync_list_t sync_way_eyecandy; ///< smoke
1589 
1590 	/**
1591 	 * Synchronous stepping of objects like vehicles.
1592 	 */
1593 	void sync_step(uint32 delta_t, bool sync, bool display );	// advance also the timer
1594 	/**
1595 	 * Tasks that are more time-consuming, like route search of vehicles and production of factories.
1596 	 */
1597 	void step();
1598 
1599 private:
access_nocheck(int i,int j)1600 	inline planquadrat_t *access_nocheck(int i, int j) const {
1601 		return &plan[i + j*cached_grid_size.x];
1602 	}
1603 
access_nocheck(koord k)1604 	inline planquadrat_t *access_nocheck(koord k) const { return access_nocheck(k.x, k.y); }
1605 
1606 public:
access(int i,int j)1607 	inline planquadrat_t *access(int i, int j) const {
1608 		return is_within_limits(i, j) ? &plan[i + j*cached_grid_size.x] : NULL;
1609 	}
1610 
access(koord k)1611 	inline planquadrat_t *access(koord k) const { return access(k.x, k.y); }
1612 
1613 private:
1614 	/**
1615 	 * @return Height at the grid point i, j - versions without checks for speed
1616 	 * @author Hj. Malthaner
1617 	 */
lookup_hgt_nocheck(sint16 x,sint16 y)1618 	inline sint8 lookup_hgt_nocheck(sint16 x, sint16 y) const {
1619 		return grid_hgts[x + y*(cached_grid_size.x+1)];
1620 	}
1621 
lookup_hgt_nocheck(koord k)1622 	inline sint8 lookup_hgt_nocheck(koord k) const { return lookup_hgt_nocheck(k.x, k.y); }
1623 
1624 public:
1625 	/**
1626 	 * @return Height at the grid point i, j
1627 	 * @author Hj. Malthaner
1628 	 */
lookup_hgt(sint16 x,sint16 y)1629 	inline sint8 lookup_hgt(sint16 x, sint16 y) const {
1630 		return is_within_grid_limits(x, y) ? grid_hgts[x + y*(cached_grid_size.x+1)] : groundwater;
1631 	}
1632 
lookup_hgt(koord k)1633 	inline sint8 lookup_hgt(koord k) const { return lookup_hgt(k.x, k.y); }
1634 
1635 	/**
1636 	 * Sets grid height.
1637 	 * Never set grid_hgts manually, always use this method!
1638 	 * @author Hj. Malthaner
1639 	 */
set_grid_hgt(sint16 x,sint16 y,sint8 hgt)1640 	void set_grid_hgt(sint16 x, sint16 y, sint8 hgt) { grid_hgts[x + y*(uint32)(cached_grid_size.x+1)] = hgt; }
1641 
set_grid_hgt(koord k,sint8 hgt)1642 	inline void set_grid_hgt(koord k, sint8 hgt) { set_grid_hgt(k.x, k.y, hgt); }
1643 
1644 
1645 private:
1646 	/**
1647 	 * @return water height - versions without checks for speed
1648 	 * @author Kieron Green
1649 	 */
get_water_hgt_nocheck(sint16 x,sint16 y)1650 	inline sint8 get_water_hgt_nocheck(sint16 x, sint16 y) const {
1651 		return water_hgts[x + y * (cached_grid_size.x)];
1652 	}
1653 
get_water_hgt_nocheck(koord k)1654 	inline sint8 get_water_hgt_nocheck(koord k) const { return get_water_hgt_nocheck(k.x, k.y); }
1655 
1656 public:
1657 	/**
1658 	 * @return water height
1659 	 * @author Kieron Green
1660 	 */
get_water_hgt(sint16 x,sint16 y)1661 	inline sint8 get_water_hgt(sint16 x, sint16 y) const {
1662 		return is_within_limits( x, y ) ? water_hgts[x + y * (cached_grid_size.x)] : groundwater;
1663 	}
1664 
get_water_hgt(koord k)1665 	inline sint8 get_water_hgt(koord k) const { return get_water_hgt(k.x, k.y); }
1666 
1667 
1668 	/**
1669 	 * Sets water height.
1670 	 * @author Kieron Green
1671 	 */
set_water_hgt(sint16 x,sint16 y,sint8 hgt)1672 	void set_water_hgt(sint16 x, sint16 y, sint8 hgt) { water_hgts[x + y * (cached_grid_size.x)] = (hgt); }
1673 
set_water_hgt(koord k,sint8 hgt)1674 	inline void set_water_hgt(koord k, sint8 hgt) {  set_water_hgt(k.x, k.y, hgt); }
1675 
1676 	/**
1677 	 * Fills array with corner heights of neighbours
1678 	 * @author Kieron Green
1679 	 */
1680 	void get_neighbour_heights(const koord k, sint8 neighbour_height[8][4]) const;
1681 
1682 	/**
1683 	 * Calculates appropriate climate for a tile
1684 	 * @author Kieron Green
1685 	 */
1686 	void calc_climate(koord k, bool recalc);
1687 
1688 	/**
1689 	 * Rotates climate and water transitions for a tile
1690 	 * @author Kieron Green
1691 	 */
1692 	void rotate_transitions(koord k);
1693 
1694 	/**
1695 	 * Recalculate climate and water transitions for a tile
1696 	 * @author Kieron Green
1697 	 */
1698 	void recalc_transitions(koord k);
1699 
1700 	/**
1701 	 * Loop recalculating transitions - suitable for multithreading
1702 	 * @author Kieron Green
1703 	 */
1704 	void recalc_transitions_loop(sint16, sint16, sint16, sint16);
1705 
1706 	/**
1707 	 * Loop creating grounds on all plans from height and water height - suitable for multithreading
1708 	 * @author Kieron Green
1709 	 */
1710 	void create_grounds_loop(sint16, sint16, sint16, sint16);
1711 
1712 	/**
1713 	 * Loop cleans grounds so that they have correct boden and slope - suitable for multithreading
1714 	 * @author Kieron Green
1715 	 */
1716 	void cleanup_grounds_loop(sint16, sint16, sint16, sint16);
1717 
1718 private:
1719 	/**
1720 	 * @return Minimum height of the planquadrats (tile) at i, j. - for speed no checks performed that coordinates are valid
1721 	 * @author Hj. Malthaner
1722 	 */
1723 	sint8 min_hgt_nocheck(koord k) const;
1724 
1725 	/**
1726 	 * @return Maximum height of the planquadrats (tile) at i, j. - for speed no checks performed that coordinates are valid
1727 	 * @author Hj. Malthaner
1728 	 */
1729 	sint8 max_hgt_nocheck(koord k) const;
1730 
1731 public:
1732 	/**
1733 	 * @return Minimum height of the planquadrats (tile) at i, j.
1734 	 * @author Hj. Malthaner
1735 	 */
1736 	sint8 min_hgt(koord k) const;
1737 
1738 	/**
1739 	 * @return Maximum height of the planquadrats (tile) at i, j.
1740 	 * @author Hj. Malthaner
1741 	 */
1742 	sint8 max_hgt(koord k) const;
1743 
1744 	/**
1745 	 * @return true, wenn Platz an Stelle pos mit Groesse dim Water ist
1746 	 * @author V. Meyer
1747 	 */
1748 	bool is_water(koord k, koord dim) const;
1749 
1750 	/**
1751 	 * @return true, if square in place (i,j) with size w, h is constructible.
1752 	 * @author Hj. Malthaner
1753 	 */
1754 	bool square_is_free(koord k, sint16 w, sint16 h, int *last_y, climate_bits cl) const;
1755 
1756 	/**
1757 	 * @return A list of all buildable squares with size w, h.
1758 	 * @note Only used for town creation at the moment.
1759 	 * @author Hj. Malthaner
1760 	 */
1761 	slist_tpl<koord> * find_squares(sint16 w, sint16 h, climate_bits cl, sint16 old_x, sint16 old_y) const;
1762 
1763 	/**
1764 	 * Plays the sound when the position is inside the visible region.
1765 	 * The sound plays lower when the position is outside the visible region.
1766 	 * @param pos Position at which the event took place.
1767 	 * @param idx Index of the sound
1768 	 * @author Hj. Malthaner
1769 	 */
1770 	bool play_sound_area_clipped(koord k, uint16 idx) const;
1771 
mute_sound(bool state)1772 	void mute_sound( bool state ) { is_sound = !state; }
1773 
1774 	/* if start is true, the current map will be used as servergame
1775 	 * Does not announce a new map!
1776 	 */
1777 	void switch_server( bool start_server, bool port_forwarding );
1778 
1779 	/**
1780 	 * Saves the map to a file.
1781 	 * @param Filename name of the file to write.
1782 	 * @author Hj. Malthaner
1783 	 */
1784 	void save(const char *filename, const loadsave_t::mode_t savemode, const char *version, bool silent);
1785 
1786 	/**
1787 	 * Loads a map from a file.
1788 	 * @param Filename name of the file to read.
1789 	 * @author Hj. Malthaner
1790 	 */
1791 	bool load(const char *filename);
1792 
1793 	/**
1794 	 * Creates a map from a heightfield.
1795 	 * @param sets game settings.
1796 	 * @author Hj. Malthaner
1797 	 */
1798 	void load_heightfield(settings_t*);
1799 
1800 	/**
1801 	 * Stops simulation and optionally closes the game.
1802 	 * @param exit_game If true, the game will also close.
1803 	 */
1804 	void stop(bool exit_game);
1805 
1806 	/**
1807 	 * Main loop with event handling.
1808 	 * @return false to exit.
1809 	 * @author Hj. Malthaner
1810 	 */
1811 	bool interactive(uint32 quit_month);
1812 
get_sync_steps()1813 	uint32 get_sync_steps() const { return sync_steps; }
1814 
1815 	/**
1816 	 * Checks whether checklist is available, ie given sync_step is not too far into past.
1817 	 */
is_checklist_available(const uint32 sync_step)1818 	bool is_checklist_available(const uint32 sync_step) const { return sync_step + LAST_CHECKLISTS_COUNT > sync_steps; }
get_checklist_at(const uint32 sync_step)1819 	const checklist_t& get_checklist_at(const uint32 sync_step) const { return LCHKLST(sync_step); }
set_checklist_at(const uint32 sync_step,const checklist_t & chklst)1820 	void set_checklist_at(const uint32 sync_step, const checklist_t &chklst) { LCHKLST(sync_step) = chklst; }
1821 
get_last_checklist()1822 	const checklist_t& get_last_checklist() const { return LCHKLST(sync_steps); }
get_last_checklist_sync_step()1823 	uint32 get_last_checklist_sync_step() const { return sync_steps; }
1824 
1825 	void command_queue_append(network_world_command_t*) const;
1826 
1827 	void clear_command_queue() const;
1828 
1829 	void network_disconnect();
1830 
1831 	/**
1832 	 * To identify the current map.
1833 	 */
get_map_counter()1834 	uint32 get_map_counter() const { return map_counter; }
1835 	void set_map_counter(uint32 new_map_counter);
1836 	/**
1837 	 * Called by the server before sending the sync commands.
1838 	 */
1839 	uint32 generate_new_map_counter() const;
1840 
1841 private:
1842 	void process_network_commands(sint32* ms_difference);
1843 	void do_network_world_command(network_world_command_t *nwc);
1844 	uint32 get_next_command_step();
1845 };
1846 
1847 
1848 /**
1849  * Returns pointer to single instance of the world.
1850  */
world()1851 inline karte_t *world()
1852 {
1853 	return karte_t::world;
1854 }
1855 
1856 
1857 /**
1858  * Class to access the pointer to the world.
1859  * No need to initialize it.
1860  */
1861 class karte_ptr_t
1862 {
1863 public:
1864 	/// dereference operator: karte_ptr_t can be used as it would be karte_t*
1865 	karte_t& operator*() {
1866 		assert( karte_t::world );
1867 		return *karte_t::world;
1868 	}
1869 	const karte_t& operator*() const {
1870 		assert( karte_t::world );
1871 		return *karte_t::world;
1872 	}
1873 
karte_ptr_t()1874 	karte_ptr_t() {}
1875 	/// dereference operator: karte_ptr_t can be used as it would be karte_t*
1876 	karte_t* operator->() {
1877 		assert( karte_t::world );
1878 		return karte_t::world;
1879 	}
1880 	const karte_t* operator->() const {
1881 		assert( karte_t::world );
1882 		return karte_t::world;
1883 	}
1884 
1885 	/// cast to karte_t*
1886 	operator karte_t* () const { return karte_t::world; }
1887 private:
1888 	karte_ptr_t(const karte_ptr_t&);
1889 	karte_ptr_t& operator=(const karte_ptr_t&);
1890 	// no cast to bool please
1891 	operator bool () const;
1892 };
1893 
1894 #endif
1895