hx3d  1
2D/3D Simple Game Framework
pool.inl.hpp
1 /*
2  Pool system.
3  Copyright (C) 2015 Denis BOURGE
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Lesser General Public
7  License as published by the Free Software Foundation; either
8  version 2.1 of the License, or (at your option) any later version.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public
16  License along with this library; if not, write to the Free Software
17  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
18  USA
19 */
20 
21 #include "hx3d/utils/log.hpp"
22 
23 namespace hx3d {
24 
25 template <class T>
26 template <class... Args>
27 Pool<T>::Pool(unsigned int size, Args... args): size(size) {
28  for (unsigned int i = 0; i < size; ++i) {
29  const Ptr<T>& p = Make<T>(args...);
30  p->setId(i);
31 
32  _available.push(i);
33  _content.push_back(p);
34  }
35 }
36 
37 template <class T>
38 Pool<T>::~Pool() {}
39 
40 template <class T>
42  if (_available.size() > 0) {
43  const Ptr<T>& ptr = _content[_available.front()];
44  _available.pop();
45  _locked.insert(ptr->getId());
46 
47  ptr->reset();
48  return ptr;
49  }
50 
51  throw std::runtime_error("STOP");
52 }
53 
54 template <class T>
55 void Pool<T>::release(const Ptr<T>& ptr) {
56  unsigned int id = ptr->getId();
57  if (_locked.find(id) != _locked.end()) {
58  _locked.erase(id);
59  _available.push(id);
60 
61  ptr->reset();
62  }
63 
64  else {
65  Log.Error("Pool: Ptr is not working.");
66  }
67 }
68 
69 template <class T>
70 const std::set<Ptr<T>>& Pool<T>::getWorking() {
71  _working.clear();
72  for (auto& i: _locked) {
73  _working.insert(_content[i]);
74  }
75 
76  return _working;
77 }
78 
79 } /* hx3d */
void release(const Ptr< T > &ptr)
Release a poolable element.
Definition: pool.inl.hpp:55
Pool(unsigned int size, Args...args)
Construct a pool with a size and arguments.
Definition: pool.inl.hpp:27
const Ptr< T > & take()
Fetch a free poolable element.
Definition: pool.inl.hpp:41
Manage poolable elements.
Definition: pool.hpp:35
hx3d framework namespace
Definition: audio.hpp:26
void Error(const std::string fmt,...)
Write an error message.
Definition: log.cpp:72
static hx3d::LogImpl Log
Current log implementation.
Definition: log.hpp:91
const std::set< Ptr< T > > & getWorking()
Get the locked elements.
Definition: pool.inl.hpp:70
std::shared_ptr< T > Ptr
Quick-typing shared ptr.
Definition: ptr.hpp:34