CommandBuff.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "CommandBuff.h"
  2. #include <algorithm>
  3. USING_NS_CC;
  4. #define EVENT_AFTER_DRAW_RESET_POSITION "director_after_draw"
  5. using std::max;
  6. #define INITIAL_SIZE (10000)
  7. static CommandBuff* instance = nullptr;
  8. CommandBuff* CommandBuff::getInstance () {
  9. if (!instance) instance = new CommandBuff();
  10. return instance;
  11. }
  12. void CommandBuff::destroyInstance () {
  13. if (instance) {
  14. delete instance;
  15. instance = nullptr;
  16. }
  17. }
  18. CommandBuff::CommandBuff () {
  19. for (unsigned int i = 0; i < INITIAL_SIZE; i++) {
  20. _commandsPool.push_back(new TrianglesCommand());
  21. }
  22. reset ();
  23. // callback after drawing is finished so we can clear out the batch state
  24. // for the next frame
  25. Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_AFTER_DRAW_RESET_POSITION, [this](EventCustom* eventCustom){
  26. this->update(0);
  27. });;
  28. }
  29. CommandBuff::~CommandBuff () {
  30. Director::getInstance()->getEventDispatcher()->removeCustomEventListeners(EVENT_AFTER_DRAW_RESET_POSITION);
  31. for (unsigned int i = 0; i < _commandsPool.size(); i++) {
  32. delete _commandsPool[i];
  33. _commandsPool[i] = nullptr;
  34. }
  35. }
  36. void CommandBuff::update (float delta) {
  37. reset();
  38. }
  39. cocos2d::TrianglesCommand* CommandBuff::addCommand(cocos2d::Renderer* renderer, float globalOrder, cocos2d::Texture2D* texture, cocos2d::GLProgramState* glProgramState, cocos2d::BlendFunc blendType, const cocos2d::TrianglesCommand::Triangles& triangles, const cocos2d::Mat4& mv, uint32_t flags) {
  40. TrianglesCommand* command = nextFreeCommand();
  41. command->init(globalOrder, texture, glProgramState, blendType, triangles, mv, flags);
  42. renderer->addCommand(command);
  43. return command;
  44. }
  45. void CommandBuff::reset() {
  46. _nextFreeCommand = 0;
  47. }
  48. cocos2d::TrianglesCommand* CommandBuff::nextFreeCommand() {
  49. if (_commandsPool.size() <= _nextFreeCommand) {
  50. auto newSize = _commandsPool.size() * 2 + 1;
  51. for (auto i = _commandsPool.size(); i < newSize; i++) {
  52. _commandsPool.push_back(new TrianglesCommand());
  53. }
  54. }
  55. return _commandsPool[_nextFreeCommand++];
  56. }