JSComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/IO/Log.h>
  24. #include <Atomic/IO/FileSystem.h>
  25. #include <Atomic/Core/Context.h>
  26. #include <Atomic/Resource/ResourceCache.h>
  27. #ifdef ATOMIC_PHYSICS
  28. #include <Atomic/Physics/PhysicsEvents.h>
  29. #include <Atomic/Physics/PhysicsWorld.h>
  30. #endif
  31. #include <Atomic/Scene/Scene.h>
  32. #include <Atomic/Scene/SceneEvents.h>
  33. #include "JSVM.h"
  34. #include "JSComponentFile.h"
  35. #include "JSComponent.h"
  36. namespace Atomic
  37. {
  38. extern const char* LOGIC_CATEGORY;
  39. class JSComponentFactory : public ObjectFactory
  40. {
  41. ATOMIC_REFCOUNTED(JSComponentFactory)
  42. public:
  43. /// Construct.
  44. JSComponentFactory(Context* context) :
  45. ObjectFactory(context)
  46. {
  47. typeInfo_ = JSComponent::GetTypeInfoStatic();
  48. }
  49. /// Create an object of the specific type.
  50. SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY)
  51. {
  52. // if in editor, just create the JSComponent
  53. if (context_->GetEditorContext())
  54. {
  55. return SharedPtr<Object>(new JSComponent(context_));
  56. }
  57. // At runtime, a XML JSComponent may refer to a "scriptClass"
  58. // component which is new'd in JS and creates the component itself
  59. // we peek ahead here to see if we have a JSComponentFile and if it is a script class
  60. String componentRef;
  61. if (source != XMLElement::EMPTY)
  62. {
  63. XMLElement attrElem = source.GetChild("attribute");
  64. while (attrElem)
  65. {
  66. if (attrElem.GetAttribute("name") == "ComponentFile")
  67. {
  68. componentRef = attrElem.GetAttribute("value");
  69. break;
  70. }
  71. attrElem = attrElem.GetNext("attribute");
  72. }
  73. }
  74. SharedPtr<Object> ptr;
  75. if (componentRef.Length())
  76. {
  77. Vector<String> split = componentRef.Split(';');
  78. if (split.Size() == 2)
  79. {
  80. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  81. JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
  82. if (componentFile)
  83. ptr = componentFile->CreateJSComponent();
  84. else
  85. {
  86. ATOMIC_LOGERRORF("Unable to load component file %s", split[1].CString());
  87. }
  88. }
  89. }
  90. if (ptr.Null())
  91. {
  92. ptr = new JSComponent(context_);
  93. }
  94. return ptr;
  95. }
  96. };
  97. JSComponent::JSComponent(Context* context) :
  98. ScriptComponent(context),
  99. updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
  100. currentEventMask_(0),
  101. instanceInitialized_(false),
  102. started_(false),
  103. destroyed_(false),
  104. scriptClassInstance_(false),
  105. delayedStartCalled_(false),
  106. loading_(false)
  107. {
  108. vm_ = JSVM::GetJSVM(NULL);
  109. }
  110. JSComponent::~JSComponent()
  111. {
  112. }
  113. void JSComponent::RegisterObject(Context* context)
  114. {
  115. context->RegisterFactory( new JSComponentFactory(context), LOGIC_CATEGORY);
  116. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetComponentFileAttr, SetComponentFileAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
  117. ATOMIC_COPY_BASE_ATTRIBUTES(ScriptComponent);
  118. }
  119. void JSComponent::OnSetEnabled()
  120. {
  121. UpdateEventSubscription();
  122. }
  123. void JSComponent::SetUpdateEventMask(unsigned char mask)
  124. {
  125. if (updateEventMask_ != mask)
  126. {
  127. updateEventMask_ = mask;
  128. UpdateEventSubscription();
  129. }
  130. }
  131. void JSComponent::ApplyAttributes()
  132. {
  133. }
  134. bool JSComponent::IsInstanceInitialized() {
  135. return instanceInitialized_;
  136. }
  137. void JSComponent::InitInstance(bool hasArgs, int argIdx)
  138. {
  139. if (context_->GetEditorContext() || componentFile_.Null())
  140. return;
  141. duk_context* ctx = vm_->GetJSContext();
  142. duk_idx_t top = duk_get_top(ctx);
  143. // apply fields
  144. const FieldMap& fields = componentFile_->GetFields();
  145. if (fields.Size())
  146. {
  147. // push self
  148. js_push_class_object_instance(ctx, this, "JSComponent");
  149. FieldMap::ConstIterator itr = fields.Begin();
  150. while (itr != fields.End())
  151. {
  152. if (fieldValues_.Contains(itr->first_))
  153. {
  154. Variant& v = fieldValues_[itr->first_];
  155. if (v.GetType() == itr->second_.variantType_)
  156. {
  157. js_push_variant(ctx, v);
  158. duk_put_prop_string(ctx, -2, itr->first_.CString());
  159. }
  160. }
  161. else
  162. {
  163. Variant v;
  164. componentFile_->GetDefaultFieldValue(itr->first_, v);
  165. js_push_variant(ctx, v);
  166. duk_put_prop_string(ctx, -2, itr->first_.CString());
  167. }
  168. itr++;
  169. }
  170. // pop self
  171. duk_pop(ctx);
  172. }
  173. // apply args if any
  174. if (hasArgs)
  175. {
  176. // push self
  177. js_push_class_object_instance(ctx, this, "JSComponent");
  178. duk_enum(ctx, argIdx, DUK_ENUM_OWN_PROPERTIES_ONLY);
  179. while (duk_next(ctx, -1, 1)) {
  180. duk_put_prop(ctx, -4);
  181. }
  182. // pop self and enum object
  183. duk_pop_2(ctx);
  184. }
  185. if (!componentFile_->GetScriptClass())
  186. {
  187. componentFile_->PushModule();
  188. if (!duk_is_object(ctx, -1))
  189. {
  190. duk_set_top(ctx, top);
  191. return;
  192. }
  193. // Check for "default" constructor which is used by TypeScript and ES2015
  194. duk_get_prop_string(ctx, -1, "default");
  195. if (!duk_is_function(ctx, -1))
  196. {
  197. duk_pop(ctx);
  198. // If "default" doesn't exist, look for component
  199. duk_get_prop_string(ctx, -1, "component");
  200. if (!duk_is_function(ctx, -1))
  201. {
  202. duk_set_top(ctx, top);
  203. return;
  204. }
  205. }
  206. // call with self
  207. js_push_class_object_instance(ctx, this, "JSComponent");
  208. if (duk_pcall(ctx, 1) != 0)
  209. {
  210. vm_->SendJSErrorEvent();
  211. duk_set_top(ctx, top);
  212. return;
  213. }
  214. }
  215. duk_set_top(ctx, top);
  216. instanceInitialized_ = true;
  217. }
  218. void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
  219. {
  220. if (destroyed_ || !node_ || !node_->GetScene())
  221. return;
  222. void* heapptr = JSGetHeapPtr();
  223. if (!heapptr)
  224. return;
  225. duk_context* ctx = vm_->GetJSContext();
  226. duk_idx_t top = duk_get_top(ctx);
  227. duk_push_heapptr(ctx, heapptr);
  228. duk_get_prop_string(ctx, -1, name.CString());
  229. if (!duk_is_function(ctx, -1))
  230. {
  231. duk_set_top(ctx, top);
  232. return;
  233. }
  234. // push this
  235. if (scriptClassInstance_)
  236. duk_push_heapptr(ctx, heapptr);
  237. if (passValue)
  238. duk_push_number(ctx, value);
  239. int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
  240. if (status != 0)
  241. {
  242. vm_->SendJSErrorEvent();
  243. duk_set_top(ctx, top);
  244. return;
  245. }
  246. duk_set_top(ctx, top);
  247. }
  248. void JSComponent::Start()
  249. {
  250. static String name = "start";
  251. CallScriptMethod(name);
  252. }
  253. void JSComponent::DelayedStart()
  254. {
  255. static String name = "delayedStart";
  256. CallScriptMethod(name);
  257. }
  258. void JSComponent::Update(float timeStep)
  259. {
  260. if (!instanceInitialized_)
  261. InitInstance();
  262. if (!started_)
  263. {
  264. started_ = true;
  265. Start();
  266. }
  267. static String name = "update";
  268. CallScriptMethod(name, true, timeStep);
  269. }
  270. void JSComponent::PostUpdate(float timeStep)
  271. {
  272. static String name = "postUpdate";
  273. CallScriptMethod(name, true, timeStep);
  274. }
  275. void JSComponent::FixedUpdate(float timeStep)
  276. {
  277. static String name = "fixedUpdate";
  278. CallScriptMethod(name, true, timeStep);
  279. }
  280. void JSComponent::FixedPostUpdate(float timeStep)
  281. {
  282. static String name = "fixedPostUpdate";
  283. CallScriptMethod(name, true, timeStep);
  284. }
  285. void JSComponent::OnNodeSet(Node* node)
  286. {
  287. if (node)
  288. {
  289. }
  290. else
  291. {
  292. Stop();
  293. }
  294. }
  295. void JSComponent::OnSceneSet(Scene* scene)
  296. {
  297. if (scene)
  298. UpdateEventSubscription();
  299. else
  300. {
  301. UnsubscribeFromEvent(E_SCENEUPDATE);
  302. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  303. #ifdef ATOMIC_PHYSICS
  304. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  305. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  306. #endif
  307. currentEventMask_ = 0;
  308. }
  309. }
  310. void JSComponent::UpdateEventSubscription()
  311. {
  312. Scene* scene = GetScene();
  313. if (!scene)
  314. return;
  315. bool enabled = IsEnabledEffective();
  316. bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
  317. if (needUpdate && !(currentEventMask_ & USE_UPDATE))
  318. {
  319. SubscribeToEvent(scene, E_SCENEUPDATE, ATOMIC_HANDLER(JSComponent, HandleSceneUpdate));
  320. currentEventMask_ |= USE_UPDATE;
  321. }
  322. else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
  323. {
  324. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  325. currentEventMask_ &= ~USE_UPDATE;
  326. }
  327. bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
  328. if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
  329. {
  330. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(JSComponent, HandleScenePostUpdate));
  331. currentEventMask_ |= USE_POSTUPDATE;
  332. }
  333. else if (!needPostUpdate && (currentEventMask_ & USE_POSTUPDATE))
  334. {
  335. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  336. currentEventMask_ &= ~USE_POSTUPDATE;
  337. }
  338. #ifdef ATOMIC_PHYSICS
  339. PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
  340. if (!world)
  341. return;
  342. bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
  343. if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
  344. {
  345. SubscribeToEvent(world, E_PHYSICSPRESTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPreStep));
  346. currentEventMask_ |= USE_FIXEDUPDATE;
  347. }
  348. else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
  349. {
  350. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  351. currentEventMask_ &= ~USE_FIXEDUPDATE;
  352. }
  353. bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
  354. if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
  355. {
  356. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPostStep));
  357. currentEventMask_ |= USE_FIXEDPOSTUPDATE;
  358. }
  359. else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
  360. {
  361. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  362. currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
  363. }
  364. #endif
  365. }
  366. void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  367. {
  368. using namespace SceneUpdate;
  369. assert(!destroyed_);
  370. // Execute user-defined delayed start function before first update
  371. if (!delayedStartCalled_)
  372. {
  373. DelayedStart();
  374. delayedStartCalled_ = true;
  375. // If did not need actual update events, unsubscribe now
  376. if (!(updateEventMask_ & USE_UPDATE))
  377. {
  378. UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
  379. currentEventMask_ &= ~USE_UPDATE;
  380. return;
  381. }
  382. }
  383. // Then execute user-defined update function
  384. Update(eventData[P_TIMESTEP].GetFloat());
  385. }
  386. void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  387. {
  388. using namespace ScenePostUpdate;
  389. // Execute user-defined post-update function
  390. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  391. }
  392. #ifdef ATOMIC_PHYSICS
  393. void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  394. {
  395. using namespace PhysicsPreStep;
  396. // Execute user-defined fixed update function
  397. FixedUpdate(eventData[P_TIMESTEP].GetFloat());
  398. }
  399. void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  400. {
  401. using namespace PhysicsPostStep;
  402. // Execute user-defined fixed post-update function
  403. FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
  404. }
  405. #endif
  406. bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
  407. {
  408. loading_ = true;
  409. bool success = Component::Load(source, setInstanceDefault);
  410. loading_ = false;
  411. return success;
  412. }
  413. bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
  414. {
  415. loading_ = true;
  416. bool success = Component::LoadXML(source, setInstanceDefault);
  417. loading_ = false;
  418. return success;
  419. }
  420. bool JSComponent::MatchScriptName(const String& path)
  421. {
  422. if (componentFile_.Null())
  423. return false;
  424. String _path = path;
  425. _path.Replace(".js", "", false);
  426. const String& name = componentFile_->GetName();
  427. if (_path == name)
  428. return true;
  429. String pathName, fileName, ext;
  430. SplitPath(name, pathName, fileName, ext);
  431. if (fileName == _path)
  432. return true;
  433. return false;
  434. }
  435. ResourceRef JSComponent::GetComponentFileAttr() const
  436. {
  437. return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
  438. }
  439. void JSComponent::SetComponentFileAttr(const ResourceRef& value)
  440. {
  441. ResourceCache* cache = GetSubsystem<ResourceCache>();
  442. SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
  443. }
  444. }