JSComponent.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. //
  2. // Copyright (c) 2008-2014 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. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  23. // Please see LICENSE.md in repository root for license information
  24. // https://github.com/AtomicGameEngine/AtomicGameEngine
  25. #include <Atomic/IO/Log.h>
  26. #include <Atomic/IO/FileSystem.h>
  27. #include <Atomic/Core/Context.h>
  28. #include <Atomic/Resource/ResourceCache.h>
  29. #ifdef ATOMIC_PHYSICS
  30. #include <Atomic/Physics/PhysicsEvents.h>
  31. #include <Atomic/Physics/PhysicsWorld.h>
  32. #endif
  33. #include <Atomic/Scene/Scene.h>
  34. #include <Atomic/Scene/SceneEvents.h>
  35. #include "JSVM.h"
  36. #include "JSComponentFile.h"
  37. #include "JSComponent.h"
  38. namespace Atomic
  39. {
  40. extern const char* LOGIC_CATEGORY;
  41. JSComponent::JSComponent(Context* context) :
  42. Component(context),
  43. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  44. currentEventMask_(0),
  45. started_(false),
  46. delayedStartCalled_(false),
  47. loading_(false)
  48. {
  49. vm_ = JSVM::GetJSVM(NULL);
  50. }
  51. JSComponent::~JSComponent()
  52. {
  53. }
  54. void JSComponent::RegisterObject(Context* context)
  55. {
  56. context->RegisterFactory<JSComponent>(LOGIC_CATEGORY);
  57. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  58. ATTRIBUTE("FieldValues", VariantMap, fieldValues_, Variant::emptyVariantMap, AM_FILE);
  59. MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetScriptAttr, SetScriptAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  60. }
  61. void JSComponent::OnSetEnabled()
  62. {
  63. UpdateEventSubscription();
  64. }
  65. void JSComponent::SetUpdateEventMask(unsigned char mask)
  66. {
  67. if (updateEventMask_ != mask)
  68. {
  69. updateEventMask_ = mask;
  70. UpdateEventSubscription();
  71. }
  72. }
  73. void JSComponent::UpdateReferences(bool remove)
  74. {
  75. duk_context* ctx = vm_->GetJSContext();
  76. int top = duk_get_top(ctx);
  77. duk_push_global_stash(ctx);
  78. duk_get_prop_index(ctx, -1, JS_GLOBALSTASH_INDEX_NODE_REGISTRY);
  79. // can't use instance as key, as this coerces to [Object] for
  80. // string property, pointer will be string representation of
  81. // address, so, unique key
  82. duk_push_pointer(ctx, (void*) node_);
  83. if (remove)
  84. duk_push_undefined(ctx);
  85. else
  86. js_push_class_object_instance(ctx, node_);
  87. duk_put_prop(ctx, -3);
  88. duk_push_pointer(ctx, (void*) this);
  89. if (remove)
  90. duk_push_undefined(ctx);
  91. else
  92. js_push_class_object_instance(ctx, this);
  93. duk_put_prop(ctx, -3);
  94. duk_pop_2(ctx);
  95. assert(duk_get_top(ctx) == top);
  96. }
  97. void JSComponent::ApplyAttributes()
  98. {
  99. }
  100. void JSComponent::InitModule()
  101. {
  102. if (context_->GetEditorContext() || componentFile_.Null())
  103. return;
  104. duk_context* ctx = vm_->GetJSContext();
  105. const String& path = componentFile_->GetName();
  106. String pathName, fileName, ext;
  107. SplitPath(path, pathName, fileName, ext);
  108. pathName += "/" + fileName;
  109. duk_idx_t top = duk_get_top(ctx);
  110. duk_get_global_string(ctx, "require");
  111. duk_push_string(ctx, pathName.CString());
  112. if (duk_pcall(ctx, 1) != 0)
  113. {
  114. vm_->SendJSErrorEvent();
  115. return;
  116. }
  117. if (!duk_is_object(ctx, -1))
  118. {
  119. duk_set_top(ctx, top);
  120. return;
  121. }
  122. // store, so pop doesn't clear
  123. UpdateReferences();
  124. // apply fields
  125. const HashMap<String, VariantType>& fields = componentFile_->GetFields();
  126. if (fields.Size())
  127. {
  128. // push self
  129. js_push_class_object_instance(ctx, this, "JSComponent");
  130. HashMap<String, VariantType>::ConstIterator itr = fields.Begin();
  131. while (itr != fields.End())
  132. {
  133. if (fieldValues_.Contains(itr->first_))
  134. {
  135. Variant& v = fieldValues_[itr->first_];
  136. if (v.GetType() == itr->second_)
  137. {
  138. js_push_variant(ctx, v);
  139. duk_put_prop_string(ctx, -2, itr->first_.CString());
  140. }
  141. }
  142. else
  143. {
  144. Variant v;
  145. switch (itr->second_)
  146. {
  147. case VAR_BOOL:
  148. v = false;
  149. break;
  150. case VAR_STRING:
  151. v = "";
  152. break;
  153. case VAR_FLOAT:
  154. v = 0.0f;
  155. break;
  156. case VAR_VECTOR3:
  157. v = Vector3::ZERO;
  158. break;
  159. default:
  160. break;
  161. }
  162. js_push_variant(ctx, v);
  163. duk_put_prop_string(ctx, -2, itr->first_.CString());
  164. }
  165. itr++;
  166. }
  167. // pop self
  168. duk_pop(ctx);
  169. }
  170. duk_get_prop_string(ctx, -1, "component");
  171. if (!duk_is_function(ctx, -1))
  172. {
  173. duk_set_top(ctx, top);
  174. return;
  175. }
  176. // call with self
  177. js_push_class_object_instance(ctx, this, "JSComponent");
  178. if (duk_pcall(ctx, 1) != 0)
  179. {
  180. vm_->SendJSErrorEvent();
  181. duk_set_top(ctx, top);
  182. return;
  183. }
  184. duk_set_top(ctx, top);
  185. }
  186. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  187. {
  188. void* heapptr = JSGetHeapPtr();
  189. if (!heapptr)
  190. return;
  191. duk_context* ctx = vm_->GetJSContext();
  192. duk_idx_t top = duk_get_top(ctx);
  193. duk_push_heapptr(ctx, heapptr);
  194. duk_get_prop_string(ctx, -1, name.CString());
  195. if (!duk_is_function(ctx, -1))
  196. {
  197. duk_set_top(ctx, top);
  198. return;
  199. }
  200. if (passValue)
  201. duk_push_number(ctx, value);
  202. if (duk_pcall(ctx, passValue ? 1 : 0) != 0)
  203. {
  204. vm_->SendJSErrorEvent();
  205. duk_set_top(ctx, top);
  206. return;
  207. }
  208. duk_set_top(ctx, top);
  209. }
  210. void JSComponent::Start()
  211. {
  212. static String name = "start";
  213. CallScriptMethod(name);
  214. }
  215. void JSComponent::DelayedStart()
  216. {
  217. static String name = "delayedStart";
  218. CallScriptMethod(name);
  219. }
  220. void JSComponent::Update(float timeStep)
  221. {
  222. static String name = "update";
  223. CallScriptMethod(name, true, timeStep);
  224. }
  225. void JSComponent::PostUpdate(float timeStep)
  226. {
  227. static String name = "postUpdate";
  228. CallScriptMethod(name, true, timeStep);
  229. }
  230. void JSComponent::FixedUpdate(float timeStep)
  231. {
  232. static String name = "fixedUpdate";
  233. CallScriptMethod(name, true, timeStep);
  234. }
  235. void JSComponent::FixedPostUpdate(float timeStep)
  236. {
  237. static String name = "fixedPostUpdate";
  238. CallScriptMethod(name, true, timeStep);
  239. }
  240. void JSComponent::OnNodeSet(Node* node)
  241. {
  242. if (node)
  243. {
  244. // We have been attached to a node. Set initial update event subscription state
  245. UpdateEventSubscription();
  246. }
  247. else
  248. {
  249. // We are being detached from a node: execute user-defined stop function and prepare for destruction
  250. UpdateReferences(true);
  251. Stop();
  252. }
  253. }
  254. void JSComponent::UpdateEventSubscription()
  255. {
  256. // If scene node is not assigned yet, no need to update subscription
  257. if (!node_)
  258. return;
  259. Scene* scene = GetScene();
  260. if (!scene)
  261. {
  262. LOGWARNING("Node is detached from scene, can not subscribe to update events");
  263. return;
  264. }
  265. bool enabled = IsEnabledEffective();
  266. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  267. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  268. {
  269. SubscribeToEvent(scene, E_SCENEUPDATE, HANDLER(JSComponent, HandleSceneUpdate));
  270. currentEventMask_ |= USE_UPDATE;
  271. }
  272. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  273. {
  274. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  275. currentEventMask_ &= ~USE_UPDATE;
  276. }
  277. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  278. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  279. {
  280. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(JSComponent, HandleScenePostUpdate));
  281. currentEventMask_ |= USE_POSTUPDATE;
  282. }
  283. else if (!needUpdate && (currentEventMask_ & USE_POSTUPDATE))
  284. {
  285. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  286. currentEventMask_ &= ~USE_POSTUPDATE;
  287. }
  288. #ifdef ATOMIC_PHYSICS
  289. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  290. if (!world)
  291. return;
  292. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  293. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  294. {
  295. SubscribeToEvent(world, E_PHYSICSPRESTEP, HANDLER(JSComponent, HandlePhysicsPreStep));
  296. currentEventMask_ |= USE_FIXEDUPDATE;
  297. }
  298. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  299. {
  300. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  301. currentEventMask_ &= ~USE_FIXEDUPDATE;
  302. }
  303. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  304. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  305. {
  306. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, HANDLER(JSComponent, HandlePhysicsPostStep));
  307. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  308. }
  309. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  310. {
  311. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  312. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  313. }
  314. #endif
  315. }
  316. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  317. {
  318. using namespace SceneUpdate;
  319. if (!started_)
  320. {
  321. started_ = true;
  322. InitModule();
  323. Start();
  324. }
  325. // Execute user-defined delayed start function before first update
  326. if (!delayedStartCalled_)
  327. {
  328. DelayedStart();
  329. delayedStartCalled_ = true;
  330. // If did not need actual update events, unsubscribe now
  331. if (!(updateEventMask_ & USE_UPDATE))
  332. {
  333. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  334. currentEventMask_ &= ~USE_UPDATE;
  335. return;
  336. }
  337. }
  338. // Then execute user-defined update function
  339. Update(eventData[P_TIMESTEP].GetFloat());
  340. }
  341. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  342. {
  343. using namespace ScenePostUpdate;
  344. // Execute user-defined post-update function
  345. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  346. }
  347. #ifdef ATOMIC_PHYSICS
  348. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  349. {
  350. using namespace PhysicsPreStep;
  351. // Execute user-defined fixed update function
  352. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  353. }
  354. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  355. {
  356. using namespace PhysicsPostStep;
  357. // Execute user-defined fixed post-update function
  358. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  359. }
  360. #endif
  361. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  362. {
  363. loading_ = true;
  364. bool success = Component::Load(source, setInstanceDefault);
  365. loading_ = false;
  366. return success;
  367. }
  368. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  369. {
  370. loading_ = true;
  371. bool success = Component::LoadXML(source, setInstanceDefault);
  372. loading_ = false;
  373. return success;
  374. }
  375. void JSComponent::SetComponentFile(JSComponentFile* cfile, bool loading)
  376. {
  377. componentFile_ = cfile;
  378. }
  379. ResourceRef JSComponent::GetScriptAttr() const
  380. {
  381. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  382. }
  383. void JSComponent::SetScriptAttr(const ResourceRef& value)
  384. {
  385. ResourceCache* cache = GetSubsystem<ResourceCache>();
  386. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_), loading_);
  387. }
  388. }