Overte C++ Documentation
EntityPriorityQueue.h
1 //
2 // EntityPriorityQueue.h
3 // assignment-client/src/entities
4 //
5 // Created by Andrew Meadows 2017.08.08
6 // Copyright 2017 High Fidelity, Inc.
7 //
8 // Distributed under the Apache License, Version 2.0.
9 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10 //
11 
12 #ifndef hifi_EntityPriorityQueue_h
13 #define hifi_EntityPriorityQueue_h
14 
15 #include <queue>
16 #include <unordered_set>
17 
18 #include "EntityItem.h"
19 
20 // PrioritizedEntity is a placeholder in a sorted queue.
21 class PrioritizedEntity {
22 public:
23  static constexpr float DO_NOT_SEND { -1.0e6f };
24  static constexpr float FORCE_REMOVE { -1.0e5f };
25  static constexpr float WHEN_IN_DOUBT_PRIORITY { 1.0f };
26 
27  PrioritizedEntity(EntityItemPointer entity, float priority, bool forceRemove = false) : _weakEntity(entity), _rawEntityPointer(entity.get()), _priority(priority), _forceRemove(forceRemove) {}
28  EntityItemPointer getEntity() const { return _weakEntity.lock(); }
29  EntityItem* getRawEntityPointer() const { return _rawEntityPointer; }
30  float getPriority() const { return _priority; }
31  bool shouldForceRemove() const { return _forceRemove; }
32 
33  class Compare {
34  public:
35  bool operator() (const PrioritizedEntity& A, const PrioritizedEntity& B) { return A._priority < B._priority; }
36  };
37  friend class Compare;
38 
39 private:
40  EntityItemWeakPointer _weakEntity;
41  EntityItem* _rawEntityPointer;
42  float _priority;
43  bool _forceRemove;
44 };
45 
46 class EntityPriorityQueue {
47 public:
48  inline bool empty() const {
49  assert(_queue.empty() == _entities.empty());
50  return _queue.empty();
51  }
52 
53  inline const PrioritizedEntity& top() const {
54  assert(!_queue.empty());
55  return _queue.top();
56  }
57 
58  inline bool contains(const EntityItem* entity) const {
59  return _entities.find(entity) != std::end(_entities);
60  }
61 
62  inline void emplace(const EntityItemPointer& entity, float priority, bool forceRemove = false) {
63  assert(entity && !contains(entity.get()));
64  _queue.emplace(entity, priority, forceRemove);
65  _entities.insert(entity.get());
66  assert(_queue.size() == _entities.size());
67  }
68 
69  inline void pop() {
70  assert(!empty());
71  _entities.erase(_queue.top().getRawEntityPointer());
72  _queue.pop();
73  assert(_queue.size() == _entities.size());
74  }
75 
76  inline void swap(EntityPriorityQueue& other) {
77  std::swap(_queue, other._queue);
78  std::swap(_entities, other._entities);
79  }
80 
81 private:
82  using PriorityQueue = std::priority_queue<PrioritizedEntity,
83  std::vector<PrioritizedEntity>,
84  PrioritizedEntity::Compare>;
85 
86  PriorityQueue _queue;
87  // Keep dictionary of all the entities in the queue for fast contain checks.
88  std::unordered_set<const EntityItem*> _entities;
89 
90 };
91 
92 #endif // hifi_EntityPriorityQueue_h
Definition: EntityItem.h:82