Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain.old/src/world_entities/weapons/weapon.cc @ 10607

Last change on this file since 10607 was 9406, checked in by bensch, 18 years ago

orxonox/trunk: merged the proxy back

merged with commandsvn merge -r9346:HEAD https://svn.orxonox.net/orxonox/branches/proxy .

no conflicts

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