Context.cpp 13 KB

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