Debian Codegraph @

engine/include/unit.h

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name unit.h - The unit headerfile. */
11 //
12 // (c) Copyright 1998-2008 by Lutz Sammer and Jimmy Salmon
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27
28 #ifndef __UNIT_H__
29 #define __UNIT_H__
30
31 //@{
32
33 /*----------------------------------------------------------------------------
34 -- Documentation
35 ----------------------------------------------------------------------------*/
36
37 /**
38 ** @class CUnit unit.h
39 **
40 ** \#include "unit.h"
41 **
42 ** Everything belonging to a unit. FIXME: rearrange for less memory.
43 **
44 ** This class contains all information about a unit in game.
45 ** A unit could be anything: a man, a vehicle, a ship, or a building.
46 ** Currently only a tile, a unit, or a missile could be placed on the map.
47 **
48 ** The unit structure members:
49 **
50 ** CUnit::Refs
51 **
52 ** The reference counter of the unit. If the pointer to the unit
53 ** is stored the counter must be incremented and if this reference
54 ** is destroyed the counter must be decremented. Alternative it
55 ** would be possible to implement a garbage collector for this.
56 **
57 ** CUnit::Slot
58 **
59 ** This is the unique slot number. It is not possible that two
60 ** units have the same slot number at the same time. The slot
61 ** numbers are reused.
62 ** This field could be accessed by the macro UnitNumber(Unit *).
63 ** Maximal 65535 (=#MAX_UNIT_SLOTS) simultaneous units are
64 ** supported.
65 **
66 ** CUnit::UnitSlot
67 **
68 ** This is the pointer into #Units[], where the unit pointer is
69 ** stored. #Units[] is a table of all units currently active in
70 ** game. This pointer is only needed to speed up, the remove of
71 ** the unit pointer from #Units[], it didn't must be searched in
72 ** the table.
73 **
74 ** CUnit::PlayerSlot
75 **
76 ** A pointer into Player::Units[], where the unit pointer is
77 ** stored. Player::Units[] is a table of all units currently
78 ** belonging to a player. This pointer is only needed to speed
79 ** up, the remove of the unit pointer from Player::Units[].
80 **
81 ** CUnit::Next
82 **
83 ** A generic link pointer. This member is currently used, if an
84 ** unit is on the map, to link all units on the same map field
85 ** together. This also links corpses and stuff. Also, this is
86 ** used in memory management to link unused units.
87 **
88 ** CUnit::Container
89 **
90 ** Pointer to the unit containing it, or NoUnitP if the unit is
91 ** free. This points to the transporter for units on board, or to
92 ** the building for peasants inside(when they are mining).
93 **
94 ** CUnit::UnitInside
95 **
96 ** Pointer to the last unit added inside. Order doesn't really
97 ** matter. All units inside are kept in a circular linked list.
98 ** This is NoUnitP if there are no units inside. Multiple levels
99 ** of inclusion are allowed, though not very usefull right now
100 **
101 ** CUnit::NextContained, CUnit::PrevContained
102 **
103 ** The next and previous element in the curent container. Bogus
104 ** values allowed for units not contained.
105 **
106 ** CUnit::InsideCount
107 **
108 ** The number of units inside the container.
109 **
110 ** CUnit::BoardCount
111 **
112 ** The number of units transported inside the container. This
113 ** does not include for instance stuff like harvesters returning
114 ** cargo.
115 **
116 ** CUnit::X CUnit::Y
117 **
118 ** The tile map coordinates of the unit. 0,0 is the upper left on
119 ** the map. To convert the map coordinates into pixels, they
120 ** must be multiplicated with the #TileSizeX and #TileSizeY.
121 ** To get the pixel coordinates of a unit, calculate
122 ** CUnit::X*#TileSizeX+CUnit::IX , CUnit::Y*#TileSizeY+CUnit::IY.
123 **
124 ** CUnit::Type
125 **
126 ** Pointer to the unit-type (::UnitType). The unit-type contains
127 ** all informations that all units of the same type shares.
128 ** (Animations, Name, Stats, ...)
129 **
130 ** CUnit::SeenType
131 ** Pointer to the unit-type that this unit was, when last seen.
132 ** Currently only used by buildings.
133 **
134 ** CUnit::Player
135 **
136 ** Pointer to the owner of this unit (::Player). An unit could
137 ** only be owned by one player.
138 **
139 ** CUnit::Stats
140 **
141 ** Pointer to the current status (::UnitStats) of a unit. The
142 ** units of the same player and the same type could share the same
143 ** stats. The status contains all values which could be different
144 ** for each player. This f.e. the upgradeable abilities of an
145 ** unit. (CUnit::Stats::SightRange, CUnit::Stats::Armor,
146 ** CUnit::Stats::HitPoints, ...)
147 **
148 ** CUnit::CurrentSightRange
149 **
150 ** Current sight range of a unit, this changes when a unit enters
151 ** a transporter or building or exits one of these.
152 **
153 ** CUnit::Colors
154 **
155 ** Player colors of the unit. Contains the hardware dependent
156 ** pixel values for the player colors (palette index #208-#211).
157 ** Setup from the global palette. This is a pointer.
158 ** @note Index #208-#211 are various SHADES of the team color
159 ** (#208 is brightest shade, #211 is darkest shade) .... these
160 ** numbers are NOT red=#208, blue=#209, etc
161 **
162 ** CUnit::IX CUnit::IY
163 **
164 ** Coordinate displacement in pixels or coordinates inside a tile.
165 ** If the unit is moving from one tile to an adjacent one.
166 ** CUnit::IX is between -::TileSizeX and +::TileSizeX,
167 ** and counts towards 0 during horizontal motion.
168 ** CUnit::IY is similar.
169 **
170 ** CUnit::Frame
171 **
172 ** Current graphic image of the animation sequence. The high bit
173 ** (128) is used to flip this image horizontal (x direction).
174 ** This also limits the number of different frames/image to 126.
175 **
176 ** CUnit::SeenFrame
177 **
178 ** Graphic image (see CUnit::Frame) what the player on this
179 ** computer has last seen. If UnitNotSeen the player haven't seen
180 ** this unit yet.
181 **
182 ** CUnit::Direction
183 **
184 ** Contains the binary angle (0-255) in which the direction the
185 ** unit looks. 0, 32, 64, 128, 160, 192, 224, 256 corresponds to
186 ** 0, 45, 90, 135, 180, 225, 270, 315, 360 or north,
187 ** north-east, east, south-east, south, south-west, west,
188 ** north-west, north. Currently only 8 directions are used, this
189 ** is more for the future.
190 **
191 ** CUnit::Attacked
192 **
193 ** Last cycle the unit was attacked. 0 means never.
194 **
195 ** CUnit::Burning
196 **
197 ** If Burning is non-zero, the unit is burning.
198 **
199 ** CUnit::VisCount[PlayerMax]
200 **
201 ** Used to keep track of visible units on the map, it counts the
202 ** Number of seen tiles for each player. This is only modified
203 ** in UnitsMarkSeen and UnitsUnmarkSeen, from fow.
204 ** We keep track of visilibty for each player, and combine with
205 ** Shared vision ONLY when querying and such.
206 **
207 ** CUnit::SeenByPlayer
208 **
209 ** This is a bitmask of 1 and 0 values. SeenByPlayer & (1<<p) is 0
210 ** If p never saw the unit and 1 if it did. This is important for
211 ** keeping track of dead units under fog. We only keep track of units
212 ** that are visible under fog with this.
213 **
214 ** CUnit::Destroyed
215 **
216 ** Unit is destroyed. pending reference.
217 **
218 ** CUnit::Removed
219 **
220 ** This flag means the unit is not active on map. This flag
221 ** have workers set if they are inside a building, units that are
222 ** on board of a transporter.
223 **
224 ** CUnit::Selected
225 **
226 ** Unit is selected. (So you can give it orders)
227 **
228 ** CUnit::Constructed
229 ** Set when a building is under construction, and still using the
230 ** generic building animation.
231 **
232 ** CUnit::SeenConstructed
233 ** Last seen state of construction. Used to draw correct building
234 ** frame. See CUnit::Constructed for more information.
235 **
236 ** CUnit::SeenState
237 ** The Seen State of the building.
238 ** 01 The building in being built when last seen.
239 ** 10 The building was been upgraded when last seen.
240 **
241 ** CUnit::Boarded
242 **
243 ** This is 1 if the unit is on board a transporter.
244 **
245 ** CUnit::Kills
246 **
247 ** How many units have been killed by the unit.
248 **
249 ** CUnit::GroupId
250 **
251 ** Number of the group to that the unit belongs. This is the main
252 ** group showed on map, a unit can belong to many groups.
253 **
254 ** CUnit::LastGroup
255 **
256 ** Automatic group number, to reselect the same units. When the
257 ** user selects more than one unit all units is given the next
258 ** same number. (Used for ALT-CLICK)
259 **
260 ** CUnit::Value
261 **
262 ** This values hold the amount of resources in a resource or in
263 ** in a harvester.
264 **
265 ** CUnit::SubAction
266 **
267 ** This is an action private variable, it is zero on the first
268 ** entry of an action. Must be set to zero, if an action finishes.
269 ** It should only be used inside of actions.
270 **
271 ** CUnit::Wait
272 **
273 ** The unit is forced too wait for that many cycles. Be carefull,
274 ** setting this to 0 will lock the unit.
275 **
276 ** CUnit::State
277 **
278 ** Animation state, currently position in the animation script.
279 ** 0 if an animation has just started, it should only be changed
280 ** inside of actions.
281 **
282 ** CUnit::Reset
283 **
284 **
285 ** CUnit::Blink
286 **
287 **
288 ** CUnit::Moving
289 **
290 **
291 ** CUnit::RescuedFrom
292 **
293 ** Pointer to the original owner of a unit. It will be NULL if
294 ** the unit was not rescued.
295 **
296 ** CUnit::OrderCount
297 **
298 ** The number of the orders unit to process. An unit has atleast
299 ** one order. CUnit::OrderCount should be a number at least 1.
300 ** The orders are in CUnit::Orders[].
301 **
302 ** CUnit::OrderFlush
303 **
304 ** A flag, which tells the unit to stop with the current order
305 ** and immediately start with the next order.
306 **
307 ** CUnit::TotalOrders
308 **
309 ** The number of Orders allocated for this unit to use.
310 ** Default is 4, but is dynamically updated if more orders are
311 ** given.
312 **
313 ** CUnit::Orders
314 **
315 ** Contains all orders of the unit. Slot 0 is always used.
316 **
317 ** CUnit::SavedOrder
318 **
319 ** This order is executed, if the current order is finished.
320 ** This is used for attacking units, to return to the old
321 ** place or for patrolling units to return to patrol after
322 ** killing some enemies. Any new order given to the unit,
323 ** clears this saved order.
324 **
325 ** CUnit::NewOrder
326 **
327 ** This field is only used by buildings and this order is
328 ** assigned to any by this building new trained unit.
329 ** This is can be used to set the exit or gathering point of a
330 ** building.
331 **
332 ** CUnit::Data
333 **
334 ** @todo continue documentation
335 **
336 ** CUnit::Goal
337 **
338 ** Generic goal pointer. Used by teleporters to point to circle of power.
339 **
340 */
341
342 /*----------------------------------------------------------------------------
343 -- Includes
344 ----------------------------------------------------------------------------*/
345
346 #include <vector>
347 #include "SDL.h"
348 #include "upgrade_structs.h"
349
350 /*----------------------------------------------------------------------------
351 -- Declarations
352 ----------------------------------------------------------------------------*/
353
354 class CUnit;
355 class CUnitType;
356 class CUnitStats;
357 class CPlayer;
358 class SpellType;
359 class CUnitColors;
360 class CConstructionFrame;
361 class CVariable;
362 class CBuildRestrictionOnTop;
363 class CFile;
364 struct lua_State;
365 class CViewport;
366 class CAnimation;
367
368 /// Called whenever the selected unit was updated
369 extern void SelectedUnitChanged(void);
370
371 /**
372 ** Unit references over network, or for memory saving.
373 */
374 typedef unsigned short UnitRef;
375
376 /**
377 ** All possible unit actions.
378 **
379 ** @note Always change the table ::HandleActionTable
380 **
381 ** @see HandleActionTable
382 */
383 typedef enum _unit_action_ {
384 UnitActionNone, /// No valid action
385
386 UnitActionStill, /// unit stand still, does nothing
387 UnitActionStandGround, /// unit stands ground
388 UnitActionFollow, /// unit follows units
389 UnitActionMove, /// unit moves to position/unit
390 UnitActionAttack, /// unit attacks position/unit
391 UnitActionAttackGround, /// unit attacks ground
392 UnitActionDie, /// unit dies
393
394 UnitActionSpellCast, /// unit casts spell
395
396 UnitActionTrain, /// building is training
397 UnitActionBuilt, /// building is under construction
398
399 // Compound actions
400 UnitActionBoard, /// unit entering transporter
401 UnitActionUnload, /// unit leaving transporter
402 UnitActionPatrol, /// unit paroling area
403 UnitActionBuild, /// unit builds building
404
405 UnitActionRepair, /// unit repairing
406 UnitActionResource, /// unit harvesting resources
407 } UnitAction;
408
409 /**
410 ** Unit order structure.
411 */
412 class COrder {
413 public:
414 COrder() : Action(UnitActionNone), Range(0), MinRange(0), Width(0),
415 Height(0), Goal(NULL), X(-1), Y(-1), Type(NULL)
416 {
417 memset(&Arg1, 0, sizeof(Arg1));
418 };
419
420 void Init() {
421 Action = UnitActionNone;
422 Range = 0;
423 MinRange = 0;
424 Width = 0;
425 Height = 0;
426 Assert(!Goal);
427 X = -1; Y = -1;
428 Type = NULL;
429 memset(&Arg1, 0, sizeof(Arg1));
430 };
431
432 unsigned char Action; /// global action
433 int Range; /// How far away
434 unsigned int MinRange; /// How far away minimum
435 unsigned char Width; /// Goal Width (used when Goal is not)
436 unsigned char Height; /// Goal Height (used when Goal is not)
437
438 CUnit *Goal; /// goal of the order (if any)
439 int X; /// or X tile coordinate of destination
440 int Y; /// or Y tile coordinate of destination
441 CUnitType *Type; /// Unit-type argument
442
443 union {
444 struct {
445 int X; /// X position for patroling.
446 int Y; /// Y position for patroling.
447 } Patrol; /// position.
448 SpellType *Spell; /// spell when casting.
449 } Arg1; /// Extra command argument.
450 };
451
452 /**
453 ** Voice groups for a unit
454 */
455 enum UnitVoiceGroup {
456 VoiceSelected, /// If selected
457 VoiceAcknowledging, /// Acknowledge command
458 VoiceReady, /// Command completed
459 VoiceHelpMe, /// If attacked
460 VoiceDying, /// If killed
461 VoiceBuilding, /// only for building under construction
462 VoiceDocking, /// only for transport reaching coast
463 };
464
465 /**
466 ** Unit/Missile headings.
467 ** N
468 ** NW NE
469 ** W E
470 ** SW SE
471 ** S
472 */
473 enum _directions_ {
474 LookingN = 0 * 32, /// Unit looking north
475 LookingNE = 1 * 32, /// Unit looking north east
476 LookingE = 2 * 32, /// Unit looking east
477 LookingSE = 3 * 32, /// Unit looking south east
478 LookingS = 4 * 32, /// Unit looking south
479 LookingSW = 5 * 32, /// Unit looking south west
480 LookingW = 6 * 32, /// Unit looking west
481 LookingNW = 7 * 32, /// Unit looking north west
482 };
483
484 #define NextDirection 32 /// Next direction N->NE->E...
485 #define UnitNotSeen 0x7fffffff /// Unit not seen, used by CUnit::SeenFrame
486
487 /// The big unit structure
488 class CUnit {
489 public:
490 CUnit() { Init(); }
491
492 void Init() {
493 Refs = 0;
494 Slot = 0;
495 UnitSlot = NULL;
496 PlayerSlot = NULL;
497 Next = NULL;
498 InsideCount = 0;
499 BoardCount = 0;
500 UnitInside = NULL;
501 Container = NULL;
502 NextContained = NULL;
503 PrevContained = NULL;
504 X = 0;
505 Y = 0;
506 Type = NULL;
507 Player = NULL;
508 Stats = NULL;
509 CurrentSightRange = 0;
510 Colors = NULL;
511 IX = 0;
512 IY = 0;
513 Frame = 0;
514 Direction = 0;
515 Attacked = 0;
516 Burning = 0;
517 Destroyed = 0;
518 Removed = 0;
519 Selected = 0;
520 TeamSelected = 0;
521 Constructed = 0;
522 Boarded = 0;
523 RescuedFrom = NULL;
524 memset(VisCount, 0, sizeof(VisCount));
525 memset(&Seen, 0, sizeof(Seen));
526 Variable = NULL;
527 TTL = 0;
528 GroupId = 0;
529 LastGroup = 0;
530 memset(ResourcesHeld, 0, sizeof(ResourcesHeld));
531 ProductionEfficiency = 100;
532 SubAction = 0;
533 Wait = 0;
534 State = 0;
535 Blink = 0;
536 Moving = 0;
537 ReCast = 0;
538 memset(&Anim, 0, sizeof(Anim));
539 OrderCount = 0;
540 OrderFlush = 0;
541 Orders.clear();
542 SavedOrder.Init();
543 NewOrder.Init();
544 AutoCastSpell = NULL;
545 AutoRepair = 0;
546 memset(&Data, 0, sizeof(Data));
547 Goal = NULL;
548 }
549
550 // @note int is faster than shorts
551 unsigned long Refs; /// Reference counter
552 int Slot; /// Assigned slot number
553 CUnit **UnitSlot; /// Slot pointer of Units
554 CUnit **PlayerSlot; /// Slot pointer of Player->Units
555
556 CUnit *Next; /// Generic link pointer (on map)
557
558 int InsideCount; /// Number of units inside.
559 int BoardCount; /// Number of units transported inside.
560 CUnit *UnitInside; /// Pointer to one of the units inside.
561 CUnit *Container; /// Pointer to the unit containing it (or 0)
562 CUnit *NextContained; /// Next unit in the container.
563 CUnit *PrevContained; /// Previous unit in the container.
564
565 int X; /// Map position X
566 int Y; /// Map position Y
567
568 CUnitType *Type; /// Pointer to unit-type (peon,...)
569 CPlayer *Player; /// Owner of this unit
570 CUnitStats *Stats; /// Current unit stats
571 int CurrentSightRange; /// Unit's Current Sight Range
572
573 // DISPLAY:
574 CUnitColors *Colors; /// Player colors
575 signed char IX; /// X image displacement to map position
576 signed char IY; /// Y image displacement to map position
577 int Frame; /// Image frame: <0 is mirrored
578
579 unsigned Direction : 8; /// angle (0-255) unit looking
580
581 unsigned long Attacked; /// gamecycle unit was last attacked
582
583 unsigned Burning : 1; /// unit is burning
584 unsigned Destroyed : 1; /// unit is destroyed pending reference
585 unsigned Removed : 1; /// unit is removed (not on map)
586 unsigned Selected : 1; /// unit is selected
587
588 unsigned Constructed : 1; /// Unit is in construction
589 unsigned Boarded : 1; /// Unit is on board a transporter.
590 unsigned TeamSelected; /// unit is selected by a team member.
591 CPlayer *RescuedFrom; /// The original owner of a rescued unit.
592 /// NULL if the unit was not rescued.
593 /* Seen stuff. */
594 int VisCount[PlayerMax]; /// Unit visibility counts
595 struct _unit_seen_ {
596 unsigned ByPlayer : PlayerMax; /// Track unit seen by player
597 int Frame; /// last seen frame/stage of buildings
598 CUnitType *Type; /// Pointer to last seen unit-type
599 int X; /// Last unit->X Seen
600 int Y; /// Last unit->Y Seen
601 signed char IX; /// Seen X image displacement to map position
602 signed char IY; /// seen Y image displacement to map position
603 unsigned Constructed : 1; /// Unit seen construction
604 unsigned State : 3; /// Unit seen build/upgrade state
605 unsigned Destroyed : PlayerMax; /// Unit seen destroyed or not
606 CConstructionFrame *CFrame; /// Seen construction frame
607 } Seen;
608
609 CVariable *Variable; /// array of User Defined variables.
610
611 unsigned long TTL; /// time to live
612
613 int GroupId; /// unit belongs to this group id
614 int LastGroup; /// unit belongs to this last group
615
616 int ResourcesHeld[MaxCosts]; /// Resources held by a unit
617 unsigned ProductionEfficiency : 8; /// Production efficiency
618
619 unsigned SubAction : 8; /// sub-action of unit
620 unsigned Wait; /// action counter
621 unsigned State : 8; /// action state
622 unsigned Blink : 3; /// Let selection rectangle blink
623 unsigned Moving : 1; /// The unit is moving
624 unsigned ReCast : 1; /// Recast again next cycle
625
626 struct _unit_anim_ {
627 const CAnimation *Anim; /// Anim
628 const CAnimation *CurrAnim; /// CurrAnim
629 int Wait; /// Wait
630 int Unbreakable; /// Unbreakable
631 } Anim;
632
633 char OrderCount; /// how many orders in queue
634 char OrderFlush; /// cancel current order, take next
635 std::vector<COrder *> Orders; /// orders to process
636 COrder SavedOrder; /// order to continue after current
637 COrder NewOrder; /// order for new trained units
638 char *AutoCastSpell; /// spells to auto cast
639 unsigned AutoRepair : 1; /// True if unit tries to repair on still action.
640
641 union _order_data_ {
642 struct _order_move_ {
643 char Fast; /// Flag fast move (one step)
644 char Length; /// stored path length
645 #define MAX_PATH_LENGTH 28 /// max length of precalculated path
646 char Path[MAX_PATH_LENGTH]; /// directions of stored path
647 } Move; /// ActionMove,...
648 struct _order_built_ {
649 int Progress; /// Progress counter, in 1/100 cycles.
650 int Cancel; /// Cancel construction
651 CConstructionFrame *Frame; /// Construction frame
652 } Built; /// ActionBuilt,...
653 struct _order_harvest_ {
654 int CurrentProduction[MaxCosts];
655 } Harvest; /// Harvest
656 struct _order_train_ {
657 int Ticks; /// Ticks to complete
658 } Train; /// Train units action
659 struct _order_repair_ {
660 int Progress; /// Progress counter
661 } Repair; /// Repair
662 } Data; /// Storage room for different commands
663
664 CUnit *Goal; /// Generic goal pointer
665
666
667 inline bool IsIdle() const {
668 return Orders[0]->Action == UnitActionStill && OrderCount == 1;
669 }
670
671 inline void ClearAction() {
672 Orders[0]->Action = UnitActionStill;
673 SubAction = 0;
674 if (Selected) {
675 SelectedUnitChanged();
676 }
677 }
678
679 /// Increase a unit's reference count
680 void RefsIncrease();
681 /// Decrease a unit's reference count
682 void RefsDecrease();
683
684 /// Initialize unit structure with default values
685 void Init(CUnitType *type);
686 /// Assign unit to player
687 void AssignToPlayer(CPlayer *player);
688
689 /// Draw a single unit
690 void Draw() const;
691 /// Place a unit on map
692 void Place(int x, int y);
693
694 /// Move unit to tile(x, y). (Do special stuff : vision, cachelist, pathfinding)
695 void MoveToXY(int x, int y);
696 /// Add a unit inside a container. Only deal with list stuff.
697 void AddInContainer(CUnit *host);
698 /// Change owner of unit
699 void ChangeOwner(CPlayer *newplayer);
700
701 /// Remove unit from map/groups/...
702 void Remove(CUnit *host);
703 /// Release a unit
704 void Release();
705
706 /// Returns true, if unit is directly seen by an allied unit.
707 bool IsVisible(const CPlayer *player) const;
708 /// Returns true, if unit is visible as a goal.
709 bool IsVisibleAsGoal(const CPlayer *player) const;
710 /// Returns true, if the unit is alive and on the map.
711 bool IsAliveOnMap() const;
712 /// Returns true, if unit is Visible for game logic on the map.
713 bool IsVisibleOnMap(const CPlayer *player) const;
714 /// Returns true if unit is visible on minimap. Only for ThisPlayer.
715 bool IsVisibleOnMinimap() const;
716 /// Returns true if unit is visible in an viewport. Only for ThisPlayer.
717 bool IsVisibleInViewport(const CViewport *vp) const;
718 /// Returns true, if unit is visible on current map view (any viewport).
719 bool IsVisibleOnScreen() const;
720
721 /// @todo more docu
722 void GetMapArea(int *sx, int *sy, int *ex, int *ey) const;
723
724 bool IsEnemy(const CPlayer *x) const;
725 bool IsEnemy(const CUnit *x) const;
726 bool IsAllied(const CPlayer *x) const;
727 bool IsAllied(const CUnit *x) const;
728 bool IsSharedVision(const CPlayer *x) const;
729 bool IsSharedVision(const CUnit *x) const;
730 bool IsBothSharedVision(const CPlayer *x) const;
731 bool IsBothSharedVision(const CUnit *x) const;
732 bool IsTeamed(const CPlayer *x) const;
733 bool IsTeamed(const CUnit *x) const;
734
735 bool IsUnusable() const;
736 };
737
738 #define NoUnitP (CUnit *)0 /// return value: for no unit found
739 #define InfiniteDistance INT_MAX /// the distance is unreachable
740
741 #define FlushCommands 1 /// Flush commands in queue
742
743 #define MAX_UNIT_SLOTS 65535 /// Maximal number of used slots
744
745 /**
746 ** Returns unit number (unique to this unit)
747 */
748 #define UnitNumber(unit) ((unit)->Slot)
749
750 /**
751 ** How many groups supported
752 */
753 #define NUM_GROUPS 10
754
755 /**
756 ** User preference.
757 */
758 class CPreference {
759 public:
760 CPreference() : ShowSightRange(false), ShowReactionRange(false),
761 ShowAttackRange(false), ShowOrders(0) {};
762
763 bool ShowSightRange; /// Show right range.
764 bool ShowReactionRange; /// Show reaction range.
765 bool ShowAttackRange; /// Show attack range.
766 int ShowOrders; /// How many second show orders of unit on map.
767 };
768
769 extern CPreference Preference;
770
771 /*----------------------------------------------------------------------------
772 -- Variables
773 ----------------------------------------------------------------------------*/
774
775 extern CUnit *Units[MAX_UNIT_SLOTS]; /// Units used
776 extern int NumUnits; /// Number of units used
777
778 // in unit_draw.cpp
779 /// @todo could be moved into the user interface ?
780 extern unsigned long ShowOrdersCount; /// Show orders for some time
781 extern bool EnableBuildingCapture; /// Config: building capture enabled
782 extern const CViewport *CurrentViewport;/// CurrentViewport
783 extern void DrawUnitSelection(const CUnit *);
784 extern void DrawSelection(Uint32 color, int x1, int y1, int x2, int y2);
785 extern int MaxSelectable; /// How many units could be selected
786
787 extern CUnit **Selected; /// currently selected units
788 extern CUnit **TeamSelected[PlayerMax]; /// teams currently selected units
789 extern int NumSelected; /// how many units selected
790 extern int TeamNumSelected[PlayerMax]; /// Number of Units a team member has selected
791
792 /*----------------------------------------------------------------------------
793 -- Functions
794 ----------------------------------------------------------------------------*/
795
796 /// Mark the field with the FieldFlags.
797 void MarkUnitFieldFlags(const CUnit *unit);
798 /// Unmark the field with the FieldFlags.
799 void UnmarkUnitFieldFlags(const CUnit *unit);
800 /// Update unit->CurrentSightRange.
801 void UpdateUnitSightRange(CUnit *unit);
802 /// Create a new unit
803 extern CUnit *MakeUnit(CUnitType *type, CPlayer *player);
804 /// Create a new unit and place on map
805 extern CUnit *MakeUnitAndPlace(int x, int y, CUnitType *type, CPlayer *player);
806 /// Handle the loss of a unit (food,...)
807 extern void UnitLost(CUnit *unit);
808 /// Remove the Orders of a Unit
809 extern void UnitClearOrders(CUnit *unit);
810 /// @todo more docu
811 extern void UpdateForNewUnit(const CUnit *unit, int upgrade);
812 /// @todo more docu
813 extern void NearestOfUnit(const CUnit *unit, int tx, int ty, int *dx, int *dy);
814
815 /// Call when an Unit goes under fog.
816 extern void UnitGoesUnderFog(CUnit *unit, const CPlayer *player);
817 /// Call when an Unit goes out of fog.
818 extern void UnitGoesOutOfFog(CUnit *unit, const CPlayer *player);
819 /// Marks a unit as seen
820 extern void UnitsOnTileMarkSeen(const CPlayer *player, int x, int y);
821 /// Unmarks a unit as seen
822 extern void UnitsOnTileUnmarkSeen(const CPlayer *player, int x, int y);
823 /// Does a recount for VisCount
824 extern void UnitCountSeen(CUnit *unit);
825
826 /// Check for rescue each second
827 extern void RescueUnits(void);
828
829 /// Convert direction (dx,dy) to heading (0-255)
830 extern int DirectionToHeading(int, int);
831 /// Update frame from heading
832 extern void UnitUpdateHeading(CUnit *unit);
833 /// Heading and frame from delta direction x,y
834 extern void UnitHeadingFromDeltaXY(CUnit *unit, int x, int y);
835
836 /// @todo more docu
837 extern void DropOutOnSide(CUnit *unit, int heading, int addx, int addy);
838 /// @todo more docu
839 extern void DropOutNearest(CUnit *unit, int x, int y, int addx, int addy);
840 /// Drop out all units in the unit
841 extern void DropOutAll(const CUnit *unit);
842
843 /// Return the rule used to build this building.
844 extern CBuildRestrictionOnTop *OnTopDetails(const CUnit *unit, const CUnitType *parent);
845 /// @todo more docu
846 extern CUnit *CanBuildHere(const CUnit *unit, const CUnitType *type, int x, int y);
847 /// @todo more docu
848 extern bool CanBuildOn(int x, int y, int mask);
849 /// FIXME: more docu
850 extern CUnit *CanBuildUnitType(const CUnit *unit, const CUnitType *type, int x, int y, int real);
851
852 /// Holds resources
853 extern bool UnitHoldsResources(const CUnit *unit);
854 /// Find resource
855 extern CUnit *UnitFindResource(const CUnit *unit, int x, int y, int range, int resource = -1);
856 /// Find the next idle worker
857 extern CUnit *FindIdleWorker(const CPlayer *player);
858
859 /// @todo more docu
860 extern CUnit *UnitOnScreen(int x, int y);
861 /// Check if a unit should be removed from UnitsConsumingResources
862 extern void UnitRemoveConsumingResources(CUnit *unit);
863
864 /// Let a unit die
865 extern void LetUnitDie(CUnit *unit);
866 /// Destory all units inside another unit
867 extern void DestroyAllInside(CUnit *source);
868 /// Hit unit with damage, if destroyed give attacker the points
869 extern void HitUnit(CUnit *attacker, CUnit *target, int damage);
870
871 /// Returns the map distance between two points
872 extern int MapDistance(int x1, int y1, int x2, int y2);
873 /// Returns the map distance between two points with unit-type
874 extern int MapDistanceToType(int x1, int y1, const CUnitType *type, int x2, int y2);
875 /// Returns the map distance to unit
876 extern int MapDistanceToUnit(int x, int y, const CUnit *dest);
877 /// Returns the map diestance between to unittype as locations
878 extern int MapDistanceBetweenTypes(const CUnitType *src, int x1, int y1, const CUnitType *dst, int x2, int y2);
879 /// Returns the map distance between two units
880 extern int MapDistanceBetweenUnits(const CUnit *src, const CUnit *dst);
881
882 /// Calculate the distance from current view point to coordinate
883 extern int ViewPointDistance(int x, int y);
884 /// Calculate the distance from current view point to unit
885 extern int ViewPointDistanceToUnit(const CUnit *dest);
886
887 /// Can this unit-type attack the other (destination)
888 extern int CanTarget(const CUnitType *type, const CUnitType *dest);
889 /// Can transporter transport the other unit
890 extern int CanTransport(const CUnit *transporter, const CUnit *unit);
891
892 /// Check if unit can move.
893 extern bool CanMove(const CUnit *unit);
894
895 /// Generate a unit reference, a printable unique string for unit
896 extern std::string UnitReference(const CUnit *unit);
897 /// Save an order
898 extern void SaveOrder(const COrder *order, CFile *file);
899 /// save unit-structure
900 extern void SaveUnit(const CUnit *unit, CFile *file);
901 /// save all units
902 extern void SaveUnits(CFile *file);
903
904 /// Initialize unit module
905 extern void InitUnits(void);
906 /// Clean unit module
907 extern void CleanUnits(void);
908
909 // in unit_draw.cpp
910 /// Register CCL decorations features
911 extern void DecorationCclRegister(void);
912 /// Load the decorations (health,charge) of units
913 extern void LoadDecorations(void);
914 /// Clean the decorations (health,charge) of units
915 extern void CleanDecorations(void);
916
917 /// Draw unit's shadow
918 extern void DrawShadow(const CUnit *unit, const CUnitType *type,
919 int frame, int x, int y);
920 /// Draw all units visible on map in viewport
921 extern int FindAndSortUnits(const CViewport *vp, CUnit **table, int tablesize);
922 /// Show a unit's orders.
923 extern void ShowOrder(const CUnit *unit);
924
925 // in unit_find.cpp
926 /// Find all units of this type
927 extern int FindUnitsByType(const CUnitType *type, CUnit **table, int tablesize);
928 /// Find all units of this type of the player
929 extern int FindPlayerUnitsByType(const CPlayer *, const CUnitType *, CUnit **, int);
930 /// Return any unit on that map tile
931 extern CUnit *UnitOnMapTile(int tx, int ty, unsigned type = (unsigned)-1);
932 /// Return possible attack target on that map area
933 extern CUnit *TargetOnMap(const CUnit *unit, int x1, int y1, int x2, int y2);
934
935 /// Return resource, if on map tile
936 extern CUnit *ResourceOnMap(int tx, int ty, int resource = -1);
937
938 /// Find best enemy in numeric range to attack
939 extern CUnit *AttackUnitsInDistance(const CUnit *unit, int range);
940 /// Find best enemy in attack range to attack
941 extern CUnit *AttackUnitsInRange(const CUnit *unit);
942 /// Find best enemy in reaction range to attack
943 extern CUnit *AttackUnitsInReactRange(const CUnit *unit);
944
945 // in groups.cpp
946 /// Initialize data structures for groups
947 extern void InitGroups(void);
948 /// Save groups
949 extern void SaveGroups(CFile *file);
950 /// Cleanup groups
951 extern void CleanGroups(void);
952
953 // 2 functions to conseal the groups internal data structures...
954 /// Get the number of units in a particular group
955 extern int GetNumberUnitsOfGroup(int num);
956 /// Get the array of units of a particular group
957 extern CUnit **GetUnitsOfGroup(int num);
958
959 /// Remove all units from a group
960 extern void ClearGroup(int num);
961 /// Add the array of units to the group
962 extern void AddToGroup(CUnit **units, int nunits, int num);
963 /// Set the contents of a particular group with an array of units
964 extern void SetGroup(CUnit **units, int nunits, int num);
965 /// Remove a unit from a group
966 extern void RemoveUnitFromGroups(CUnit *unit);
967 /// Register CCL group features
968 extern void GroupCclRegister(void);
969
970 // in selection.cpp
971 /// Check if unit is the currently only selected
972 #define IsOnlySelected(unit) (NumSelected == 1 && Selected[0] == (unit))
973
974 /// Save selection to restore after.
975 extern void SaveSelection(void);
976 /// Restore selection.
977 extern void RestoreSelection(void);
978 /// Clear current selection
979 extern void UnSelectAll(void);
980 /// Select group as selection
981 extern void ChangeSelectedUnits(CUnit **units, int num_units);
982 /// Changed TeamUnit Selection
983 extern void ChangeTeamSelectedUnits(CPlayer *player, CUnit **units, int adjust, int count);
984 /// Add a unit to selection
985 extern int SelectUnit(CUnit *unit);
986 /// Select one unit as selection
987 extern void SelectSingleUnit(CUnit *unit);
988 /// Remove a unit from selection
989 extern void UnSelectUnit(CUnit *unit);
990 /// Add a unit to selected if not already selected, remove it otherwise
991 extern int ToggleSelectUnit(CUnit *unit);
992 /// Select units from the same type (if selectable by rectangle)
993 extern int SelectUnitsByType(CUnit *base);
994 /// Toggle units from the same type (if selectable by rectangle)
995 extern int ToggleUnitsByType(CUnit *base);
996 /// Select the units belonging to a particular group
997 extern int SelectGroup(int group_number);
998 /// Add the units from the same group as the one in parameter
999 extern int AddGroupFromUnitToSelection(CUnit *unit);
1000 /// Select the units from the same group as the one in parameter
1001 extern int SelectGroupFromUnit(CUnit *unit);
1002 /// Select the units in the selection rectangle
1003 extern int SelectUnitsInRectangle(int tx, int ty, int w, int h);
1004 /// Select ground units in the selection rectangle
1005 extern int SelectGroundUnitsInRectangle(int tx, int ty, int w, int h);
1006 /// Select flying units in the selection rectangle
1007 extern int SelectAirUnitsInRectangle(int tx, int ty, int w, int h);
1008 /// Add the units in the selection rectangle to the current selection
1009 extern int AddSelectedUnitsInRectangle(int tx, int ty, int w, int h);
1010 /// Add ground units in the selection rectangle to the current selection
1011 extern int AddSelectedGroundUnitsInRectangle(int tx, int ty, int w, int h);
1012 /// Add flying units in the selection rectangle to the current selection
1013 extern int AddSelectedAirUnitsInRectangle(int tx, int ty, int w, int h);
1014
1015 /// Init selections
1016 extern void InitSelections(void);
1017 /// Save current selection state
1018 extern void SaveSelections(CFile *file);
1019 /// Clean up selections
1020 extern void CleanSelections(void);
1021 /// Register CCL selection features
1022 extern void SelectionCclRegister(void);
1023
1024 // in script_unit.cpp
1025 /// Parse order
1026 extern void CclParseOrder(lua_State *l, COrder *order);
1027 /// register CCL units features
1028 extern void UnitCclRegister(void);
1029
1030 //@}
1031
1032 #endif // !__UNIT_H__