RandomSelector.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2014 Guy Allard
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "RandomSelector.h"
  23. #include "math/mMathFn.h"
  24. using namespace BadBehavior;
  25. //------------------------------------------------------------------------------
  26. // Random selector node
  27. //------------------------------------------------------------------------------
  28. IMPLEMENT_CONOBJECT(RandomSelector);
  29. Task *RandomSelector::createTask(SimObject &owner, BehaviorTreeRunner &runner)
  30. {
  31. return new RandomSelectorTask(*this, owner, runner);
  32. }
  33. //------------------------------------------------------------------------------
  34. // Random selector task
  35. //------------------------------------------------------------------------------
  36. RandomSelectorTask::RandomSelectorTask(Node &node, SimObject &owner, BehaviorTreeRunner &runner)
  37. : Parent(node, owner, runner)
  38. {
  39. }
  40. void RandomSelectorTask::onInitialize()
  41. {
  42. Parent::onInitialize();
  43. // randomize the order of our child tasks
  44. VectorPtr<Task *> randomChildren;
  45. while(mChildren.size() > 0)
  46. {
  47. U32 index = mRandI(0, mChildren.size() - 1);
  48. Task* child = mChildren[index];
  49. randomChildren.push_back(child);
  50. mChildren.erase_fast(index);
  51. }
  52. mChildren = randomChildren;
  53. // normal init
  54. mCurrentChild = mChildren.begin();
  55. if(mCurrentChild != mChildren.end())
  56. (*mCurrentChild)->reset();
  57. }