Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/spaceshipcontrol/src/world_entities/weapons/weapon.cc @ 6905

Last change on this file since 6905 was 6756, checked in by bensch, 19 years ago

trunk: Burst Particles

File size: 19.3 KB
Line 
1
2/*
3   orxonox - the future of 3D-vertical-scrollers
4
5   Copyright (C) 2004 orx
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2, or (at your option)
10   any later version.
11
12### File Specific
13   main-programmer: Patrick Boenzli
14   co-programmer: Benjamin Grauer
15
16   2005-07-15: Benjamin Grauer: restructurating the entire Class
17*/
18
19#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WEAPON
20
21#include "weapon.h"
22
23#include "fast_factory.h"
24#include "world_entities/projectiles/projectile.h"
25
26#include "resource_manager.h"
27#include "class_list.h"
28#include "load_param.h"
29#include "state.h"
30#include "animation3d.h"
31#include "vector.h"
32
33#include "sound_source.h"
34#include "sound_buffer.h"
35
36#include "glgui_bar.h"
37
38////////////////////
39// INITAILISATION //
40// SETTING VALUES //
41////////////////////
42/**
43 * standard constructor
44 *
45 * creates a new weapon
46*/
47Weapon::Weapon ()
48{
49  this->init();
50}
51
52/**
53 * standard deconstructor
54*/
55Weapon::~Weapon ()
56{
57  for (int i = 0; i < WS_STATE_COUNT; i++)
58    if (this->animation[i] && ClassList::exists(animation[i], CL_ANIMATION))  //!< @todo this should check animation3D
59      delete this->animation[i];
60  for (int i = 0; i < WA_ACTION_COUNT; i++)
61    if (this->soundBuffers[i] != NULL && ClassList::exists(this->soundBuffers[i], CL_SOUND_BUFFER))
62      ResourceManager::getInstance()->unload(this->soundBuffers[i]);
63
64  if (ClassList::exists(this->soundSource, CL_SOUND_SOURCE))
65    delete this->soundSource;
66}
67
68/**
69 * initializes the Weapon with ALL default values
70 *
71 * This Sets the default values of the Weapon
72 */
73void Weapon::init()
74{
75  this->currentState     = WS_INACTIVE;            //< Normaly the Weapon is Inactive
76  this->requestedAction  = WA_NONE;                //< No action is requested by default
77  this->stateDuration    = 0.0;                    //< All the States have zero duration
78  for (int i = 0; i < WS_STATE_COUNT; i++)         //< Every State has:
79  {
80    this->times[i] = 0.0;                        //< An infinitesimal duration
81    this->animation[i] = NULL;                   //< No animation
82  }
83  for (int i = 0; i < WA_ACTION_COUNT; i++)
84    this->soundBuffers[i] = NULL;                  //< No Sounds
85
86  this->soundSource = new SoundSource(this);       //< Every Weapon has exacty one SoundSource.
87  this->emissionPoint.setParent(this);             //< One EmissionPoint, that is a PNode connected to the weapon. You can set this to the exitting point of the Projectiles
88
89  this->target = NULL;                             //< Nothing is Targeted by default.
90
91  this->projectile = CL_NULL;                      //< No Projectile Class is Connected to this weapon
92  this->projectileFactory = NULL;                  //< No Factory generating Projectiles is selected.
93
94  this->hideInactive = true;                       //< The Weapon will be hidden if it is inactive (by default)
95
96  this->minCharge = 1.0;                           //< The minimum charge the Weapon can hold is 1 unit.
97  this->maxCharge = 1.0;                           //< The maximum charge is also one unit.
98
99  this->energy = 10;                               //< The secondary Buffer (before we have to reload)
100  this->energyMax = 10.0;                          //< How much energy can be carried
101  this->capability = WTYPE_ALL;                    //< The Weapon has all capabilities @see W_Capability.
102
103  this->energyWidget = NULL;
104
105  // set this object to be synchronized over network
106  //this->setSynchronized(true);
107}
108
109/**
110 * loads the Parameters of a Weapon
111 * @param root the XML-Element to load the Weapons settings from
112 */
113void Weapon::loadParams(const TiXmlElement* root)
114{
115  WorldEntity::loadParams(root);
116
117  LoadParam(root, "projectile", this, Weapon, setProjectileType)
118  .describe("Sets the name of the Projectile to load onto the Entity");
119
120  LoadParam(root, "emission-point", this, Weapon, setEmissionPoint)
121  .describe("Sets the Point of emission of this weapon");
122
123  LoadParam(root, "state-duration", this, Weapon, setStateDuration)
124  .describe("Sets the duration of a given state (1: state-Name; 2: duration in seconds)");
125
126  LoadParam(root, "action-sound", this, Weapon, setActionSound)
127  .describe("Sets a given sound to an action (1: action-Name; 2: name of the sound (relative to the Data-Path))");
128}
129
130
131/**
132 * sets the Projectile to use for this weapon.
133 * @param projectile The ID of the Projectile to use
134 * @returns true, if it was sucessfull, false on error
135 *
136 * be aware, that this function does not create Factories, as this is job of Projecitle/Bullet-classes.
137 * What it does, is telling the Weapon what Projectiles it can Emit.
138 */
139void Weapon::setProjectileType(ClassID projectile)
140{
141  if (projectile == CL_NULL)
142    return;
143  this->projectile = projectile;
144  this->projectileFactory = FastFactory::searchFastFactory(projectile);
145  if (this->projectileFactory == NULL)
146  {
147    PRINTF(1)("unable to find FastFactory for the Projectile.\n");
148    return;
149  }
150  else
151  {
152    // grabbing Parameters from the Projectile to have them at hand here.
153    Projectile* pj = dynamic_cast<Projectile*>(this->projectileFactory->resurrect());
154    this->minCharge = pj->getMinEnergy();
155    this->maxCharge = pj->getHealthMax();
156    this->chargeable = pj->isChageable();
157    this->projectileFactory->kill(pj);
158  }
159}
160
161
162/**
163 * @see bool Weapon::setProjectile(ClassID projectile)
164 * @param projectile the Name of the Projectile.
165 */
166void Weapon::setProjectileType(const char* projectile)
167{
168  if (projectile == NULL)
169    return;
170  FastFactory* tmpFac = FastFactory::searchFastFactory(projectile);
171  if (tmpFac != NULL)
172  {
173    this->setProjectileType(tmpFac->getStoredID());
174  }
175  else
176  {
177    PRINTF(1)("Projectile %s does not exist for weapon %s\n", projectile, this->getName());
178  }
179}
180
181
182/**
183 * prepares Projectiles of the Weapon
184 * @param count how many Projectiles to create (they will be stored in the ProjectileFactory)
185 */
186void Weapon::prepareProjectiles(unsigned int count)
187{
188  if (likely(this->projectileFactory != NULL))
189    projectileFactory->prepare(count);
190  else
191    PRINTF(2)("unable to create %d projectile for Weapon %s (%s)\n", count, this->getName(), this->getClassName());
192}
193
194
195/**
196 * resurects and returns a Projectile
197 * @returns a Projectile on success, NULL on error
198 *
199 * errors: 1. (ProjectileFastFactory not Found)
200 *         2. No more Projectiles availiable.
201 */
202Projectile* Weapon::getProjectile()
203{
204  if (likely (this->projectileFactory != NULL))
205  {
206    Projectile* pj = dynamic_cast<Projectile*>(this->projectileFactory->resurrect());
207    pj->toList((OM_LIST)(this->getOMListNumber()+1));
208    return pj;
209  }
210  else
211  {
212    PRINTF(2)("No projectile defined for Weapon %s(%s) can't return any\n", this->getName(), this->getClassName());
213    return NULL;
214  }
215}
216
217
218/**
219 * sets the emissionPoint's relative position from the Weapon
220 * @param point the Point relative to the mass-point of the Weapon
221 */
222void Weapon::setEmissionPoint(const Vector& point)
223{
224  this->emissionPoint.setRelCoor(point);
225}
226
227
228/**
229 * assigns a Sound-file to an action
230 * @param action the action the sound should be assigned too
231 * @param soundFile the soundFile's relative position to the data-directory (will be looked for by the ResourceManager)
232 */
233void Weapon::setActionSound(WeaponAction action, const char* soundFile)
234{
235  if (action >= WA_ACTION_COUNT)
236    return;
237  if (this->soundBuffers[action] != NULL)
238    ResourceManager::getInstance()->unload(this->soundBuffers[action]);
239
240  else if (soundFile != NULL)
241  {
242    this->soundBuffers[action] = (SoundBuffer*)ResourceManager::getInstance()->load(soundFile, WAV);
243    if (this->soundBuffers[action] != NULL)
244    {
245      PRINTF(4)("Loaded sound %s to action %s.\n", soundFile, actionToChar(action));
246    }
247    else
248    {
249      PRINTF(2)("Failed to load sound %s to %s.\n.", soundFile, actionToChar(action));
250    }
251  }
252  else
253    this->soundBuffers[action] = NULL;
254}
255
256
257/**
258 * creates/returns an Animation3D for a certain State.
259 * @param state what State should the Animation be created/returned for
260 * @param node the node this Animation should apply to. (NULL is fine if the animation was already created)
261 * @returns The created animation.Animation(), NULL on error (or if the animation does not yet exist).
262 *
263 * This function does only generate the Animation Object, and if set it will
264 * automatically be executed, when a certain State is reached.
265 * What this does not do, is set keyframes, you have to operate on the returned animation.
266 */
267Animation3D* Weapon::getAnimation(WeaponState state, PNode* node)
268{
269  if (state >= WS_STATE_COUNT) // if the state is not known
270    return NULL;
271
272  if (unlikely(this->animation[state] == NULL)) // if the animation does not exist yet create it.
273  {
274    if (likely(node != NULL))
275      return this->animation[state] = new Animation3D(node);
276    else
277    {
278      PRINTF(2)("Node not defined for the Creation of the 3D-animation of state %s\n", stateToChar(state));
279      return NULL;
280    }
281  }
282  else
283    return this->animation[state];
284}
285
286GLGuiWidget* Weapon::getEnergyWidget()
287{
288  if (this->energyWidget == NULL)
289  {
290    this->energyWidget = new GLGuiBar;
291    this->energyWidget->setSize2D( 20, 100);
292    this->energyWidget->setMaximum(this->getEnergyMax());
293    this->energyWidget->setValue(this->getEnergy());
294  }
295  return this->energyWidget;
296}
297
298void Weapon::updateWidgets()
299{
300  if (this->energyWidget != NULL)
301  {
302    this->energyWidget->setMaximum(this->energyMax);
303    this->energyWidget->setValue(this->energy);
304  }
305}
306
307/////////////////
308//  EXECUTION  //
309// GAME ACTION //
310/////////////////
311/**
312 * request an action that should be executed,
313 * @param action the next action to take
314 *
315 * This function must be called instead of the actions (like fire/reload...)
316 * to make all the checks needed to have a usefull WeaponSystem.
317 */
318void Weapon::requestAction(WeaponAction action)
319{
320  if (likely(this->isActive()))
321  {
322    if (this->requestedAction != WA_NONE)
323      return;
324    PRINTF(5)("next action will be %s in %f seconds\n", actionToChar(action), this->stateDuration);
325    this->requestedAction = action;
326  }
327  //else
328  else if (unlikely(action == WA_ACTIVATE))
329  {
330    this->currentState = WS_ACTIVATING;
331    this->requestedAction = WA_ACTIVATE;
332  }
333}
334
335
336/**
337 * adds energy to the Weapon
338 * @param energyToAdd The amount of energy
339 * @returns the amount of energy we did not pick up, because the weapon is already full
340 */
341float Weapon::increaseEnergy(float energyToAdd)
342{
343  float maxAddEnergy = this->energyMax - this->energy;
344
345  if (maxAddEnergy >= energyToAdd)
346  {
347    this->energy += energyToAdd;
348    return 0.0;
349  }
350  else
351  {
352    this->energy += maxAddEnergy;
353    return energyToAdd - maxAddEnergy;
354  }
355}
356
357
358////////////////////////////////////////////////////////////
359// WEAPON INTERNALS                                       //
360// These are functions, that no other Weapon should over- //
361// write. No class has direct Access to them, as it is    //
362// quite a complicated process, handling a Weapon from    //
363// the outside                                            //
364////////////////////////////////////////////////////////////
365/**
366 * executes an action, and with it starts a new State.
367 * @return true, if it worked, false otherwise
368 *
369 * This function checks, wheter the possibility of executing an action is valid,
370 * and does all the necessary stuff, to execute them. If an action does not succeed,
371 * it tries to go around it. (ex. shoot->noAmo->reload()->wait until shoot comes again)
372 */
373bool Weapon::execute()
374{
375#if DEBUG > 4
376  PRINTF(4)("trying to execute action %s\n", actionToChar(this->requestedAction));
377  this->debug();
378#endif
379
380  WeaponAction action = this->requestedAction;
381  this->requestedAction = WA_NONE;
382
383  switch (action)
384  {
385  case WA_SHOOT:
386    return this->fireW();
387    break;
388  case WA_CHARGE:
389    return this->chargeW();
390    break;
391  case WA_RELOAD:
392    return this->reloadW();
393    break;
394  case WA_DEACTIVATE:
395    return this->deactivateW();
396    break;
397  case WA_ACTIVATE:
398    return this->activateW();
399    break;
400  }
401}
402
403/**
404 * checks and activates the Weapon.
405 * @return true on success.
406 */
407bool Weapon::activateW()
408{
409  //  if (this->currentState == WS_INACTIVE)
410  {
411    // play Sound
412    if (likely(this->soundBuffers[WA_ACTIVATE] != NULL))
413      this->soundSource->play(this->soundBuffers[WA_ACTIVATE]);
414    this->updateWidgets();
415    // activate
416    PRINTF(4)("Activating the Weapon %s\n", this->getName());
417    this->activate();
418    // setting up for next action
419    this->enterState(WS_ACTIVATING);
420  }
421}
422
423/**
424 * checks and deactivates the Weapon
425 * @return true on success.
426 */
427bool Weapon::deactivateW()
428{
429  //  if (this->currentState != WS_INACTIVE)
430  {
431    PRINTF(4)("Deactivating the Weapon %s\n", this->getName());
432    // play Sound
433    if (this->soundBuffers[WA_DEACTIVATE] != NULL)
434      this->soundSource->play(this->soundBuffers[WA_DEACTIVATE]);
435    // deactivate
436    this->deactivate();
437    this->enterState(WS_DEACTIVATING);
438  }
439}
440
441/**
442 * checks and charges the Weapon
443 * @return true on success.
444 */
445bool Weapon::chargeW()
446{
447  if ( this->currentState != WS_INACTIVE && this->energy >= this->minCharge)
448  {
449    // playing Sound
450    if (this->soundBuffers[WA_CHARGE] != NULL)
451      this->soundSource->play(this->soundBuffers[WA_CHARGE]);
452
453    // charge
454    this->charge();
455    // setting up for the next state
456    this->enterState(WS_CHARGING);
457  }
458  else // deactivate the Weapon if we do not have enough energy
459  {
460    this->requestAction(WA_RELOAD);
461  }
462}
463
464/**
465 * checks and fires the Weapon
466 * @return true on success.
467 */
468bool Weapon::fireW()
469{
470  //if (likely(this->currentState != WS_INACTIVE))
471  if (this->minCharge <= this->energy)
472  {
473    // playing Sound
474    if (this->soundBuffers[WA_SHOOT] != NULL)
475      this->soundSource->play(this->soundBuffers[WA_SHOOT]);
476    this->updateWidgets();
477    // fire
478    this->energy -= this->minCharge;
479    this->fire();
480    // setting up for the next state
481    this->enterState(WS_SHOOTING);
482  }
483  else  // reload if we still have the charge
484  {
485    this->requestAction(WA_RELOAD);
486    this->execute();
487  }
488}
489
490/**
491 * checks and Reloads the Weapon
492 * @return true on success.
493 */
494bool Weapon::reloadW()
495{
496  PRINTF(4)("Reloading Weapon %s\n", this->getName());
497  if (this->ammoContainer.get() != NULL &&
498        unlikely(this->energy + this->ammoContainer->getStoredEnergy() < this->minCharge))
499  {
500    this->requestAction(WA_DEACTIVATE);
501    this->execute();
502    return false;
503  }
504
505
506  if (this->soundBuffers[WA_RELOAD] != NULL)
507    this->soundSource->play(this->soundBuffers[WA_RELOAD]);
508
509  if (this->ammoContainer.get() != NULL)
510    this->ammoContainer->fillWeapon(this);
511  else
512  {
513    this->energy = this->energyMax;
514  }
515  this->updateWidgets();
516  this->reload();
517  this->enterState(WS_RELOADING);
518}
519
520/**
521 * enters the requested State, plays back animations updates the timing.
522 * @param state the state to enter.
523 */
524inline void Weapon::enterState(WeaponState state)
525{
526  PRINTF(4)("ENTERING STATE %s\n", stateToChar(state));
527  // playing animation if availiable
528  if (likely(this->animation[state] != NULL))
529    this->animation[state]->replay();
530
531  this->stateDuration += this->times[state];
532  this->currentState = state;
533}
534
535///////////////////
536//  WORLD-ENTITY //
537// FUNCTIONALITY //
538///////////////////
539/**
540 * tick signal for time dependent/driven stuff
541*/
542bool Weapon::tickW(float dt)
543{
544  //printf("%s ", stateToChar(this->currentState));
545
546  // setting up the timing properties
547  this->stateDuration -= dt;
548
549  if (this->stateDuration <= 0.0)
550  {
551    if (unlikely (this->currentState == WS_DEACTIVATING))
552    {
553      this->currentState = WS_INACTIVE;
554      return false;
555    }
556    else
557      this->currentState = WS_IDLE;
558
559    if (this->requestedAction != WA_NONE)
560    {
561      this->stateDuration = -dt;
562      this->execute();
563    }
564  }
565  return true;
566}
567
568
569
570
571//////////////////////
572// HELPER FUNCTIONS //
573//////////////////////
574/**
575 * checks wether all the Weapons functions are valid, and if it is possible to go to action with it.
576 * @todo IMPLEMENT the Weapons Check
577 */
578bool Weapon::check() const
579{
580  bool retVal = true;
581
582  //  if (this->projectile == NULL)
583  {
584    PRINTF(1)("There was no projectile assigned to the Weapon.\n");
585    retVal = false;
586  }
587
588
589
590
591  return retVal;
592}
593
594/**
595 * some nice debugging information about this Weapon
596 */
597void Weapon::debug() const
598{
599  PRINT(0)("Weapon-Debug %s, state: %s (duration: %fs), nextAction: %s\n", this->getName(), Weapon::stateToChar(this->currentState), this->stateDuration, Weapon::actionToChar(requestedAction));
600  PRINT(0)("Energy: max: %f; current: %f; chargeMin: %f, chargeMax %f\n",
601           this->energyMax, this->energy, this->minCharge, this->maxCharge);
602
603
604}
605
606////////////////////////////////////////////////////////
607// static Definitions (transormators for readability) //
608////////////////////////////////////////////////////////
609/**
610 * Converts a String into an Action.
611 * @param action the String input holding the Action.
612 * @return The Action if known, WA_NONE otherwise.
613 */
614WeaponAction Weapon::charToAction(const char* action)
615{
616  if (!strcmp(action, "none"))
617    return WA_NONE;
618  else if (!strcmp(action, "shoot"))
619    return WA_SHOOT;
620  else if (!strcmp(action, "charge"))
621    return WA_CHARGE;
622  else if (!strcmp(action, "reload"))
623    return WA_RELOAD;
624  else if (!strcmp(action, "acitvate"))
625    return WA_ACTIVATE;
626  else if (!strcmp(action, "deactivate"))
627    return WA_DEACTIVATE;
628  else if (!strcmp(action, "special1"))
629    return WA_SPECIAL1;
630  else
631  {
632    PRINTF(2)("action %s could not be identified.\n", action);
633    return WA_NONE;
634  }
635}
636
637/**
638 * converts an action into a String
639 * @param action the action to convert
640 * @return a String matching the name of the action
641 */
642const char* Weapon::actionToChar(WeaponAction action)
643{
644  switch (action)
645  {
646  case WA_SHOOT:
647    return "shoot";
648    break;
649  case WA_CHARGE:
650    return "charge";
651    break;
652  case WA_RELOAD:
653    return "reload";
654    break;
655  case WA_ACTIVATE:
656    return "activate";
657    break;
658  case WA_DEACTIVATE:
659    return "deactivate";
660    break;
661  case WA_SPECIAL1:
662    return "special1";
663    break;
664  default:
665    return "none";
666    break;
667  }
668}
669
670/**
671 * Converts a String into a State.
672 * @param state the String input holding the State.
673 * @return The State if known, WS_NONE otherwise.
674 */
675WeaponState Weapon::charToState(const char* state)
676{
677  if (!strcmp(state, "none"))
678    return WS_NONE;
679  else if (!strcmp(state, "shooting"))
680    return WS_SHOOTING;
681  else if (!strcmp(state, "charging"))
682    return WS_CHARGING;
683  else if (!strcmp(state, "reloading"))
684    return WS_RELOADING;
685  else if (!strcmp(state, "activating"))
686    return WS_ACTIVATING;
687  else if (!strcmp(state, "deactivating"))
688    return WS_DEACTIVATING;
689  else if (!strcmp(state, "inactive"))
690    return WS_INACTIVE;
691  else if (!strcmp(state, "idle"))
692    return WS_IDLE;
693  else
694  {
695    PRINTF(2)("state %s could not be identified.\n", state);
696    return WS_NONE;
697  }
698}
699
700/**
701 * converts a State into a String
702 * @param state the state to convert
703 * @return a String matching the name of the state
704 */
705const char* Weapon::stateToChar(WeaponState state)
706{
707  switch (state)
708  {
709  case WS_SHOOTING:
710    return "shooting";
711    break;
712  case WS_CHARGING:
713    return "charging";
714    break;
715  case WS_RELOADING:
716    return "reloading";
717    break;
718  case WS_ACTIVATING:
719    return "activating";
720    break;
721  case WS_DEACTIVATING:
722    return "deactivating";
723    break;
724  case WS_IDLE:
725    return "idle";
726    break;
727  case WS_INACTIVE:
728    return "inactive";
729    break;
730  default:
731    return "none";
732    break;
733  }
734}
Note: See TracBrowser for help on using the repository browser.