RegisterArray.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  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 "Precompiled.h"
  24. #include "Exception.h"
  25. #include "RegisterArray.h"
  26. #include <cstring>
  27. #include "DebugNew.h"
  28. // Adapted from Angelscript's scriptarray add-on, but with garbage collection disabled
  29. //! Script array buffer
  30. struct SArrayBuffer
  31. {
  32. asDWORD numElements;
  33. asBYTE data[1];
  34. };
  35. static CScriptArray* ScriptArrayFactory2(asIObjectType* ot, asUINT length)
  36. {
  37. CScriptArray* a = new CScriptArray(length, ot);
  38. // It's possible the constructor raised a script exception, in which case we
  39. // need to free the memory and return null instead, else we get a memory leak.
  40. asIScriptContext* context = asGetActiveContext();
  41. if (context && context->GetState() == asEXECUTION_EXCEPTION)
  42. {
  43. delete a;
  44. return 0;
  45. }
  46. return a;
  47. }
  48. static CScriptArray* ScriptArrayFactoryDefVal(asIObjectType* ot, asUINT length, void* defVal)
  49. {
  50. CScriptArray* a = new CScriptArray(length, defVal, ot);
  51. // It's possible the constructor raised a script exception, in which case we
  52. // need to free the memory and return null instead, else we get a memory leak.
  53. asIScriptContext* context = asGetActiveContext();
  54. if (context && context->GetState() == asEXECUTION_EXCEPTION)
  55. {
  56. delete a;
  57. return 0;
  58. }
  59. return a;
  60. }
  61. static CScriptArray* ScriptArrayFactory(asIObjectType* ot)
  62. {
  63. return ScriptArrayFactory2(ot, 0);
  64. }
  65. // This optional callback is called when the template type is first used by the compiler.
  66. // It allows the application to validate if the template can be instanciated for the requested
  67. // subtype at compile time, instead of at runtime.
  68. static bool ScriptArrayTemplateCallback(asIObjectType* ot)
  69. {
  70. // Make sure the subtype can be instanciated with a default factory/constructor,
  71. // otherwise we won't be able to instanciate the elements. Script classes always
  72. // have default factories, so we don't have to worry about those.
  73. int typeId = ot->GetSubTypeId();
  74. if ((typeId & asTYPEID_MASK_OBJECT) && !(typeId & asTYPEID_OBJHANDLE) && !(typeId & asTYPEID_SCRIPTOBJECT))
  75. {
  76. asIObjectType *subtype = ot->GetEngine()->GetObjectTypeById(typeId);
  77. asDWORD flags = subtype->GetFlags();
  78. if ((flags & asOBJ_VALUE) && !(flags & asOBJ_POD))
  79. {
  80. // Verify that there is a default constructor
  81. for (int n = 0; n < subtype->GetBehaviourCount(); ++n)
  82. {
  83. asEBehaviours beh;
  84. int funcId = subtype->GetBehaviourByIndex(n, &beh);
  85. if (beh != asBEHAVE_CONSTRUCT)
  86. continue;
  87. asIScriptFunction* func = ot->GetEngine()->GetFunctionDescriptorById(funcId);
  88. if (func->GetParamCount() == 0)
  89. {
  90. // Found the default constructor
  91. return true;
  92. }
  93. }
  94. // There is no default constructor
  95. return false;
  96. }
  97. else if ((flags & asOBJ_REF))
  98. {
  99. // Verify that there is a default factory
  100. for (int n = 0; n < subtype->GetFactoryCount(); ++n)
  101. {
  102. int funcId = subtype->GetFactoryIdByIndex(n);
  103. asIScriptFunction* func = ot->GetEngine()->GetFunctionDescriptorById(funcId);
  104. if (func->GetParamCount() == 0)
  105. {
  106. // Found the default factory
  107. return true;
  108. }
  109. }
  110. // No default factory
  111. return false;
  112. }
  113. }
  114. // The type is ok
  115. return true;
  116. }
  117. CScriptArray& CScriptArray::operator = (const CScriptArray &other)
  118. {
  119. // Only perform the copy if the array types are the same
  120. if (&other != this && other.GetArrayObjectType() == GetArrayObjectType())
  121. {
  122. if (buffer)
  123. {
  124. DeleteBuffer(buffer);
  125. buffer = 0;
  126. }
  127. // Copy all elements from the other array
  128. CreateBuffer(&buffer, other.buffer->numElements);
  129. CopyBuffer(buffer, other.buffer);
  130. }
  131. return *this;
  132. }
  133. CScriptArray::CScriptArray(asUINT length, asIObjectType* ot)
  134. {
  135. refCount = 1;
  136. gcFlag = false;
  137. objType = ot;
  138. objType->AddRef();
  139. buffer = 0;
  140. // Determine element size
  141. // TODO: Should probably store the template sub type id as well
  142. int typeId = objType->GetSubTypeId();
  143. if (typeId & asTYPEID_MASK_OBJECT)
  144. elementSize = sizeof(asPWORD);
  145. else
  146. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(typeId);
  147. isArrayOfHandles = typeId & asTYPEID_OBJHANDLE ? true : false;
  148. // Make sure the array size isn't too large for us to handle
  149. if (!CheckMaxSize(length))
  150. {
  151. // Don't continue with the initialization
  152. return;
  153. }
  154. CreateBuffer(&buffer, length);
  155. }
  156. CScriptArray::CScriptArray(asUINT length, void *defVal, asIObjectType *ot)
  157. {
  158. refCount = 1;
  159. gcFlag = false;
  160. objType = ot;
  161. objType->AddRef();
  162. buffer = 0;
  163. // Determine element size
  164. // TODO: Should probably store the template sub type id as well
  165. int typeId = objType->GetSubTypeId();
  166. if (typeId & asTYPEID_MASK_OBJECT)
  167. elementSize = sizeof(asPWORD);
  168. else
  169. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(typeId);
  170. isArrayOfHandles = typeId & asTYPEID_OBJHANDLE ? true : false;
  171. // Make sure the array size isn't too large for us to handle
  172. if (!CheckMaxSize(length))
  173. {
  174. // Don't continue with the initialization
  175. return;
  176. }
  177. CreateBuffer(&buffer, length);
  178. // Initialize the elements with the default value
  179. for (asUINT n = 0; n < GetSize(); ++n)
  180. SetValue(n, defVal);
  181. }
  182. // Internal
  183. void CScriptArray::SetValue(asUINT index, void *value)
  184. {
  185. int typeId = objType->GetSubTypeId();
  186. if ((typeId & ~0x03FFFFFF) && !(typeId & asTYPEID_OBJHANDLE))
  187. objType->GetEngine()->CopyScriptObject(At(index), value, typeId);
  188. else if (typeId & asTYPEID_OBJHANDLE)
  189. {
  190. *(void**)At(index) = *(void**)value;
  191. objType->GetEngine()->AddRefScriptObject(*(void**)value, typeId);
  192. }
  193. else if (typeId == asTYPEID_BOOL || typeId == asTYPEID_INT8 || typeId == asTYPEID_UINT8)
  194. *(char*)At(index) = *(char*)value;
  195. else if (typeId == asTYPEID_INT16 || typeId == asTYPEID_UINT16)
  196. *(short*)At(index) = *(short*)value;
  197. else if (typeId == asTYPEID_INT32 || typeId == asTYPEID_UINT32 || typeId == asTYPEID_FLOAT)
  198. *(int*)At(index) = *(int*)value;
  199. else if (typeId == asTYPEID_INT64 || typeId == asTYPEID_UINT64 || typeId == asTYPEID_DOUBLE)
  200. *(double*)At(index) = *(double*)value;
  201. }
  202. CScriptArray::~CScriptArray()
  203. {
  204. if (buffer)
  205. {
  206. DeleteBuffer(buffer);
  207. buffer = 0;
  208. }
  209. if (objType)
  210. objType->Release();
  211. }
  212. asUINT CScriptArray::GetSize() const
  213. {
  214. return buffer->numElements;
  215. }
  216. void CScriptArray::Resize(asUINT numElements)
  217. {
  218. if (numElements & 0x80000000)
  219. {
  220. CheckMaxSize(numElements);
  221. return;
  222. }
  223. Resize((int)numElements - (int)buffer->numElements, -1);
  224. }
  225. // Internal
  226. void CScriptArray::Resize(int delta, asUINT at)
  227. {
  228. if (delta < 0)
  229. {
  230. if (-delta > (int)buffer->numElements)
  231. delta = -(int)buffer->numElements;
  232. if (at > buffer->numElements + delta)
  233. at = buffer->numElements + delta;
  234. }
  235. else if (delta > 0)
  236. {
  237. // Make sure the array size isn't too large for us to handle
  238. if (delta > 0 && !CheckMaxSize(buffer->numElements + delta))
  239. return;
  240. if (at > buffer->numElements)
  241. at = buffer->numElements;
  242. }
  243. if (delta == 0)
  244. return;
  245. // Allocate memory for the buffer
  246. SArrayBuffer *newBuffer;
  247. newBuffer = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)];
  248. newBuffer->numElements = buffer->numElements + delta;
  249. int c = newBuffer->numElements > buffer->numElements ? buffer->numElements : newBuffer->numElements;
  250. memcpy(newBuffer->data, buffer->data, at*elementSize);
  251. if (delta > 0 && at < buffer->numElements)
  252. memcpy(newBuffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements-at)*elementSize);
  253. else if (delta < 0 && at < buffer->numElements)
  254. memcpy(newBuffer->data + at*elementSize, buffer->data + (at-delta)*elementSize, (buffer->numElements-at+delta)*elementSize);
  255. int typeId = objType->GetSubTypeId();
  256. if (typeId & asTYPEID_MASK_OBJECT)
  257. {
  258. if (delta > 0)
  259. Construct(newBuffer, at, at+delta);
  260. else if (delta < 0)
  261. Destruct(buffer, at, at-delta);
  262. }
  263. // Release the old buffer
  264. delete[] (asBYTE*)buffer;
  265. buffer = newBuffer;
  266. }
  267. // internal
  268. bool CScriptArray::CheckMaxSize(asUINT numElements)
  269. {
  270. // This code makes sure the size of the buffer that is allocated
  271. // for the array doesn't overflow and becomes smaller than requested
  272. asUINT maxSize = 0xFFFFFFFFul - sizeof(SArrayBuffer) + 1;
  273. if (objType->GetSubTypeId() & asTYPEID_MASK_OBJECT)
  274. maxSize /= sizeof(void*);
  275. else
  276. maxSize /= elementSize;
  277. if (numElements > maxSize)
  278. SAFE_EXCEPTION_RET("Too large array size", false);
  279. // OK
  280. return true;
  281. }
  282. asIObjectType *CScriptArray::GetArrayObjectType() const
  283. {
  284. return objType;
  285. }
  286. int CScriptArray::GetArrayTypeId() const
  287. {
  288. return objType->GetTypeId();
  289. }
  290. int CScriptArray::GetElementTypeId() const
  291. {
  292. return objType->GetSubTypeId();
  293. }
  294. void CScriptArray::InsertAt(asUINT index, void *value)
  295. {
  296. if (index > buffer->numElements)
  297. SAFE_EXCEPTION("Index out of bounds");
  298. // Make room for the new element
  299. Resize(1, index);
  300. // Set the value of the new element
  301. SetValue(index, value);
  302. }
  303. void CScriptArray::InsertLast(void *value)
  304. {
  305. InsertAt(buffer->numElements, value);
  306. }
  307. void CScriptArray::RemoveAt(asUINT index)
  308. {
  309. if (index >= buffer->numElements)
  310. SAFE_EXCEPTION("Index out of bounds");
  311. // Remove the element
  312. Resize(-1, index);
  313. }
  314. void CScriptArray::RemoveLast()
  315. {
  316. RemoveAt(buffer->numElements-1);
  317. }
  318. // Return a pointer to the array element. Returns 0 if the index is out of bounds
  319. void *CScriptArray::At(asUINT index)
  320. {
  321. if (index >= buffer->numElements)
  322. {
  323. SAFE_EXCEPTION_RET("Index out of bounds", 0);
  324. }
  325. else
  326. {
  327. int typeId = objType->GetSubTypeId();
  328. if ((typeId & asTYPEID_MASK_OBJECT) && !isArrayOfHandles)
  329. return (void*)((size_t*)buffer->data)[index];
  330. else
  331. return buffer->data + elementSize*index;
  332. }
  333. }
  334. // internal
  335. void CScriptArray::CreateBuffer(SArrayBuffer **buf, asUINT numElements)
  336. {
  337. int typeId = objType->GetSubTypeId();
  338. if (typeId & asTYPEID_MASK_OBJECT)
  339. {
  340. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+sizeof(void*)*numElements];
  341. (*buf)->numElements = numElements;
  342. }
  343. else
  344. {
  345. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+elementSize*numElements];
  346. (*buf)->numElements = numElements;
  347. }
  348. Construct(*buf, 0, numElements);
  349. }
  350. // internal
  351. void CScriptArray::DeleteBuffer(SArrayBuffer *buf)
  352. {
  353. Destruct(buf, 0, buf->numElements);
  354. // Free the buffer
  355. delete[] (asBYTE*)buf;
  356. }
  357. // internal
  358. void CScriptArray::Construct(SArrayBuffer *buf, asUINT start, asUINT end)
  359. {
  360. int typeId = objType->GetSubTypeId();
  361. if (isArrayOfHandles)
  362. {
  363. // Set all object handles to null
  364. void* d = (void*)(buf->data + start * sizeof(void*));
  365. memset(d, 0, (end-start)*sizeof(void*));
  366. }
  367. else if (typeId & asTYPEID_MASK_OBJECT)
  368. {
  369. void** max = (void**)(buf->data + end * sizeof(void*));
  370. void** d = (void**)(buf->data + start * sizeof(void*));
  371. asIScriptEngine* engine = objType->GetEngine();
  372. for (; d < max; d++)
  373. *d = (void*)engine->CreateScriptObject(typeId);
  374. }
  375. }
  376. // internal
  377. void CScriptArray::Destruct(SArrayBuffer *buf, asUINT start, asUINT end)
  378. {
  379. int typeId = objType->GetSubTypeId();
  380. if (typeId & asTYPEID_MASK_OBJECT)
  381. {
  382. asIScriptEngine* engine = objType->GetEngine();
  383. void** max = (void**)(buf->data + end * sizeof(void*));
  384. void** d = (void**)(buf->data + start * sizeof(void*));
  385. for(; d < max; d++ )
  386. {
  387. if( *d )
  388. engine->ReleaseScriptObject(*d, typeId);
  389. }
  390. }
  391. }
  392. // internal
  393. void CScriptArray::CopyBuffer(SArrayBuffer *dst, SArrayBuffer *src)
  394. {
  395. asIScriptEngine* engine = objType->GetEngine();
  396. if(isArrayOfHandles)
  397. {
  398. // Copy the references and increase the reference counters
  399. if (dst->numElements > 0 && src->numElements > 0)
  400. {
  401. int typeId = objType->GetSubTypeId();
  402. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  403. void** max = (void**)(dst->data + count * sizeof(void*));
  404. void** d = (void**)dst->data;
  405. void** s = (void**)src->data;
  406. for (; d < max; d++, s++)
  407. {
  408. *d = *s;
  409. if (*d)
  410. engine->AddRefScriptObject(*d, typeId);
  411. }
  412. }
  413. }
  414. else
  415. {
  416. int typeId = objType->GetSubTypeId();
  417. if (dst->numElements > 0 && src->numElements > 0)
  418. {
  419. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  420. if (typeId & asTYPEID_MASK_OBJECT)
  421. {
  422. // Call the assignment operator on all of the objects
  423. void** max = (void**)(dst->data + count * sizeof(void*));
  424. void** d = (void**)dst->data;
  425. void** s = (void**)src->data;
  426. for(; d < max; d++, s++)
  427. engine->CopyScriptObject(*d, *s, typeId);
  428. }
  429. else
  430. {
  431. // Primitives are copied byte for byte
  432. memcpy(dst->data, src->data, count*elementSize);
  433. }
  434. }
  435. }
  436. }
  437. void CScriptArray::AddRef() const
  438. {
  439. // Clear the GC flag then increase the counter
  440. gcFlag = false;
  441. refCount++;
  442. }
  443. void CScriptArray::Release() const
  444. {
  445. // Now do the actual releasing (clearing the flag set by GC)
  446. gcFlag = false;
  447. if (--refCount == 0)
  448. delete this;
  449. }
  450. // Registers the template array type
  451. void registerArray(asIScriptEngine* engine)
  452. {
  453. engine->RegisterObjectType("array<class T>", 0, asOBJ_REF | asOBJ_TEMPLATE);
  454. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int&in)", asFUNCTION(ScriptArrayTemplateCallback), asCALL_CDECL);
  455. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_FACTORY, "array<T>@ f(int& in)", asFUNCTIONPR(ScriptArrayFactory, (asIObjectType*), CScriptArray*), asCALL_CDECL);
  456. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_FACTORY, "array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  457. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_FACTORY, "array<T>@ f(int& in, uint, const T& in)", asFUNCTIONPR(ScriptArrayFactoryDefVal, (asIObjectType*, asUINT, void *), CScriptArray*), asCALL_CDECL);
  458. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_LIST_FACTORY, "array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  459. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptArray,AddRef), asCALL_THISCALL);
  460. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptArray,Release), asCALL_THISCALL);
  461. engine->RegisterObjectMethod("array<T>", "T& opIndex(uint)", asMETHOD(CScriptArray, At), asCALL_THISCALL);
  462. engine->RegisterObjectMethod("array<T>", "const T& opIndex(uint) const", asMETHOD(CScriptArray, At), asCALL_THISCALL);
  463. engine->RegisterObjectMethod("array<T>", "array<T> &opAssign(const array<T>& in)", asMETHOD(CScriptArray, operator=), asCALL_THISCALL);
  464. engine->RegisterObjectMethod("array<T>", "void insertAt(uint, const T& in)", asMETHOD(CScriptArray, InsertAt), asCALL_THISCALL);
  465. engine->RegisterObjectMethod("array<T>", "void removeAt(uint)", asMETHOD(CScriptArray, RemoveAt), asCALL_THISCALL);
  466. engine->RegisterObjectMethod("array<T>", "void insertLast(const T& in)", asMETHOD(CScriptArray, InsertLast), asCALL_THISCALL);
  467. engine->RegisterObjectMethod("array<T>", "void removeLast()", asMETHOD(CScriptArray, RemoveLast), asCALL_THISCALL);
  468. engine->RegisterObjectMethod("array<T>", "uint length() const", asMETHOD(CScriptArray, GetSize), asCALL_THISCALL);
  469. engine->RegisterObjectMethod("array<T>", "void resize(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  470. engine->RegisterDefaultArrayType("array<T>");
  471. }