Context.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/EventProfiler.h"
  25. #include "../IO/Log.h"
  26. #ifndef MINI_URHO
  27. #include <SDL/SDL.h>
  28. #ifdef URHO3D_IK
  29. #include <ik/log.h>
  30. #include <ik/memory.h>
  31. #endif
  32. #endif
  33. #include "../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. #ifndef MINI_URHO
  37. // Keeps track of how many times SDL was initialised so we know when to call SDL_Quit().
  38. static int sdlInitCounter = 0;
  39. // Keeps track of how many times IK was initialised
  40. static int ikInitCounter = 0;
  41. // Reroute all messages from the ik library to the Urho3D log
  42. static void HandleIKLog(const char* msg)
  43. {
  44. URHO3D_LOGINFOF("[IK] %s", msg);
  45. }
  46. #endif
  47. void EventReceiverGroup::BeginSendEvent()
  48. {
  49. ++inSend_;
  50. }
  51. void EventReceiverGroup::EndSendEvent()
  52. {
  53. assert(inSend_ > 0);
  54. --inSend_;
  55. if (inSend_ == 0 && dirty_)
  56. {
  57. /// \todo Could be optimized by erase-swap, but this keeps the receiver order
  58. for (unsigned i = receivers_.Size() - 1; i < receivers_.Size(); --i)
  59. {
  60. if (!receivers_[i])
  61. receivers_.Erase(i);
  62. }
  63. dirty_ = false;
  64. }
  65. }
  66. void EventReceiverGroup::Add(Object* object)
  67. {
  68. if (object)
  69. receivers_.Push(object);
  70. }
  71. void EventReceiverGroup::Remove(Object* object)
  72. {
  73. if (inSend_ > 0)
  74. {
  75. PODVector<Object*>::Iterator i = receivers_.Find(object);
  76. if (i != receivers_.End())
  77. {
  78. (*i) = nullptr;
  79. dirty_ = true;
  80. }
  81. }
  82. else
  83. receivers_.Remove(object);
  84. }
  85. void RemoveNamedAttribute(HashMap<StringHash, Vector<AttributeInfo> >& attributes, StringHash objectType, const char* name)
  86. {
  87. HashMap<StringHash, Vector<AttributeInfo> >::Iterator i = attributes.Find(objectType);
  88. if (i == attributes.End())
  89. return;
  90. Vector<AttributeInfo>& infos = i->second_;
  91. for (Vector<AttributeInfo>::Iterator j = infos.Begin(); j != infos.End(); ++j)
  92. {
  93. if (!j->name_.Compare(name, true))
  94. {
  95. infos.Erase(j);
  96. break;
  97. }
  98. }
  99. // If the vector became empty, erase the object type from the map
  100. if (infos.Empty())
  101. attributes.Erase(i);
  102. }
  103. Context::Context() :
  104. eventHandler_(nullptr)
  105. {
  106. #ifdef __ANDROID__
  107. // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs
  108. SetRandomSeed(1);
  109. #endif
  110. // Set the main thread ID (assuming the Context is created in it)
  111. Thread::SetMainThread();
  112. }
  113. Context::~Context()
  114. {
  115. // Remove subsystems that use SDL in reverse order of construction, so that Graphics can shut down SDL last
  116. /// \todo Context should not need to know about subsystems
  117. RemoveSubsystem("Audio");
  118. RemoveSubsystem("UI");
  119. RemoveSubsystem("Input");
  120. RemoveSubsystem("Renderer");
  121. RemoveSubsystem("Graphics");
  122. subsystems_.Clear();
  123. factories_.Clear();
  124. // Delete allocated event data maps
  125. for (PODVector<VariantMap*>::Iterator i = eventDataMaps_.Begin(); i != eventDataMaps_.End(); ++i)
  126. delete *i;
  127. eventDataMaps_.Clear();
  128. }
  129. SharedPtr<Object> Context::CreateObject(StringHash objectType)
  130. {
  131. HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories_.Find(objectType);
  132. if (i != factories_.End())
  133. return i->second_->CreateObject();
  134. else
  135. return SharedPtr<Object>();
  136. }
  137. void Context::RegisterFactory(ObjectFactory* factory)
  138. {
  139. if (!factory)
  140. return;
  141. factories_[factory->GetType()] = factory;
  142. }
  143. void Context::RegisterFactory(ObjectFactory* factory, const char* category)
  144. {
  145. if (!factory)
  146. return;
  147. RegisterFactory(factory);
  148. if (String::CStringLength(category))
  149. objectCategories_[category].Push(factory->GetType());
  150. }
  151. void Context::RegisterSubsystem(Object* object)
  152. {
  153. if (!object)
  154. return;
  155. subsystems_[object->GetType()] = object;
  156. }
  157. void Context::RemoveSubsystem(StringHash objectType)
  158. {
  159. HashMap<StringHash, SharedPtr<Object> >::Iterator i = subsystems_.Find(objectType);
  160. if (i != subsystems_.End())
  161. subsystems_.Erase(i);
  162. }
  163. AttributeHandle Context::RegisterAttribute(StringHash objectType, const AttributeInfo& attr)
  164. {
  165. // None or pointer types can not be supported
  166. if (attr.type_ == VAR_NONE || attr.type_ == VAR_VOIDPTR || attr.type_ == VAR_PTR
  167. || attr.type_ == VAR_CUSTOM_HEAP || attr.type_ == VAR_CUSTOM_STACK)
  168. {
  169. URHO3D_LOGWARNING("Attempt to register unsupported attribute type " + Variant::GetTypeName(attr.type_) + " to class " +
  170. GetTypeName(objectType));
  171. return AttributeHandle();
  172. }
  173. AttributeHandle handle;
  174. Vector<AttributeInfo>& objectAttributes = attributes_[objectType];
  175. objectAttributes.Push(attr);
  176. handle.attributeInfo_ = &objectAttributes.Back();
  177. if (attr.mode_ & AM_NET)
  178. {
  179. Vector<AttributeInfo>& objectNetworkAttributes = networkAttributes_[objectType];
  180. objectNetworkAttributes.Push(attr);
  181. handle.networkAttributeInfo_ = &objectNetworkAttributes.Back();
  182. }
  183. return handle;
  184. }
  185. void Context::RemoveAttribute(StringHash objectType, const char* name)
  186. {
  187. RemoveNamedAttribute(attributes_, objectType, name);
  188. RemoveNamedAttribute(networkAttributes_, objectType, name);
  189. }
  190. void Context::UpdateAttributeDefaultValue(StringHash objectType, const char* name, const Variant& defaultValue)
  191. {
  192. AttributeInfo* info = GetAttribute(objectType, name);
  193. if (info)
  194. info->defaultValue_ = defaultValue;
  195. }
  196. VariantMap& Context::GetEventDataMap()
  197. {
  198. unsigned nestingLevel = eventSenders_.Size();
  199. while (eventDataMaps_.Size() < nestingLevel + 1)
  200. eventDataMaps_.Push(new VariantMap());
  201. VariantMap& ret = *eventDataMaps_[nestingLevel];
  202. ret.Clear();
  203. return ret;
  204. }
  205. #ifndef MINI_URHO
  206. bool Context::RequireSDL(unsigned int sdlFlags)
  207. {
  208. // Always increment, the caller must match with ReleaseSDL(), regardless of
  209. // what happens.
  210. ++sdlInitCounter;
  211. // Need to call SDL_Init() at least once before SDL_InitSubsystem()
  212. if (sdlInitCounter == 1)
  213. {
  214. URHO3D_LOGDEBUG("Initialising SDL");
  215. if (SDL_Init(0) != 0)
  216. {
  217. URHO3D_LOGERRORF("Failed to initialise SDL: %s", SDL_GetError());
  218. return false;
  219. }
  220. }
  221. Uint32 remainingFlags = sdlFlags & ~SDL_WasInit(0);
  222. if (remainingFlags != 0)
  223. {
  224. if (SDL_InitSubSystem(remainingFlags) != 0)
  225. {
  226. URHO3D_LOGERRORF("Failed to initialise SDL subsystem: %s", SDL_GetError());
  227. return false;
  228. }
  229. }
  230. return true;
  231. }
  232. void Context::ReleaseSDL()
  233. {
  234. --sdlInitCounter;
  235. if (sdlInitCounter == 0)
  236. {
  237. URHO3D_LOGDEBUG("Quitting SDL");
  238. SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
  239. SDL_Quit();
  240. }
  241. if (sdlInitCounter < 0)
  242. URHO3D_LOGERROR("Too many calls to Context::ReleaseSDL()!");
  243. }
  244. #ifdef URHO3D_IK
  245. void Context::RequireIK()
  246. {
  247. // Always increment, the caller must match with ReleaseSDL(), regardless of
  248. // what happens.
  249. ++ikInitCounter;
  250. if (ikInitCounter == 1)
  251. {
  252. URHO3D_LOGDEBUG("Initialising Inverse Kinematics library");
  253. ik_memory_init();
  254. ik_log_init(IK_LOG_NONE);
  255. ik_log_register_listener(HandleIKLog);
  256. }
  257. }
  258. void Context::ReleaseIK()
  259. {
  260. --ikInitCounter;
  261. if (ikInitCounter == 0)
  262. {
  263. URHO3D_LOGDEBUG("De-initialising Inverse Kinematics library");
  264. ik_log_unregister_listener(HandleIKLog);
  265. ik_log_deinit();
  266. ik_memory_deinit();
  267. }
  268. if (ikInitCounter < 0)
  269. URHO3D_LOGERROR("Too many calls to Context::ReleaseIK()");
  270. }
  271. #endif // ifdef URHO3D_IK
  272. #endif // ifndef MINI_URHO
  273. void Context::CopyBaseAttributes(StringHash baseType, StringHash derivedType)
  274. {
  275. // Prevent endless loop if mistakenly copying attributes from same class as derived
  276. if (baseType == derivedType)
  277. {
  278. URHO3D_LOGWARNING("Attempt to copy base attributes to itself for class " + GetTypeName(baseType));
  279. return;
  280. }
  281. const Vector<AttributeInfo>* baseAttributes = GetAttributes(baseType);
  282. if (baseAttributes)
  283. {
  284. for (unsigned i = 0; i < baseAttributes->Size(); ++i)
  285. {
  286. const AttributeInfo& attr = baseAttributes->At(i);
  287. attributes_[derivedType].Push(attr);
  288. if (attr.mode_ & AM_NET)
  289. networkAttributes_[derivedType].Push(attr);
  290. }
  291. }
  292. }
  293. Object* Context::GetSubsystem(StringHash type) const
  294. {
  295. HashMap<StringHash, SharedPtr<Object> >::ConstIterator i = subsystems_.Find(type);
  296. if (i != subsystems_.End())
  297. return i->second_;
  298. else
  299. return nullptr;
  300. }
  301. const Variant& Context::GetGlobalVar(StringHash key) const
  302. {
  303. VariantMap::ConstIterator i = globalVars_.Find(key);
  304. return i != globalVars_.End() ? i->second_ : Variant::EMPTY;
  305. }
  306. void Context::SetGlobalVar(StringHash key, const Variant& value)
  307. {
  308. globalVars_[key] = value;
  309. }
  310. Object* Context::GetEventSender() const
  311. {
  312. if (!eventSenders_.Empty())
  313. return eventSenders_.Back();
  314. else
  315. return nullptr;
  316. }
  317. const String& Context::GetTypeName(StringHash objectType) const
  318. {
  319. // Search factories to find the hash-to-name mapping
  320. HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories_.Find(objectType);
  321. return i != factories_.End() ? i->second_->GetTypeName() : String::EMPTY;
  322. }
  323. AttributeInfo* Context::GetAttribute(StringHash objectType, const char* name)
  324. {
  325. HashMap<StringHash, Vector<AttributeInfo> >::Iterator i = attributes_.Find(objectType);
  326. if (i == attributes_.End())
  327. return nullptr;
  328. Vector<AttributeInfo>& infos = i->second_;
  329. for (Vector<AttributeInfo>::Iterator j = infos.Begin(); j != infos.End(); ++j)
  330. {
  331. if (!j->name_.Compare(name, true))
  332. return &(*j);
  333. }
  334. return nullptr;
  335. }
  336. void Context::AddEventReceiver(Object* receiver, StringHash eventType)
  337. {
  338. SharedPtr<EventReceiverGroup>& group = eventReceivers_[eventType];
  339. if (!group)
  340. group = new EventReceiverGroup();
  341. group->Add(receiver);
  342. }
  343. void Context::AddEventReceiver(Object* receiver, Object* sender, StringHash eventType)
  344. {
  345. SharedPtr<EventReceiverGroup>& group = specificEventReceivers_[sender][eventType];
  346. if (!group)
  347. group = new EventReceiverGroup();
  348. group->Add(receiver);
  349. }
  350. void Context::RemoveEventSender(Object* sender)
  351. {
  352. HashMap<Object*, HashMap<StringHash, SharedPtr<EventReceiverGroup> > >::Iterator i = specificEventReceivers_.Find(sender);
  353. if (i != specificEventReceivers_.End())
  354. {
  355. for (HashMap<StringHash, SharedPtr<EventReceiverGroup> >::Iterator j = i->second_.Begin(); j != i->second_.End(); ++j)
  356. {
  357. for (PODVector<Object*>::Iterator k = j->second_->receivers_.Begin(); k != j->second_->receivers_.End(); ++k)
  358. {
  359. Object* receiver = *k;
  360. if (receiver)
  361. receiver->RemoveEventSender(sender);
  362. }
  363. }
  364. specificEventReceivers_.Erase(i);
  365. }
  366. }
  367. void Context::RemoveEventReceiver(Object* receiver, StringHash eventType)
  368. {
  369. EventReceiverGroup* group = GetEventReceivers(eventType);
  370. if (group)
  371. group->Remove(receiver);
  372. }
  373. void Context::RemoveEventReceiver(Object* receiver, Object* sender, StringHash eventType)
  374. {
  375. EventReceiverGroup* group = GetEventReceivers(sender, eventType);
  376. if (group)
  377. group->Remove(receiver);
  378. }
  379. void Context::BeginSendEvent(Object* sender, StringHash eventType)
  380. {
  381. #ifdef URHO3D_PROFILING
  382. if (EventProfiler::IsActive())
  383. {
  384. EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
  385. if (eventProfiler)
  386. eventProfiler->BeginBlock(eventType);
  387. }
  388. #endif
  389. eventSenders_.Push(sender);
  390. }
  391. void Context::EndSendEvent()
  392. {
  393. eventSenders_.Pop();
  394. #ifdef URHO3D_PROFILING
  395. if (EventProfiler::IsActive())
  396. {
  397. EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
  398. if (eventProfiler)
  399. eventProfiler->EndBlock();
  400. }
  401. #endif
  402. }
  403. }