Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/world_entities/weapons/weapon.cc @ 8258

Last change on this file since 8258 was 7779, checked in by bensch, 18 years ago

3088 linews changed :): trunk: namespaces

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