Debian Codegraph @

engine/game/missile.cpp

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 missile.cpp - The missiles. */
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
29 //@{
30
31 /*----------------------------------------------------------------------------
32 -- Includes
33 ----------------------------------------------------------------------------*/
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <math.h>
39
40
41 #include "stratagus.h"
42
43 #include <vector>
44 #include <string>
45 #include <map>
46
47 #include "video.h"
48 #include "font.h"
49 #include "map.h"
50 #include "unitsound.h"
51 #include "unittype.h"
52 #include "unit_cache.h"
53 #include "player.h"
54 #include "unit.h"
55 #include "missile.h"
56 #include "sound.h"
57 #include "ui.h"
58 #include "iolib.h"
59 #include "particle.h"
60 #include "trigger.h"
61 #include "luacallback.h"
62
63 /*----------------------------------------------------------------------------
64 -- Declarations
65 ----------------------------------------------------------------------------*/
66
67 unsigned int Missile::Count = 0;
68
69 static std::vector<MissileType *>MissileTypes; /// Missile types.
70
71 static std::vector<Missile*> GlobalMissiles; /// all global missiles on map
72 static std::vector<Missile*> LocalMissiles; /// all local missiles on map
73
74 /// lookup table for missile names
75 static std::map<std::string, MissileType *> MissileTypeMap;
76
77 std::vector<BurningBuildingFrame *> BurningBuildingFrames; /// Burning building frames
78
79 /*----------------------------------------------------------------------------
80 -- Functions
81 ----------------------------------------------------------------------------*/
82
83 /**
84 ** Load the graphics for a missile type
85 */
86 void MissileType::LoadMissileSprite()
87 {
88 if (this->G && !this->G->IsLoaded()) {
89 this->G->Load();
90 if (this->Flip) {
91 this->G->Flip();
92 }
93
94 // Correct the number of frames in graphic
95 Assert(this->G->NumFrames >= this->SpriteFrames);
96 this->G->NumFrames = this->SpriteFrames;
97 // FIXME: Don't use NumFrames as number of frames.
98 }
99 }
100
101 /**
102 ** Load the graphics for all missiles types
103 */
104 void LoadMissileSprites(void)
105 {
106 for (std::vector<MissileType*>::iterator i = MissileTypes.begin(); i != MissileTypes.end(); ++i) {
107 (*i)->LoadMissileSprite();
108 }
109 }
110 /**
111 ** Get Missile type by identifier.
112 **
113 ** @param ident Identifier.
114 **
115 ** @return Missile type pointer.
116 */
117 MissileType *MissileTypeByIdent(const std::string &ident)
118 {
119 return MissileTypeMap[ident];
120 }
121
122 /**
123 ** Allocate an empty missile-type slot.
124 **
125 ** @param ident Identifier to identify the slot.
126 **
127 ** @return New allocated (zeroed) missile-type pointer.
128 */
129 MissileType *NewMissileTypeSlot(const std::string &ident)
130 {
131 MissileType *mtype;
132
133 mtype = new MissileType(ident);
134 MissileTypeMap[ident] = mtype;
135 MissileTypes.push_back(mtype);
136 return mtype;
137 }
138
139 /**
140 ** Constructor
141 */
142 Missile::Missile() :
143 SourceX(0), SourceY(0), X(0), Y(0), DX(0), DY(0),
144 Type(NULL), SpriteFrame(0), State(0), AnimWait(0), Wait(0),
145 Delay(0), SourceUnit(NULL), TargetUnit(NULL), Damage(0),
146 TTL(-1), Hidden(0),
147 CurrentStep(0), TotalStep(0),
148 Local(0)
149 {
150 this->Slot = Missile::Count++;
151 }
152
153 /**
154 ** Initialize a new made missile.
155 **
156 ** @param mtype Type pointer of missile.
157 ** @param sx Missile x start point in pixel.
158 ** @param sy Missile y start point in pixel.
159 ** @param dx Missile x destination point in pixel.
160 ** @param dy Missile y destination point in pixel.
161 **
162 ** @return created missile.
163 */
164 Missile *Missile::Init(MissileType *mtype, int sx, int sy, int dx, int dy)
165 {
166 Missile *missile = NULL;
167
168 switch (mtype->Class) {
169 case MissileClassNone :
170 missile = new MissileNone;
171 break;
172 case MissileClassPointToPoint :
173 missile = new MissilePointToPoint;
174 break;
175 case MissileClassPointToPointWithHit :
176 missile = new MissilePointToPointWithHit;
177 break;
178 case MissileClassPointToPointCycleOnce :
179 missile = new MissilePointToPointCycleOnce;
180 break;
181 case MissileClassPointToPointBounce :
182 missile = new MissilePointToPointBounce;
183 break;
184 case MissileClassStay :
185 missile = new MissileStay;
186 break;
187 case MissileClassCycleOnce :
188 missile = new MissileCycleOnce;
189 break;
190 case MissileClassFire :
191 missile = new MissileFire;
192 break;
193 case MissileClassHit :
194 missile = new MissileHit;
195 break;
196 case MissileClassParabolic :
197 missile = new MissileParabolic;
198 break;
199 }
200
201 missile->X = sx - mtype->Width / 2;
202 missile->Y = sy - mtype->Height / 2;
203 missile->DX = dx - mtype->Width / 2;
204 missile->DY = dy - mtype->Height / 2;
205 missile->SourceX = missile->X;
206 missile->SourceY = missile->Y;
207 missile->Type = mtype;
208 missile->Wait = mtype->Sleep;
209 missile->Delay = mtype->StartDelay;
210
211 return missile;
212 }
213
214 /**
215 ** Create a new global missile at (x,y).
216 **
217 ** @param mtype Type pointer of missile.
218 ** @param sx Missile x start point in pixel.
219 ** @param sy Missile y start point in pixel.
220 ** @param dx Missile x destination point in pixel.
221 ** @param dy Missile y destination point in pixel.
222 **
223 ** @return created missile.
224 */
225 Missile *MakeMissile(MissileType *mtype, int sx, int sy, int dx, int dy)
226 {
227 Missile *missile;
228
229 missile = Missile::Init(mtype, sx, sy, dx, dy);
230 GlobalMissiles.push_back(missile);
231 return missile;
232 }
233
234 /**
235 ** Create a new local missile at (x,y).
236 **
237 ** @param mtype Type pointer of missile.
238 ** @param sx Missile x start point in pixel.
239 ** @param sy Missile y start point in pixel.
240 ** @param dx Missile x destination point in pixel.
241 ** @param dy Missile y destination point in pixel.
242 **
243 ** @return created missile.
244 */
245 Missile *MakeLocalMissile(MissileType *mtype, int sx, int sy, int dx, int dy)
246 {
247 Missile *missile;
248
249 missile = Missile::Init(mtype, sx, sy, dx, dy);
250 missile->Local = 1;
251 LocalMissiles.push_back(missile);
252 return missile;
253 }
254
255 /**
256 ** Free a missile.
257 **
258 ** @param missiles Missile pointer.
259 ** @param i Index in missiles of missile to free
260 */
261 static void FreeMissile(std::vector<Missile *> &missiles, size_t i)
262 {
263 Missile *missile;
264 CUnit *unit;
265
266 missile = missiles[i];
267 //
268 // Release all unit references.
269 //
270 if ((unit = missile->SourceUnit)) {
271 unit->RefsDecrease();
272 }
273 if ((unit = missile->TargetUnit)) {
274 unit->RefsDecrease();
275 }
276 for (std::vector<Missile*>::iterator j = missiles.begin(); j != missiles.end(); ++j) {
277 if (*j == missile) {
278 missiles.erase(j);
279 break;
280 }
281 }
282 delete missile;
283 }
284
285 /**
286 ** Calculate damage.
287 **
288 ** @todo NOTE: different targets (big are hit by some missiles better)
289 ** @todo NOTE: lower damage for hidden targets.
290 ** @todo NOTE: lower damage for targets on higher ground.
291 **
292 ** @param attacker Attacker.
293 ** @param goal Goal unit.
294 **
295 ** @return damage inflicted on goal.
296 */
297 static int CalculateDamage(const CUnit *attacker, const CUnit *goal)
298 {
299 int damage;
300 int basic_damage;
301 int piercing_damage;
302
303 basic_damage = attacker->Stats->Variables[BASICDAMAGE_INDEX].Value;
304 piercing_damage = attacker->Stats->Variables[PIERCINGDAMAGE_INDEX].Value;
305
306 damage = std::max(basic_damage - goal->Stats->Variables[ARMOR_INDEX].Value, 1);
307 damage += piercing_damage;
308 damage -= SyncRand() % ((damage + 2) / 2);
309 Assert(damage >= 0);
310
311 return damage;
312 }
313
314 /**
315 ** Fire missile.
316 **
317 ** @param unit Unit that fires the missile.
318 */
319 void FireMissile(CUnit *unit)
320 {
321 int x;
322 int y;
323 int dx;
324 int dy;
325 CUnit *goal;
326 Missile *missile;
327
328 //
329 // Goal dead?
330 //
331 goal = unit->Orders[0]->Goal;
332 if (goal) {
333
334 // Better let the caller/action handle this.
335
336 if (goal->Destroyed) {
337 DebugPrint("destroyed unit\n");
338 return;
339 }
340 if (goal->Removed || goal->Orders[0]->Action == UnitActionDie) {
341 return;
342 }
343
344 // FIXME: Some missile hit the field of the target and all units on it.
345 // FIXME: goal is already dead, but missile could hit others?
346 }
347
348 //
349 // No missile hits immediately!
350 //
351 if (unit->Type->Missile.Missile->Class == MissileClassNone) {
352 // No goal, take target coordinates
353 if (!goal) {
354 DebugPrint("Missile-none hits no unit, shouldn't happen!\n");
355 return;
356 }
357
358 HitUnit(unit, goal, CalculateDamage(unit, goal));
359
360 return;
361 }
362
363 // If Firing from inside a Bunker
364 if (unit->Container) {
365 x = unit->Container->X * TileSizeX + TileSizeX / 2; // missile starts in tile middle
366 y = unit->Container->Y * TileSizeY + TileSizeY / 2;
367 } else {
368 x = unit->X * TileSizeX + TileSizeX / 2; // missile starts in tile middle
369 y = unit->Y * TileSizeY + TileSizeY / 2;
370 }
371
372 if (goal) {
373 Assert(goal->Type); // Target invalid?
374 //
375 // Moved out of attack range?
376 //
377 if (MapDistanceBetweenUnits(unit, goal) < unit->Type->MinAttackRange) {
378 DebugPrint("Missile target too near %d,%d\n" _C_
379 MapDistanceBetweenUnits(unit, goal) _C_ unit->Type->MinAttackRange);
380 // FIXME: do something other?
381 return;
382 }
383 // Fire to nearest point of the unit!
384 // If Firing from inside a Bunker
385 if (unit->Container) {
386 NearestOfUnit(goal, unit->Container->X, unit->Container->Y, &dx, &dy);
387 } else {
388 NearestOfUnit(goal, unit->X, unit->Y, &dx, &dy);
389 }
390 } else {
391 dx = unit->Orders[0]->X;
392 dy = unit->Orders[0]->Y;
393 // FIXME: Can this be too near??
394 }
395
396 // Fire to the tile center of the destination.
397 dx = dx * TileSizeX + TileSizeX / 2;
398 dy = dy * TileSizeY + TileSizeY / 2;
399 missile = MakeMissile(unit->Type->Missile.Missile, x, y, dx, dy);
400 //
401 // Damage of missile
402 //
403 if (goal) {
404 missile->TargetUnit = goal;
405 goal->RefsIncrease();
406 }
407 missile->SourceUnit = unit;
408 unit->RefsIncrease();
409 }
410
411 /**
412 ** Get area of tiles covered by missile
413 **
414 ** @param missile Missile to be checked and set.
415 ** @param sx OUT: Pointer to X of top left corner in map tiles.
416 ** @param sy OUT: Pointer to Y of top left corner in map tiles.
417 ** @param ex OUT: Pointer to X of bottom right corner in map tiles.
418 ** @param ey OUT: Pointer to Y of bottom right corner in map tiles.
419 **
420 ** @return sx,sy,ex,ey defining area in Map
421 */
422 static void GetMissileMapArea(const Missile *missile, int *sx, int *sy,
423 int *ex, int *ey)
424 {
425 #define BoundX(x) std::min(std::max(0, x), Map.Info.MapWidth - 1)
426 #define BoundY(y) std::min(std::max(0, y), Map.Info.MapHeight - 1)
427
428 *sx = BoundX(missile->X / TileSizeX);
429 *sy = BoundY(missile->Y / TileSizeY);
430 *ex = BoundX((missile->X + missile->Type->Width + TileSizeX - 1) / TileSizeX);
431 *ey = BoundY((missile->Y + missile->Type->Height + TileSizeY - 1) / TileSizeY);
432
433 #undef BoundX
434 #undef BoundY
435 }
436
437 /**
438 ** Check missile visibility in a given viewport.
439 **
440 ** @param vp Viewport to be checked.
441 ** @param missile Missile pointer to check if visible.
442 **
443 ** @return Returns true if visible, false otherwise.
444 */
445 static int MissileVisibleInViewport(const CViewport *vp, const Missile *missile)
446 {
447 int min_x;
448 int max_x;
449 int min_y;
450 int max_y;
451
452 GetMissileMapArea(missile, &min_x, &min_y, &max_x, &max_y);
453 if (!vp->AnyMapAreaVisibleInViewport(min_x, min_y, max_x, max_y)) {
454 return 0;
455 }
456
457 for (int x = min_x; x <= max_x; ++x) {
458 for (int y = min_y; y <= max_y; ++y) {
459 if (ReplayRevealMap || Map.IsFieldVisible(ThisPlayer, x, y)) {
460 return 1;
461 }
462 }
463 }
464 return 0;
465 }
466
467 /**
468 ** Draw missile.
469 **
470 ** @param frame Animation frame
471 ** @param x Screen pixel X position
472 ** @param y Screen pixel Y position
473 */
474 void MissileType::DrawMissileType(int frame, int x, int y) const
475 {
476 if (this->Flip) {
477 if (frame < 0) {
478 if (this->Transparency == 50) {
479 this->G->DrawFrameClipTransX(-frame - 1, x, y, 128);
480 } else {
481 this->G->DrawFrameClipX(-frame - 1, x, y);
482 }
483 } else {
484 if (this->Transparency == 50) {
485 this->G->DrawFrameClipTrans(frame, x, y, 128);
486 } else {
487 this->G->DrawFrameClip(frame, x, y);
488 }
489 }
490 } else {
491 int row;
492
493 row = this->NumDirections / 2 + 1;
494 if (frame < 0) {
495 frame = ((-frame - 1) / row) * this->NumDirections + this->NumDirections - (-frame - 1) % row;
496 } else {
497 frame = (frame / row) * this->NumDirections + frame % row;
498 }
499 if (this->Transparency == 50) {
500 this->G->DrawFrameClipTrans(frame, x, y, 128);
501 } else {
502 this->G->DrawFrameClip(frame, x, y);
503 }
504 }
505 }
506
507 /**
508 ** Draw missile.
509 */
510 void Missile::DrawMissile() const
511 {
512 int x;
513 int y;
514 const CViewport *vp;
515
516 Assert(this->Type);
517 Assert(CurrentViewport);
518
519 vp = CurrentViewport;
520 x = this->X - vp->MapX * TileSizeX + vp->X - vp->OffsetX;
521 y = this->Y - vp->MapY * TileSizeY + vp->Y - vp->OffsetY;
522 switch (this->Type->Class) {
523 case MissileClassHit:
524 VideoDrawNumberClip(x, y, GameFont, this->Damage);
525 break;
526 default:
527 this->Type->DrawMissileType(this->SpriteFrame, x, y);
528 break;
529 }
530 }
531
532 /**
533 ** Compare Draw level. Used by qsort.
534 **
535 ** @param v1 adress of a missile pointer.
536 ** @param v2 adress of a missile pointer.
537 **
538 ** @return -1 if v1 < v2, 1 else.
539 */
540 static int MissileDrawLevelCompare(const void *v1, const void *v2)
541 {
542 const Missile *c1;
543 const Missile *c2;
544
545 c1 = *(Missile **)v1;
546 c2 = *(Missile **)v2;
547
548 if (c1->Type->DrawLevel == c2->Type->DrawLevel) {
549 return c1->Slot < c2->Slot ? -1 : 1;
550 } else {
551 return c1->Type->DrawLevel <= c2->Type->DrawLevel ? -1 : 1;
552 }
553 }
554 /**
555 ** Sort visible missiles on map for display.
556 **
557 ** @param vp Viewport pointer.
558 ** @param table OUT : array of missile to display sorted by DrawLevel.
559 ** @param tablesize Size of table array
560 **
561 ** @return number of missiles returned in table
562 */
563 int FindAndSortMissiles(const CViewport *vp, Missile **table, int tablesize)
564 {
565 int nmissiles;
566 std::vector<Missile *>::const_iterator i;
567
568 //
569 // Loop through global missiles, then through locals.
570 //
571 nmissiles = 0;
572 for (i = GlobalMissiles.begin(); i != GlobalMissiles.end() && nmissiles < tablesize; ++i) {
573 if ((*i)->Delay || (*i)->Hidden) {
574 continue; // delayed or hidden -> aren't shown
575 }
576 // Draw only visible missiles
577 if (MissileVisibleInViewport(vp, *i)) {
578 table[nmissiles++] = *i;
579 }
580 }
581
582 for (i = LocalMissiles.begin(); i != LocalMissiles.end() && nmissiles < tablesize; ++i) {
583 if ((*i)->Delay || (*i)->Hidden) {
584 continue; // delayed or hidden -> aren't shown
585 }
586 // Local missile are visible.
587 table[nmissiles++] = *i;
588 }
589 if (nmissiles) {
590 qsort((void *)table, nmissiles, sizeof(Missile *), MissileDrawLevelCompare);
591 }
592 return nmissiles;
593 }
594
595 /**
596 ** Change missile heading from x,y.
597 ** Do not change the animation step.
598 **
599 ** @param missile Missile pointer.
600 ** @param dx Delta in x.
601 ** @param dy Delta in y.
602 ** @internal We have : SpriteFrame / (2 * (Numdirection - 1)) == DirectionToHeading / 256.
603 */
604 static void MissileNewHeadingFromXY(Missile *missile, int dx, int dy)
605 {
606 int dir;
607 int nextdir;
608
609 // If the heading cannot be changed, return right away.
610 if (missile->Type->NumDirections == 1 || (dx == 0 && dy == 0)) {
611 return;
612 }
613
614 // Compute the number of the first frame of the current
615 // animation step, discarding the previous heading.
616 if (missile->SpriteFrame < 0) {
617 missile->SpriteFrame = -missile->SpriteFrame - 1;
618 }
619 missile->SpriteFrame /= missile->Type->NumDirections / 2 + 1;
620 missile->SpriteFrame *= missile->Type->NumDirections / 2 + 1;
621
622 // How many heading units there are per frame.
623 // This assumes NumDirections is a power of 2; otherwise,
624 // nextdir is truncated and dir can get out of range.
625 nextdir = 256 / missile->Type->NumDirections;
626 Assert(nextdir != 0);
627
628 // Compute the frame number relative to the current animation
629 // step, as if flipping were not used. Add nextdir/2 so the
630 // quotient is rounded, not truncated.
631 dir = ((DirectionToHeading(10 * dx, 10 * dy) + nextdir / 2) & 0xFF) / nextdir;
632
633 // Compute the absolute frame number, with both the animation
634 // step and the heading.
635 if (dir <= LookingS / nextdir) { // north->east->south
636 missile->SpriteFrame += dir;
637 } else {
638 missile->SpriteFrame += 256 / nextdir - dir;
639 missile->SpriteFrame = -missile->SpriteFrame - 1;
640 }
641 }
642
643 /**
644 ** Init the move.
645 **
646 ** @param missile missile to initialise for movement.
647 **
648 ** @return 1 if goal is reached, 0 else.
649 */
650 static int MissileInitMove(Missile *missile)
651 {
652 int dx;
653 int dy;
654
655 dx = missile->DX - missile->X;
656 dy = missile->DY - missile->Y;
657 MissileNewHeadingFromXY(missile, dx, dy);
658 if (!(missile->State & 1)) {
659 missile->CurrentStep = 0;
660 missile->TotalStep = 0;
661 if (dx == 0 && dy == 0) {
662 return 1;
663 }
664 // initialize
665 missile->TotalStep = MapDistance(missile->SourceX, missile->SourceY, missile->DX, missile->DY);
666 missile->State++;
667 return 0;
668 }
669 Assert(missile->TotalStep != 0);
670 missile->CurrentStep += missile->Type->Speed;
671 if (missile->CurrentStep >= missile->TotalStep) {
672 missile->X = missile->DX;
673 missile->Y = missile->DY;
674 return 1;
675 }
676 return 0;
677 }
678
679 /**
680 ** Handle point to point missile.
681 **
682 ** @param missile Missile pointer.
683 **
684 ** @return 1 if goal is reached, 0 else.
685 */
686 static int PointToPointMissile(Missile *missile)
687 {
688 int xstep;
689 int ystep;
690 int x;
691 int y;
692
693 if (MissileInitMove(missile) == 1) {
694 return 1;
695 }
696
697 Assert(missile->Type != NULL);
698 Assert(missile->TotalStep != 0);
699 xstep = (missile->DX - missile->SourceX) * 1024 / missile->TotalStep;
700 ystep = (missile->DY - missile->SourceY) * 1024 / missile->TotalStep;
701 missile->X = missile->SourceX + xstep * missile->CurrentStep / 1024;
702 missile->Y = missile->SourceY + ystep * missile->CurrentStep / 1024;
703 if (missile->Type->SmokeMissile && missile->CurrentStep) {
704 x = missile->X + missile->Type->Width / 2;
705 y = missile->Y + missile->Type->Height / 2;
706 MakeMissile(missile->Type->SmokeMissile, x, y, x, y);
707 }
708 return 0;
709 }
710
711 /**
712 ** Calculate parabolic trajectories.
713 **
714 ** @param missile Missile pointer.
715 **
716 ** @return 1 if target is reached, 0 otherwise
717 **
718 ** @todo Find good values for ZprojToX and Y
719 */
720 static int ParabolicMissile(Missile *missile)
721 {
722 int orig_x; // position before moving.
723 int orig_y; // position before moving.
724 int xstep;
725 int ystep;
726 int k; // Coefficient of the parabol.
727 int zprojToX; // Projection of Z axis on axis X.
728 int zprojToY; // Projection of Z axis on axis Y.
729 int z; // should be missile->Z later.
730 int x;
731 int y;
732
733 k = -2048; //-1024; // Should be initialised by an other method (computed with distance...)
734 zprojToX = 4;
735 zprojToY = 1024;
736 if (MissileInitMove(missile) == 1) {
737 return 1;
738 }
739 Assert(missile->Type != NULL);
740 orig_x = missile->X;
741 orig_y = missile->Y;
742 xstep = missile->DX - missile->SourceX;
743 ystep = missile->DY - missile->SourceY;
744 Assert(missile->TotalStep != 0);
745 xstep = xstep * 1000 / missile->TotalStep;
746 ystep = ystep * 1000 / missile->TotalStep;
747 missile->X = missile->SourceX + xstep * missile->CurrentStep / 1000;
748 missile->Y = missile->SourceY + ystep * missile->CurrentStep / 1000;
749 Assert(k != 0);
750 z = missile->CurrentStep * (missile->TotalStep - missile->CurrentStep) / k;
751 // Until Z is used for drawing, modify X and Y.
752 missile->X += z * zprojToX / 64;
753 missile->Y += z * zprojToY / 64;
754 MissileNewHeadingFromXY(missile, missile->X - orig_x, missile->Y - orig_y);
755 if (missile->Type->SmokeMissile && missile->CurrentStep) {
756 x = missile->X + missile->Type->Width / 2;
757 y = missile->Y + missile->Type->Height / 2;
758 MakeMissile(missile->Type->SmokeMissile, x, y, x, y);
759 }
760 return 0;
761 }
762
763 /**
764 ** Missile hits the goal.
765 **
766 ** @param missile Missile hitting the goal.
767 ** @param goal Goal of the missile.
768 ** @param splash Splash damage divisor.
769 */
770 static void MissileHitsGoal(const Missile *missile, CUnit *goal, int splash)
771 {
772 if (!missile->Type->CanHitOwner && goal == missile->SourceUnit) {
773 return;
774 }
775
776 if (goal->Orders[0]->Action != UnitActionDie) {
777 if (missile->Damage) { // direct damage, spells mostly
778 HitUnit(missile->SourceUnit, goal, missile->Damage / splash);
779 } else {
780 Assert(missile->SourceUnit != NULL);
781 HitUnit(missile->SourceUnit, goal,
782 CalculateDamage(missile->SourceUnit, goal) / splash);
783 }
784 }
785 }
786
787 /**
788 ** Work for missile hit.
789 **
790 ** @param missile Missile reaching end-point.
791 */
792 void MissileHit(Missile *missile)
793 {
794 CUnit *goal;
795 int x;
796 int y;
797 CUnit *table[UnitMax];
798 int n;
799 int i;
800 int splash;
801
802 if (missile->Type->ImpactSound.Sound) {
803 PlayMissileSound(missile, missile->Type->ImpactSound.Sound);
804 }
805
806 x = missile->X + missile->Type->Width / 2;
807 y = missile->Y + missile->Type->Height / 2;
808
809 //
810 // The impact generates a new missile.
811 //
812 if (missile->Type->ImpactMissile) {
813 MakeMissile(missile->Type->ImpactMissile, x, y, x, y);
814 }
815 if (missile->Type->ImpactParticle) {
816 missile->Type->ImpactParticle->pushPreamble();
817 missile->Type->ImpactParticle->pushInteger(x);
818 missile->Type->ImpactParticle->pushInteger(y);
819 missile->Type->ImpactParticle->run();
820 }
821
822 if (!missile->SourceUnit) { // no owner - green-cross ...
823 return;
824 }
825
826 x /= TileSizeX;
827 y /= TileSizeY;
828
829 if (x < 0 || y < 0 || x >= Map.Info.MapWidth || y >= Map.Info.MapHeight) {
830 // FIXME: this should handled by caller?
831 DebugPrint("Missile gone outside of map!\n");
832 return; // outside the map.
833 }
834
835 //
836 // Choose correct goal.
837 //
838 if (!missile->Type->Range) {
839 if (missile->TargetUnit) {
840 //
841 // Missiles without range only hits the goal always.
842 //
843 goal = missile->TargetUnit;
844 if (goal->Destroyed) { // Destroyed
845 goal->RefsDecrease();
846 missile->TargetUnit = NoUnitP;
847 return;
848 }
849 MissileHitsGoal(missile, goal, 1);
850 return;
851 }
852 return;
853 }
854
855 //
856 // Hits all units in range.
857 //
858 i = missile->Type->Range;
859 n = UnitCache.Select(x - i + 1, y - i + 1, x + i, y + i, table, UnitMax);
860 Assert(missile->SourceUnit != NULL);
861 for (i = 0; i < n; ++i) {
862 goal = table[i];
863 //
864 // Can the unit attack the this unit-type?
865 // NOTE: perhaps this should be come a property of the missile.
866 //
867 if (CanTarget(missile->SourceUnit->Type, goal->Type)) {
868 splash = MapDistanceToUnit(x, y, goal);
869 if (splash) {
870 splash *= missile->Type->SplashFactor;
871 } else {
872 splash = 1;
873 }
874 MissileHitsGoal(missile, goal, splash);
875 }
876 }
877 }
878
879 /**
880 ** Pass to the next frame for animation.
881 **
882 ** @param missile missile to animate.
883 ** @param sign 1 for next frame, -1 for previous frame.
884 ** @param longAnimation 1 if Frame is conditionned by covered distance, 0 else.
885 **
886 ** @return 1 if animation is finished, 0 else.
887 */
888 static int NextMissileFrame(Missile *missile, char sign, char longAnimation)
889 {
890 int neg; // True for mirroring sprite.
891 int animationIsFinished; // returned value.
892 int numDirections; // Number of direction of the missile.
893
894 //
895 // Animate missile, cycle through frames
896 //
897 neg = 0;
898 animationIsFinished = 0;
899 numDirections = missile->Type->NumDirections / 2 + 1;
900 if (missile->SpriteFrame < 0) {
901 neg = 1;
902 missile->SpriteFrame = -missile->SpriteFrame - 1;
903 }
904 if (longAnimation) {
905 int totalf; // Total number of frame (for one direction).
906 int df; // Current frame (for one direction).
907 int totalx; // Total distance to cover.
908 int dx; // Covered distance.
909
910 totalx = MapDistance(missile->DX, missile->DY, missile->SourceX, missile->SourceY);
911 dx = MapDistance(missile->X, missile->Y, missile->SourceX, missile->SourceY);
912 totalf = missile->Type->SpriteFrames / numDirections;
913 df = missile->SpriteFrame / numDirections;
914 if ((sign == 1 && dx * totalf <= df * totalx) ||
915 (sign == -1 && dx * totalf > df * totalx)) {
916 return animationIsFinished;
917 }
918 }
919 missile->SpriteFrame += sign * numDirections;
920 if (sign > 0) {
921 if (missile->SpriteFrame >= missile->Type->SpriteFrames) {
922 missile->SpriteFrame -= missile->Type->SpriteFrames;
923 animationIsFinished = 1;
924 }
925 } else {
926 if (missile->SpriteFrame < 0) {
927 missile->SpriteFrame += missile->Type->SpriteFrames;
928 animationIsFinished = 1;
929 }
930 }
931 if (neg) {
932 missile->SpriteFrame = -missile->SpriteFrame - 1;
933 }
934
935 return animationIsFinished;
936 }
937
938 /**
939 ** Pass the next frame of the animation.
940 ** This animation goes from start to finish ONCE on the way
941 **
942 ** @param missile Missile pointer.
943 */
944 static void NextMissileFrameCycle(Missile *missile)
945 {
946 int neg;
947 int totalx;
948 int dx;
949 int f;
950
951 neg = 0;
952 if (missile->SpriteFrame < 0) {
953 neg = 1;
954 missile->SpriteFrame = -missile->SpriteFrame - 1;
955 }
956 totalx = abs(missile->DX - missile->SourceX);
957 dx = abs(missile->X - missile->SourceX);
958 f = missile->Type->SpriteFrames / (missile->Type->NumDirections / 2 + 1);
959 f = 2 * f - 1;
960 for (int i = 1, j = 1; i <= f; ++i) {
961 if (dx * f / i < totalx) {
962 if ((i - 1) * 2 < f) {
963 j = i - 1;
964 } else {
965 j = f - i;
966 }
967 missile->SpriteFrame = missile->SpriteFrame % (missile->Type->NumDirections / 2 + 1) +
968 j * (missile->Type->NumDirections / 2 + 1);
969 break;
970 }
971 }
972 if (neg) {
973 missile->SpriteFrame = -missile->SpriteFrame - 1;
974 }
975 }
976
977 /**
978 ** Handle all missile actions of global/local missiles.
979 **
980 ** @param missiles Table of missiles.
981 */
982 static void MissilesActionLoop(std::vector<Missile *> &missiles)
983 {
984 //
985 // NOTE: missiles[??] could be modified!!! Yes (freed)
986 //
987 for (size_t i = 0; i != missiles.size(); ) {
988
989 if (missiles[i]->Delay) {
990 missiles[i]->Delay--;
991 ++i;
992 continue; // delay start of missile
993 }
994
995 if (missiles[i]->TTL > 0) {
996 missiles[i]->TTL--; // overall time to live if specified
997 }
998
999 if (!missiles[i]->TTL) {
1000 FreeMissile(missiles, i);
1001 continue;
1002 }
1003
1004 Assert(missiles[i]->Wait);
1005 if (--missiles[i]->Wait) { // wait until time is over
1006 ++i;
1007 continue;
1008 }
1009
1010 missiles[i]->Action();
1011
1012 if (!missiles[i]->TTL) {
1013 FreeMissile(missiles, i);
1014 continue;
1015 }
1016 ++i;
1017 }
1018 }
1019
1020 /**
1021 ** Handle all missile actions.
1022 */
1023 void MissileActions(void)
1024 {
1025 MissilesActionLoop(GlobalMissiles);
1026 MissilesActionLoop(LocalMissiles);
1027 }
1028
1029 /**
1030 ** Calculate distance from view-point to missle.
1031 **
1032 ** @param missile Missile pointer for distance.
1033 **
1034 ** @return the computed value.
1035 */
1036 int ViewPointDistanceToMissile(const Missile *missile)
1037 {
1038 int x = (missile->X + missile->Type->Width / 2) / TileSizeX;
1039 int y = (missile->Y + missile->Type->Height / 2) / TileSizeY; // pixel -> tile
1040
1041 return ViewPointDistance(x, y);
1042 }
1043
1044 /**
1045 ** Get the burning building missile based on hp percent.
1046 **
1047 ** @param percent HP percent
1048 **
1049 ** @return the missile used for burning.
1050 */
1051 MissileType *MissileBurningBuilding(int percent)
1052 {
1053 for (std::vector<BurningBuildingFrame *>::iterator i = BurningBuildingFrames.begin();
1054 i != BurningBuildingFrames.end(); ++i) {
1055 if (percent > (*i)->Percent) {
1056 return (*i)->Missile;
1057 }
1058 }
1059 return NULL;
1060 }
1061
1062 /**
1063 ** Save the state of a missile to file.
1064 **
1065 ** @param file Output file.
1066 */
1067 void Missile::SaveMissile(CFile *file) const
1068 {
1069 file->printf("Missile(\"type\", \"%s\",", this->Type->Ident.c_str());
1070 file->printf(" \"%s\",", this->Local ? "local" : "global");
1071 file->printf(" \"pos\", {%d, %d}, \"origin-pos\", {%d, %d}, \"goal\", {%d, %d},",
1072 this->X, this->Y, this->SourceX, this->SourceY, this->DX, this->DY);
1073 file->printf("\n \"frame\", %d, \"state\", %d, \"anim-wait\", %d, \"wait\", %d, \"delay\", %d,\n ",
1074 this->SpriteFrame, this->State, this->AnimWait, this->Wait, this->Delay);
1075
1076 if (this->SourceUnit) {
1077 file->printf(" \"source\", \"%s\",", UnitReference(this->SourceUnit).c_str());
1078 }
1079 if (this->TargetUnit) {
1080 file->printf(" \"target\", \"%s\",", UnitReference(this->TargetUnit).c_str());
1081 }
1082
1083 file->printf(" \"damage\", %d,", this->Damage);
1084
1085 file->printf(" \"ttl\", %d,", this->TTL);
1086 if (this->Hidden) {
1087 file->printf(" \"hidden\", ");
1088 }
1089
1090 file->printf(" \"step\", {%d, %d}", this->CurrentStep, this->TotalStep);
1091
1092 // Slot filled in during init
1093
1094 file->printf(")\n");
1095 }
1096
1097 /**
1098 ** Save the state missiles to file.
1099 **
1100 ** @param file Output file.
1101 */
1102 void SaveMissiles(CFile *file)
1103 {
1104 std::vector<Missile *>::const_iterator i;
1105
1106 file->printf("\n--- -----------------------------------------\n");
1107 file->printf("--- MODULE: missiles\n\n");
1108
1109 for (i = GlobalMissiles.begin(); i != GlobalMissiles.end(); ++i) {
1110 (*i)->SaveMissile(file);
1111 }
1112 for (i = LocalMissiles.begin(); i != LocalMissiles.end(); ++i) {
1113 (*i)->SaveMissile(file);
1114 }
1115 }
1116
1117 /**
1118 ** Initialize missile type.
1119 */
1120 void MissileType::Init(void)
1121 {
1122 //
1123 // Resolve impact missiles and sounds.
1124 //
1125 if (!this->FiredSound.Name.empty()) {
1126 this->FiredSound.Sound = SoundForName(this->FiredSound.Name);
1127 }
1128 if (!this->ImpactSound.Name.empty()) {
1129 this->ImpactSound.Sound = SoundForName(this->ImpactSound.Name);
1130 }
1131 this->ImpactMissile = MissileTypeByIdent(this->ImpactName);
1132 this->SmokeMissile = MissileTypeByIdent(this->SmokeName);
1133 }
1134
1135 /**
1136 ** Initialize missile-types.
1137 */
1138 void InitMissileTypes(void)
1139 {
1140 for (std::vector<MissileType*>::iterator i = MissileTypes.begin(); i != MissileTypes.end(); ++i) {
1141 (*i)->Init();
1142 }
1143 }
1144
1145 /**
1146 ** Constructor.
1147 */
1148 MissileType::MissileType(const std::string &ident) :
1149 Ident(ident), Transparency(0), Width(0), Height(0),
1150 DrawLevel(0), SpriteFrames(0), NumDirections(0),
1151 Flip(false), CanHitOwner(false), FriendlyFire(false),
1152 Class(), NumBounces(0), StartDelay(0), Sleep(0), Speed(0),
1153 Range(0), SplashFactor(0), ImpactMissile(NULL),
1154 SmokeMissile(NULL), ImpactParticle(NULL), G(NULL)
1155 {
1156 };
1157
1158 /**
1159 ** Destructor.
1160 */
1161 MissileType::~MissileType()
1162 {
1163 CGraphic::Free(this->G);
1164 delete ImpactParticle;
1165 }
1166
1167 /**
1168 ** Clean up missile-types.
1169 */
1170 void CleanMissileTypes(void)
1171 {
1172 for (std::vector<MissileType*>::iterator i = MissileTypes.begin(); i != MissileTypes.end(); ++i) {
1173 delete *i;
1174 }
1175 MissileTypes.clear();
1176 MissileTypeMap.clear();
1177 }
1178
1179 /**
1180 ** Initialize missiles.
1181 */
1182 void InitMissiles(void)
1183 {
1184 }
1185
1186 /**
1187 ** Clean up missiles.
1188 */
1189 void CleanMissiles(void)
1190 {
1191 std::vector<Missile*>::const_iterator i;
1192
1193 for (i = GlobalMissiles.begin(); i != GlobalMissiles.end(); ++i) {
1194 delete *i;
1195 }
1196 GlobalMissiles.clear();
1197 for (i = LocalMissiles.begin(); i != LocalMissiles.end(); ++i) {
1198 delete *i;
1199 }
1200 LocalMissiles.clear();
1201 }
1202
1203 void FreeBurningBuildingFrames()
1204 {
1205 for (std::vector<BurningBuildingFrame *>::iterator i = BurningBuildingFrames.begin();
1206 i != BurningBuildingFrames.end(); ++i) {
1207 delete *i;
1208 }
1209 BurningBuildingFrames.clear();
1210 }
1211
1212 /*----------------------------------------------------------------------------
1213 -- Functions (Spells Controllers/Callbacks) TODO: move to another file?
1214 ----------------------------------------------------------------------------*/
1215
1216 // ****************************************************************************
1217 // Actions for the missiles
1218 // ****************************************************************************
1219
1220 /*
1221 ** Missile controllers
1222 **
1223 ** To cancel a missile set it's TTL to 0, it will be handled right after
1224 ** the controller call and missile will be down.
1225 */
1226
1227 /**
1228 ** Missile does nothing
1229 */
1230 void MissileNone::Action()
1231 {
1232 this->Wait = this->Type->Sleep;
1233 // Busy doing nothing.
1234 }
1235
1236 /**
1237 ** Missile flies from x,y to x1,y1 animation on the way
1238 */
1239 void MissilePointToPoint::Action()
1240 {
1241 this->Wait = this->Type->Sleep;
1242 if (PointToPointMissile(this)) {
1243 MissileHit(this);
1244 this->TTL = 0;
1245 } else {
1246 NextMissileFrame(this, 1, 0);
1247 }
1248 }
1249
1250 /**
1251 ** Missile flies from x,y to x1,y1 showing the first frame
1252 ** and then shows a hit animation.
1253 */
1254 void MissilePointToPointWithHit::Action()
1255 {
1256 this->Wait = this->Type->Sleep;
1257 if (PointToPointMissile(this)) {
1258 if (NextMissileFrame(this, 1, 0)) {
1259 MissileHit(this);
1260 this->TTL = 0;
1261 }
1262 }
1263 }
1264
1265 /**
1266 ** Missile flies from x,y to x1,y1 and stays there for a moment
1267 */
1268 void MissilePointToPointCycleOnce::Action()
1269 {
1270 this->Wait = this->Type->Sleep;
1271 if (PointToPointMissile(this)) {
1272 MissileHit(this);
1273 this->TTL = 0;
1274 } else {
1275 NextMissileFrameCycle(this);
1276 }
1277 }
1278
1279 /**
1280 ** Missile don't move, than disappears
1281 */
1282 void MissileStay::Action()
1283 {
1284 this->Wait = this->Type->Sleep;
1285 if (NextMissileFrame(this, 1, 0)) {
1286 MissileHit(this);
1287 this->TTL = 0;
1288 }
1289 }
1290
1291 /**
1292 ** Missile flies from x,y to x1,y1 than bounces NumBounces times
1293 */
1294 void MissilePointToPointBounce::Action()
1295 {
1296 this->Wait = this->Type->Sleep;
1297 if (PointToPointMissile(this)) {
1298 if (this->State < 2 * this->Type->NumBounces - 1 && this->TotalStep) {
1299 int xstep;
1300 int ystep;
1301
1302 xstep = (this->DX - this->SourceX) * 1024 / this->TotalStep;
1303 ystep = (this->DY - this->SourceY) * 1024 / this->TotalStep;
1304 this->DX += xstep * (TileSizeX + TileSizeY) * 3 / 4 / 1024;
1305 this->DY += ystep * (TileSizeX + TileSizeY) * 3 / 4 / 1024;
1306
1307 this->State++; // !(State & 1) to initialise
1308 this->SourceX = this->X;
1309 this->SourceY = this->Y;
1310 PointToPointMissile(this);
1311 //this->State++;
1312 MissileHit(this);
1313 // FIXME: hits to left and right
1314 // FIXME: reduce damage effects on later impacts
1315 } else {
1316 MissileHit(this);
1317 this->TTL = 0;
1318 }
1319 } else {
1320 NextMissileFrame(this, 1, 0);
1321 }
1322 }
1323
1324 /**
1325 ** Missile doesn't move, it will just cycle once and vanish.
1326 ** Used for ui missiles (cross shown when you give and order)
1327 */
1328 void MissileCycleOnce::Action()
1329 {
1330 this->Wait = this->Type->Sleep;
1331 switch (this->State) {
1332 case 0:
1333 case 2:
1334 ++this->State;
1335 break;
1336 case 1:
1337 if (NextMissileFrame(this, 1, 0)) {
1338 ++this->State;
1339 }
1340 break;
1341 case 3:
1342 if (NextMissileFrame(this, -1, 0)) {
1343 MissileHit(this);
1344 this->TTL = 0;
1345 }
1346 break;
1347 }
1348 }
1349
1350 /**
1351 ** Missile don't move, than checks the source unit for HP.
1352 */
1353 void MissileFire::Action()
1354 {
1355 CUnit *unit;
1356
1357 unit = this->SourceUnit;
1358 this->Wait = this->Type->Sleep;
1359 if (unit->Destroyed || unit->Orders[0]->Action == UnitActionDie) {
1360 this->TTL = 0;
1361 return;
1362 }
1363 if (NextMissileFrame(this, 1, 0)) {
1364 int f;
1365 MissileType *fire;
1366
1367 this->SpriteFrame = 0;
1368 f = (100 * unit->Variable[HP_INDEX].Value) / unit->Variable[HP_INDEX].Max;
1369 fire = MissileBurningBuilding(f);
1370 if (!fire) {
1371 this->TTL = 0;
1372 unit->Burning = 0;
1373 } else {
1374 if (this->Type != fire) {
1375 this->X += this->Type->Width / 2;
1376 this->Y += this->Type->Height / 2;
1377 this->Type = fire;
1378 this->X -= this->Type->Width / 2;
1379 this->Y -= this->Type->Height / 2;
1380 }
1381 }
1382 }
1383 }
1384
1385 /**
1386 ** Missile shows hit points?
1387 */
1388 void MissileHit::Action()
1389 {
1390 this->Wait = this->Type->Sleep;
1391 if (PointToPointMissile(this)) {
1392 ::MissileHit(this);
1393 this->TTL = 0;
1394 }
1395 }
1396
1397 /**
1398 ** Missile flies from x,y to x1,y1 using a parabolic path
1399 */
1400 void MissileParabolic::Action()
1401 {
1402 this->Wait = this->Type->Sleep;
1403 if (ParabolicMissile(this)) {
1404 MissileHit(this);
1405 this->TTL = 0;
1406 } else {
1407 NextMissileFrameCycle(this);
1408 }
1409 }
1410
1411 //@}