Context.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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::RemoveAllAttributes(StringHash objectType)
  191. {
  192. attributes_.Erase(objectType);
  193. networkAttributes_.Erase(objectType);
  194. }
  195. void Context::UpdateAttributeDefaultValue(StringHash objectType, const char* name, const Variant& defaultValue)
  196. {
  197. AttributeInfo* info = GetAttribute(objectType, name);
  198. if (info)
  199. info->defaultValue_ = defaultValue;
  200. }
  201. VariantMap& Context::GetEventDataMap()
  202. {
  203. unsigned nestingLevel = eventSenders_.Size();
  204. while (eventDataMaps_.Size() < nestingLevel + 1)
  205. eventDataMaps_.Push(new VariantMap());
  206. VariantMap& ret = *eventDataMaps_[nestingLevel];
  207. ret.Clear();
  208. return ret;
  209. }
  210. #ifndef MINI_URHO
  211. bool Context::RequireSDL(unsigned int sdlFlags)
  212. {
  213. // Always increment, the caller must match with ReleaseSDL(), regardless of
  214. // what happens.
  215. ++sdlInitCounter;
  216. // Need to call SDL_Init() at least once before SDL_InitSubsystem()
  217. if (sdlInitCounter == 1)
  218. {
  219. URHO3D_LOGDEBUG("Initialising SDL");
  220. if (SDL_Init(0) != 0)
  221. {
  222. URHO3D_LOGERRORF("Failed to initialise SDL: %s", SDL_GetError());
  223. return false;
  224. }
  225. }
  226. Uint32 remainingFlags = sdlFlags & ~SDL_WasInit(0);
  227. if (remainingFlags != 0)
  228. {
  229. if (SDL_InitSubSystem(remainingFlags) != 0)
  230. {
  231. URHO3D_LOGERRORF("Failed to initialise SDL subsystem: %s", SDL_GetError());
  232. return false;
  233. }
  234. }
  235. return true;
  236. }
  237. void Context::ReleaseSDL()
  238. {
  239. --sdlInitCounter;
  240. if (sdlInitCounter == 0)
  241. {
  242. URHO3D_LOGDEBUG("Quitting SDL");
  243. SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
  244. SDL_Quit();
  245. }
  246. if (sdlInitCounter < 0)
  247. URHO3D_LOGERROR("Too many calls to Context::ReleaseSDL()!");
  248. }
  249. #ifdef URHO3D_IK
  250. void Context::RequireIK()
  251. {
  252. // Always increment, the caller must match with ReleaseSDL(), regardless of
  253. // what happens.
  254. ++ikInitCounter;
  255. if (ikInitCounter == 1)
  256. {
  257. URHO3D_LOGDEBUG("Initialising Inverse Kinematics library");
  258. ik_memory_init();
  259. ik_log_init(IK_LOG_NONE);
  260. ik_log_register_listener(HandleIKLog);
  261. }
  262. }
  263. void Context::ReleaseIK()
  264. {
  265. --ikInitCounter;
  266. if (ikInitCounter == 0)
  267. {
  268. URHO3D_LOGDEBUG("De-initialising Inverse Kinematics library");
  269. ik_log_unregister_listener(HandleIKLog);
  270. ik_log_deinit();
  271. ik_memory_deinit();
  272. }
  273. if (ikInitCounter < 0)
  274. URHO3D_LOGERROR("Too many calls to Context::ReleaseIK()");
  275. }
  276. #endif // ifdef URHO3D_IK
  277. #endif // ifndef MINI_URHO
  278. void Context::CopyBaseAttributes(StringHash baseType, StringHash derivedType)
  279. {
  280. // Prevent endless loop if mistakenly copying attributes from same class as derived
  281. if (baseType == derivedType)
  282. {
  283. URHO3D_LOGWARNING("Attempt to copy base attributes to itself for class " + GetTypeName(baseType));
  284. return;
  285. }
  286. const Vector<AttributeInfo>* baseAttributes = GetAttributes(baseType);
  287. if (baseAttributes)
  288. {
  289. for (unsigned i = 0; i < baseAttributes->Size(); ++i)
  290. {
  291. const AttributeInfo& attr = baseAttributes->At(i);
  292. attributes_[derivedType].Push(attr);
  293. if (attr.mode_ & AM_NET)
  294. networkAttributes_[derivedType].Push(attr);
  295. }
  296. }
  297. }
  298. Object* Context::GetSubsystem(StringHash type) const
  299. {
  300. HashMap<StringHash, SharedPtr<Object> >::ConstIterator i = subsystems_.Find(type);
  301. if (i != subsystems_.End())
  302. return i->second_;
  303. else
  304. return nullptr;
  305. }
  306. const Variant& Context::GetGlobalVar(StringHash key) const
  307. {
  308. VariantMap::ConstIterator i = globalVars_.Find(key);
  309. return i != globalVars_.End() ? i->second_ : Variant::EMPTY;
  310. }
  311. void Context::SetGlobalVar(StringHash key, const Variant& value)
  312. {
  313. globalVars_[key] = value;
  314. }
  315. Object* Context::GetEventSender() const
  316. {
  317. if (!eventSenders_.Empty())
  318. return eventSenders_.Back();
  319. else
  320. return nullptr;
  321. }
  322. const String& Context::GetTypeName(StringHash objectType) const
  323. {
  324. // Search factories to find the hash-to-name mapping
  325. HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories_.Find(objectType);
  326. return i != factories_.End() ? i->second_->GetTypeName() : String::EMPTY;
  327. }
  328. AttributeInfo* Context::GetAttribute(StringHash objectType, const char* name)
  329. {
  330. HashMap<StringHash, Vector<AttributeInfo> >::Iterator i = attributes_.Find(objectType);
  331. if (i == attributes_.End())
  332. return nullptr;
  333. Vector<AttributeInfo>& infos = i->second_;
  334. for (Vector<AttributeInfo>::Iterator j = infos.Begin(); j != infos.End(); ++j)
  335. {
  336. if (!j->name_.Compare(name, true))
  337. return &(*j);
  338. }
  339. return nullptr;
  340. }
  341. void Context::AddEventReceiver(Object* receiver, StringHash eventType)
  342. {
  343. SharedPtr<EventReceiverGroup>& group = eventReceivers_[eventType];
  344. if (!group)
  345. group = new EventReceiverGroup();
  346. group->Add(receiver);
  347. }
  348. void Context::AddEventReceiver(Object* receiver, Object* sender, StringHash eventType)
  349. {
  350. SharedPtr<EventReceiverGroup>& group = specificEventReceivers_[sender][eventType];
  351. if (!group)
  352. group = new EventReceiverGroup();
  353. group->Add(receiver);
  354. }
  355. void Context::RemoveEventSender(Object* sender)
  356. {
  357. HashMap<Object*, HashMap<StringHash, SharedPtr<EventReceiverGroup> > >::Iterator i = specificEventReceivers_.Find(sender);
  358. if (i != specificEventReceivers_.End())
  359. {
  360. for (HashMap<StringHash, SharedPtr<EventReceiverGroup> >::Iterator j = i->second_.Begin(); j != i->second_.End(); ++j)
  361. {
  362. for (PODVector<Object*>::Iterator k = j->second_->receivers_.Begin(); k != j->second_->receivers_.End(); ++k)
  363. {
  364. Object* receiver = *k;
  365. if (receiver)
  366. receiver->RemoveEventSender(sender);
  367. }
  368. }
  369. specificEventReceivers_.Erase(i);
  370. }
  371. }
  372. void Context::RemoveEventReceiver(Object* receiver, StringHash eventType)
  373. {
  374. EventReceiverGroup* group = GetEventReceivers(eventType);
  375. if (group)
  376. group->Remove(receiver);
  377. }
  378. void Context::RemoveEventReceiver(Object* receiver, Object* sender, StringHash eventType)
  379. {
  380. EventReceiverGroup* group = GetEventReceivers(sender, eventType);
  381. if (group)
  382. group->Remove(receiver);
  383. }
  384. void Context::BeginSendEvent(Object* sender, StringHash eventType)
  385. {
  386. #ifdef URHO3D_PROFILING
  387. if (EventProfiler::IsActive())
  388. {
  389. auto* eventProfiler = GetSubsystem<EventProfiler>();
  390. if (eventProfiler)
  391. eventProfiler->BeginBlock(eventType);
  392. }
  393. #endif
  394. eventSenders_.Push(sender);
  395. }
  396. void Context::EndSendEvent()
  397. {
  398. eventSenders_.Pop();
  399. #ifdef URHO3D_PROFILING
  400. if (EventProfiler::IsActive())
  401. {
  402. auto* eventProfiler = GetSubsystem<EventProfiler>();
  403. if (eventProfiler)
  404. eventProfiler->EndBlock();
  405. }
  406. #endif
  407. }
  408. }