Addons.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203
  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. #include "Precompiled.h"
  23. #include "Addons.h"
  24. #include <cstring>
  25. #include <new>
  26. #include <stdio.h>
  27. // Adapted from Angelscript's scriptarray & scriptstdstring add-ons, but with garbage collection disabled
  28. namespace Urho3D
  29. {
  30. using namespace std;
  31. /// %Script array buffer.
  32. struct SArrayBuffer
  33. {
  34. asDWORD maxElements;
  35. asDWORD numElements;
  36. asBYTE data[1];
  37. };
  38. /// %Script array cache.
  39. struct SArrayCache
  40. {
  41. asIScriptFunction *cmpFunc;
  42. asIScriptFunction *eqFunc;
  43. int cmpFuncReturnCode; // To allow better error message in case of multiple matches
  44. int eqFuncReturnCode;
  45. };
  46. // We just define a number here that we assume nobody else is using for
  47. // object type user data. The add-ons have reserved the numbers 1000
  48. // through 1999 for this purpose, so we should be fine.
  49. const asPWORD ARRAY_CACHE = 1000;
  50. static void CleanupObjectTypeArrayCache(asIObjectType *type)
  51. {
  52. SArrayCache *cache = reinterpret_cast<SArrayCache*>(type->GetUserData(ARRAY_CACHE));
  53. if( cache )
  54. delete cache;
  55. }
  56. static CScriptArray* ScriptArrayFactory2(asIObjectType *ot, asUINT length)
  57. {
  58. CScriptArray *a = new CScriptArray(length, ot);
  59. // It's possible the constructor raised a script exception, in which case we
  60. // need to free the memory and return null instead, else we get a memory leak.
  61. asIScriptContext *ctx = asGetActiveContext();
  62. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  63. {
  64. a->Release();
  65. return 0;
  66. }
  67. return a;
  68. }
  69. static CScriptArray* ScriptArrayListFactory(asIObjectType *ot, void *initList)
  70. {
  71. CScriptArray *a = new CScriptArray(ot, initList);
  72. // It's possible the constructor raised a script exception, in which case we
  73. // need to free the memory and return null instead, else we get a memory leak.
  74. asIScriptContext *ctx = asGetActiveContext();
  75. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  76. {
  77. a->Release();
  78. return 0;
  79. }
  80. return a;
  81. }
  82. static CScriptArray* ScriptArrayFactoryDefVal(asIObjectType *ot, asUINT length, void *defVal)
  83. {
  84. CScriptArray *a = new CScriptArray(length, defVal, ot);
  85. // It's possible the constructor raised a script exception, in which case we
  86. // need to free the memory and return null instead, else we get a memory leak.
  87. asIScriptContext *ctx = asGetActiveContext();
  88. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  89. {
  90. a->Release();
  91. return 0;
  92. }
  93. return a;
  94. }
  95. static CScriptArray* ScriptArrayFactory(asIObjectType *ot)
  96. {
  97. return ScriptArrayFactory2(ot, 0);
  98. }
  99. // This optional callback is called when the template type is first used by the compiler.
  100. // It allows the application to validate if the template can be instanciated for the requested
  101. // subtype at compile time, instead of at runtime. The output argument dontGarbageCollect
  102. // allow the callback to tell the engine if the template instance type shouldn't be garbage collected,
  103. // i.e. no asOBJ_GC flag.
  104. static bool ScriptArrayTemplateCallback(asIObjectType *ot, bool &dontGarbageCollect)
  105. {
  106. // Urho3D: nothing is garbage collected
  107. dontGarbageCollect = true;
  108. // Make sure the subtype can be instanciated with a default factory/constructor,
  109. // otherwise we won't be able to instanciate the elements.
  110. int typeId = ot->GetSubTypeId();
  111. if( typeId == asTYPEID_VOID )
  112. return false;
  113. if( (typeId & asTYPEID_MASK_OBJECT) && !(typeId & asTYPEID_OBJHANDLE) )
  114. {
  115. asIObjectType *subtype = ot->GetEngine()->GetObjectTypeById(typeId);
  116. asDWORD flags = subtype->GetFlags();
  117. if( (flags & asOBJ_VALUE) && !(flags & asOBJ_POD) )
  118. {
  119. // Verify that there is a default constructor
  120. bool found = false;
  121. for( asUINT n = 0; n < subtype->GetBehaviourCount(); n++ )
  122. {
  123. asEBehaviours beh;
  124. asIScriptFunction *func = subtype->GetBehaviourByIndex(n, &beh);
  125. if( beh != asBEHAVE_CONSTRUCT ) continue;
  126. if( func->GetParamCount() == 0 )
  127. {
  128. // Found the default constructor
  129. found = true;
  130. break;
  131. }
  132. }
  133. if( !found )
  134. {
  135. // There is no default constructor
  136. return false;
  137. }
  138. }
  139. else if( (flags & asOBJ_REF) )
  140. {
  141. bool found = false;
  142. // If value assignment for ref type has been disabled then the array
  143. // can be created if the type has a default factory function
  144. if( !ot->GetEngine()->GetEngineProperty(asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE) )
  145. {
  146. // Verify that there is a default factory
  147. for( asUINT n = 0; n < subtype->GetFactoryCount(); n++ )
  148. {
  149. asIScriptFunction *func = subtype->GetFactoryByIndex(n);
  150. if( func->GetParamCount() == 0 )
  151. {
  152. // Found the default factory
  153. found = true;
  154. break;
  155. }
  156. }
  157. }
  158. if( !found )
  159. {
  160. // No default factory
  161. return false;
  162. }
  163. }
  164. // If the object type is not garbage collected then the array also doesn't need to be
  165. if( !(flags & asOBJ_GC) )
  166. dontGarbageCollect = true;
  167. }
  168. else if( !(typeId & asTYPEID_OBJHANDLE) )
  169. {
  170. // Arrays with primitives cannot form circular references,
  171. // thus there is no need to garbage collect them
  172. dontGarbageCollect = true;
  173. }
  174. // The type is ok
  175. return true;
  176. }
  177. CScriptArray &CScriptArray::operator=(const CScriptArray &other)
  178. {
  179. // Only perform the copy if the array types are the same
  180. if( &other != this &&
  181. other.GetArrayObjectType() == GetArrayObjectType() )
  182. {
  183. // Make sure the arrays are of the same size
  184. Resize(other.buffer->numElements);
  185. // Copy the value of each element
  186. CopyBuffer(buffer, other.buffer);
  187. }
  188. return *this;
  189. }
  190. CScriptArray::CScriptArray(asIObjectType *ot, void *buf)
  191. {
  192. refCount = 1;
  193. gcFlag = false;
  194. objType = ot;
  195. objType->AddRef();
  196. buffer = 0;
  197. Precache();
  198. asIScriptEngine *engine = ot->GetEngine();
  199. // Determine element size
  200. if( subTypeId & asTYPEID_MASK_OBJECT )
  201. elementSize = sizeof(asPWORD);
  202. else
  203. elementSize = engine->GetSizeOfPrimitiveType(subTypeId);
  204. // Determine the initial size from the buffer
  205. asUINT length = *(asUINT*)buf;
  206. // Make sure the array size isn't too large for us to handle
  207. if( !CheckMaxSize(length) )
  208. {
  209. // Don't continue with the initialization
  210. return;
  211. }
  212. // Copy the values of the array elements from the buffer
  213. if( (ot->GetSubTypeId() & asTYPEID_MASK_OBJECT) == 0 )
  214. {
  215. CreateBuffer(&buffer, length);
  216. // Copy the values of the primitive type into the internal buffer
  217. memcpy(At(0), (((asUINT*)buf)+1), length * elementSize);
  218. }
  219. else if( ot->GetSubTypeId() & asTYPEID_OBJHANDLE )
  220. {
  221. CreateBuffer(&buffer, length);
  222. // Copy the handles into the internal buffer
  223. memcpy(At(0), (((asUINT*)buf)+1), length * elementSize);
  224. // With object handles it is safe to clear the memory in the received buffer
  225. // instead of increasing the ref count. It will save time both by avoiding the
  226. // call the increase ref, and also relieve the engine from having to release
  227. // its references too
  228. memset((((asUINT*)buf)+1), 0, length * elementSize);
  229. }
  230. else if( ot->GetSubType()->GetFlags() & asOBJ_REF )
  231. {
  232. // Only allocate the buffer, but not the objects
  233. subTypeId |= asTYPEID_OBJHANDLE;
  234. CreateBuffer(&buffer, length);
  235. subTypeId &= ~asTYPEID_OBJHANDLE;
  236. // Copy the handles into the internal buffer
  237. memcpy(buffer->data, (((asUINT*)buf)+1), length * elementSize);
  238. // For ref types we can do the same as for handles, as they are
  239. // implicitly stored as handles.
  240. memset((((asUINT*)buf)+1), 0, length * elementSize);
  241. }
  242. else
  243. {
  244. // TODO: Optimize by calling the copy constructor of the object instead of
  245. // constructing with the default constructor and then assigning the value
  246. // TODO: With C++11 ideally we should be calling the move constructor, instead
  247. // of the copy constructor as the engine will just discard the objects in the
  248. // buffer afterwards.
  249. CreateBuffer(&buffer, length);
  250. // For value types we need to call the opAssign for each individual object
  251. for( asUINT n = 0; n < length; n++ )
  252. {
  253. void *obj = At(n);
  254. asBYTE *srcObj = (asBYTE*)buf;
  255. srcObj += 4 + n*ot->GetSubType()->GetSize();
  256. engine->AssignScriptObject(obj, srcObj, ot->GetSubType());
  257. }
  258. }
  259. // Urho3D: garbage collection disabled
  260. /*
  261. // Notify the GC of the successful creation
  262. if( objType->GetFlags() & asOBJ_GC )
  263. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  264. */
  265. }
  266. CScriptArray::CScriptArray(asUINT length, asIObjectType *ot)
  267. {
  268. refCount = 1;
  269. gcFlag = false;
  270. objType = ot;
  271. objType->AddRef();
  272. buffer = 0;
  273. Precache();
  274. // Determine element size
  275. if( subTypeId & asTYPEID_MASK_OBJECT )
  276. elementSize = sizeof(asPWORD);
  277. else
  278. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(subTypeId);
  279. // Make sure the array size isn't too large for us to handle
  280. if( !CheckMaxSize(length) )
  281. {
  282. // Don't continue with the initialization
  283. return;
  284. }
  285. CreateBuffer(&buffer, length);
  286. // Urho3D: garbage collection disabled
  287. /*
  288. // Notify the GC of the successful creation
  289. if( objType->GetFlags() & asOBJ_GC )
  290. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  291. */
  292. }
  293. CScriptArray::CScriptArray(const CScriptArray &other)
  294. {
  295. refCount = 1;
  296. gcFlag = false;
  297. objType = other.objType;
  298. objType->AddRef();
  299. buffer = 0;
  300. Precache();
  301. elementSize = other.elementSize;
  302. // Urho3D: garbage collection disabled
  303. /*
  304. if( objType->GetFlags() & asOBJ_GC )
  305. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  306. */
  307. CreateBuffer(&buffer, 0);
  308. // Copy the content
  309. *this = other;
  310. }
  311. CScriptArray::CScriptArray(asUINT length, void *defVal, asIObjectType *ot)
  312. {
  313. refCount = 1;
  314. gcFlag = false;
  315. objType = ot;
  316. objType->AddRef();
  317. buffer = 0;
  318. Precache();
  319. // Determine element size
  320. if( subTypeId & asTYPEID_MASK_OBJECT )
  321. elementSize = sizeof(asPWORD);
  322. else
  323. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(subTypeId);
  324. // Make sure the array size isn't too large for us to handle
  325. if( !CheckMaxSize(length) )
  326. {
  327. // Don't continue with the initialization
  328. return;
  329. }
  330. CreateBuffer(&buffer, length);
  331. // Urho3D: garbage collection disabled
  332. /*
  333. // Notify the GC of the successful creation
  334. if( objType->GetFlags() & asOBJ_GC )
  335. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  336. */
  337. // Initialize the elements with the default value
  338. for( asUINT n = 0; n < GetSize(); n++ )
  339. SetValue(n, defVal);
  340. }
  341. void CScriptArray::SetValue(asUINT index, void *value)
  342. {
  343. // At() will take care of the out-of-bounds checking, though
  344. // if called from the application then nothing will be done
  345. void *ptr = At(index);
  346. if( ptr == 0 ) return;
  347. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  348. objType->GetEngine()->AssignScriptObject(ptr, value, objType->GetSubType());
  349. else if( subTypeId & asTYPEID_OBJHANDLE )
  350. {
  351. void *tmp = *(void**)ptr;
  352. *(void**)ptr = *(void**)value;
  353. objType->GetEngine()->AddRefScriptObject(*(void**)value, objType->GetSubType());
  354. if( tmp )
  355. objType->GetEngine()->ReleaseScriptObject(tmp, objType->GetSubType());
  356. }
  357. else if( subTypeId == asTYPEID_BOOL ||
  358. subTypeId == asTYPEID_INT8 ||
  359. subTypeId == asTYPEID_UINT8 )
  360. *(char*)ptr = *(char*)value;
  361. else if( subTypeId == asTYPEID_INT16 ||
  362. subTypeId == asTYPEID_UINT16 )
  363. *(short*)ptr = *(short*)value;
  364. else if( subTypeId == asTYPEID_INT32 ||
  365. subTypeId == asTYPEID_UINT32 ||
  366. subTypeId == asTYPEID_FLOAT ||
  367. subTypeId > asTYPEID_DOUBLE ) // enums have a type id larger than doubles
  368. *(int*)ptr = *(int*)value;
  369. else if( subTypeId == asTYPEID_INT64 ||
  370. subTypeId == asTYPEID_UINT64 ||
  371. subTypeId == asTYPEID_DOUBLE )
  372. *(double*)ptr = *(double*)value;
  373. }
  374. CScriptArray::~CScriptArray()
  375. {
  376. if( buffer )
  377. {
  378. DeleteBuffer(buffer);
  379. buffer = 0;
  380. }
  381. if( objType ) objType->Release();
  382. }
  383. asUINT CScriptArray::GetSize() const
  384. {
  385. return buffer->numElements;
  386. }
  387. bool CScriptArray::IsEmpty() const
  388. {
  389. return buffer->numElements == 0;
  390. }
  391. void CScriptArray::Reserve(asUINT maxElements)
  392. {
  393. if( maxElements <= buffer->maxElements )
  394. return;
  395. // Allocate memory for the buffer
  396. SArrayBuffer *newBuffer;
  397. #if defined(__S3E__) // Marmalade doesn't understand (nothrow)
  398. newBuffer = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1 + elementSize*maxElements];
  399. #else
  400. newBuffer = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1 + elementSize*maxElements];
  401. #endif
  402. if( newBuffer )
  403. {
  404. newBuffer->numElements = buffer->numElements;
  405. newBuffer->maxElements = maxElements;
  406. }
  407. else
  408. {
  409. // Out of memory
  410. asIScriptContext *ctx = asGetActiveContext();
  411. if( ctx )
  412. ctx->SetException("Out of memory");
  413. return;
  414. }
  415. memcpy(newBuffer->data, buffer->data, buffer->numElements*elementSize);
  416. // Release the old buffer
  417. delete[] (asBYTE*)buffer;
  418. buffer = newBuffer;
  419. }
  420. void CScriptArray::Resize(asUINT numElements)
  421. {
  422. if( numElements & 0x80000000 )
  423. {
  424. CheckMaxSize(numElements);
  425. return;
  426. }
  427. Resize((int)numElements - (int)buffer->numElements, (asUINT)-1);
  428. }
  429. // Internal
  430. void CScriptArray::Resize(int delta, asUINT at)
  431. {
  432. if( delta < 0 )
  433. {
  434. if( -delta > (int)buffer->numElements )
  435. delta = -(int)buffer->numElements;
  436. if( at > buffer->numElements + delta )
  437. at = buffer->numElements + delta;
  438. }
  439. else if( delta > 0 )
  440. {
  441. // Make sure the array size isn't too large for us to handle
  442. if( delta > 0 && !CheckMaxSize(buffer->numElements + delta) )
  443. return;
  444. if( at > buffer->numElements )
  445. at = buffer->numElements;
  446. }
  447. if( delta == 0 ) return;
  448. if( buffer->maxElements < buffer->numElements + delta )
  449. {
  450. // Allocate memory for the buffer
  451. SArrayBuffer *newBuffer;
  452. #if defined(__S3E__) // Marmalade doesn't understand (nothrow)
  453. newBuffer = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)];
  454. #else
  455. newBuffer = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)];
  456. #endif
  457. if( newBuffer )
  458. {
  459. newBuffer->numElements = buffer->numElements + delta;
  460. newBuffer->maxElements = newBuffer->numElements;
  461. }
  462. else
  463. {
  464. // Out of memory
  465. asIScriptContext *ctx = asGetActiveContext();
  466. if( ctx )
  467. ctx->SetException("Out of memory");
  468. return;
  469. }
  470. memcpy(newBuffer->data, buffer->data, at*elementSize);
  471. if( at < buffer->numElements )
  472. memcpy(newBuffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements-at)*elementSize);
  473. if( subTypeId & asTYPEID_MASK_OBJECT )
  474. Construct(newBuffer, at, at+delta);
  475. // Release the old buffer
  476. delete[] (asBYTE*)buffer;
  477. buffer = newBuffer;
  478. }
  479. else if( delta < 0 )
  480. {
  481. Destruct(buffer, at, at-delta);
  482. memmove(buffer->data + at*elementSize, buffer->data + (at-delta)*elementSize, (buffer->numElements - (at-delta))*elementSize);
  483. buffer->numElements += delta;
  484. }
  485. else
  486. {
  487. memmove(buffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements - at)*elementSize);
  488. Construct(buffer, at, at+delta);
  489. buffer->numElements += delta;
  490. }
  491. }
  492. // internal
  493. bool CScriptArray::CheckMaxSize(asUINT numElements)
  494. {
  495. // This code makes sure the size of the buffer that is allocated
  496. // for the array doesn't overflow and becomes smaller than requested
  497. asUINT maxSize = 0xFFFFFFFFul - sizeof(SArrayBuffer) + 1;
  498. if( subTypeId & asTYPEID_MASK_OBJECT )
  499. maxSize /= sizeof(void*);
  500. else if( elementSize > 0 )
  501. maxSize /= elementSize;
  502. if( numElements > maxSize )
  503. {
  504. asIScriptContext *ctx = asGetActiveContext();
  505. if( ctx )
  506. {
  507. // Set a script exception
  508. ctx->SetException("Too large array size");
  509. }
  510. return false;
  511. }
  512. // OK
  513. return true;
  514. }
  515. asIObjectType *CScriptArray::GetArrayObjectType() const
  516. {
  517. return objType;
  518. }
  519. int CScriptArray::GetArrayTypeId() const
  520. {
  521. return objType->GetTypeId();
  522. }
  523. int CScriptArray::GetElementTypeId() const
  524. {
  525. return subTypeId;
  526. }
  527. void CScriptArray::InsertAt(asUINT index, void *value)
  528. {
  529. if( index > buffer->numElements )
  530. {
  531. // If this is called from a script we raise a script exception
  532. asIScriptContext *ctx = asGetActiveContext();
  533. if( ctx )
  534. ctx->SetException("Index out of bounds");
  535. return;
  536. }
  537. // Make room for the new element
  538. Resize(1, index);
  539. // Set the value of the new element
  540. SetValue(index, value);
  541. }
  542. void CScriptArray::InsertLast(void *value)
  543. {
  544. InsertAt(buffer->numElements, value);
  545. }
  546. void CScriptArray::RemoveAt(asUINT index)
  547. {
  548. if( index >= buffer->numElements )
  549. {
  550. // If this is called from a script we raise a script exception
  551. asIScriptContext *ctx = asGetActiveContext();
  552. if( ctx )
  553. ctx->SetException("Index out of bounds");
  554. return;
  555. }
  556. // Remove the element
  557. Resize(-1, index);
  558. }
  559. void CScriptArray::RemoveLast()
  560. {
  561. RemoveAt(buffer->numElements-1);
  562. }
  563. // Return a pointer to the array element. Returns 0 if the index is out of bounds
  564. const void *CScriptArray::At(asUINT index) const
  565. {
  566. if( buffer == 0 || index >= buffer->numElements )
  567. {
  568. // If this is called from a script we raise a script exception
  569. asIScriptContext *ctx = asGetActiveContext();
  570. if( ctx )
  571. ctx->SetException("Index out of bounds");
  572. return 0;
  573. }
  574. if( (subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  575. return (void*)((size_t*)buffer->data)[index];
  576. else
  577. return buffer->data + elementSize*index;
  578. }
  579. void *CScriptArray::At(asUINT index)
  580. {
  581. return const_cast<void*>(const_cast<const CScriptArray *>(this)->At(index));
  582. }
  583. // internal
  584. void CScriptArray::CreateBuffer(SArrayBuffer **buf, asUINT numElements)
  585. {
  586. if( subTypeId & asTYPEID_MASK_OBJECT )
  587. {
  588. #if defined(__S3E__) // Marmalade doesn't understand (nothrow)
  589. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+sizeof(void*)*numElements];
  590. #else
  591. *buf = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1+sizeof(void*)*numElements];
  592. #endif
  593. }
  594. else
  595. {
  596. #if defined(__S3E__)
  597. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+elementSize*numElements];
  598. #else
  599. *buf = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1+elementSize*numElements];
  600. #endif
  601. }
  602. if( *buf )
  603. {
  604. (*buf)->numElements = numElements;
  605. (*buf)->maxElements = numElements;
  606. Construct(*buf, 0, numElements);
  607. }
  608. else
  609. {
  610. // Oops, out of memory
  611. asIScriptContext *ctx = asGetActiveContext();
  612. if( ctx )
  613. ctx->SetException("Out of memory");
  614. }
  615. }
  616. // internal
  617. void CScriptArray::DeleteBuffer(SArrayBuffer *buf)
  618. {
  619. Destruct(buf, 0, buf->numElements);
  620. // Free the buffer
  621. delete[] (asBYTE*)buf;
  622. }
  623. // internal
  624. void CScriptArray::Construct(SArrayBuffer *buf, asUINT start, asUINT end)
  625. {
  626. if( subTypeId & asTYPEID_OBJHANDLE )
  627. {
  628. // Set all object handles to null
  629. void *d = (void*)(buf->data + start * sizeof(void*));
  630. memset(d, 0, (end-start)*sizeof(void*));
  631. }
  632. else if( subTypeId & asTYPEID_MASK_OBJECT )
  633. {
  634. void **max = (void**)(buf->data + end * sizeof(void*));
  635. void **d = (void**)(buf->data + start * sizeof(void*));
  636. asIScriptEngine *engine = objType->GetEngine();
  637. asIObjectType *subType = objType->GetSubType();
  638. for( ; d < max; d++ )
  639. *d = (void*)engine->CreateScriptObject(subType);
  640. }
  641. }
  642. // internal
  643. void CScriptArray::Destruct(SArrayBuffer *buf, asUINT start, asUINT end)
  644. {
  645. if( subTypeId & asTYPEID_MASK_OBJECT )
  646. {
  647. asIScriptEngine *engine = objType->GetEngine();
  648. void **max = (void**)(buf->data + end * sizeof(void*));
  649. void **d = (void**)(buf->data + start * sizeof(void*));
  650. for( ; d < max; d++ )
  651. {
  652. if( *d )
  653. engine->ReleaseScriptObject(*d, objType->GetSubType());
  654. }
  655. }
  656. }
  657. // internal
  658. bool CScriptArray::Less(const void *a, const void *b, bool asc, asIScriptContext *ctx, SArrayCache *cache)
  659. {
  660. if( !asc )
  661. {
  662. // Swap items
  663. const void *TEMP = a;
  664. a = b;
  665. b = TEMP;
  666. }
  667. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  668. {
  669. // Simple compare of values
  670. switch( subTypeId )
  671. {
  672. #define COMPARE(T) *((T*)a) < *((T*)b)
  673. case asTYPEID_BOOL: return COMPARE(bool);
  674. case asTYPEID_INT8: return COMPARE(signed char);
  675. case asTYPEID_UINT8: return COMPARE(unsigned char);
  676. case asTYPEID_INT16: return COMPARE(signed short);
  677. case asTYPEID_UINT16: return COMPARE(unsigned short);
  678. case asTYPEID_INT32: return COMPARE(signed int);
  679. case asTYPEID_UINT32: return COMPARE(unsigned int);
  680. case asTYPEID_FLOAT: return COMPARE(float);
  681. case asTYPEID_DOUBLE: return COMPARE(double);
  682. default: return COMPARE(signed int); // All enums fall in this case
  683. #undef COMPARE
  684. }
  685. }
  686. else
  687. {
  688. int r = 0;
  689. if( subTypeId & asTYPEID_OBJHANDLE )
  690. {
  691. // Allow sort to work even if the array contains null handles
  692. if( *(void**)a == 0 ) return true;
  693. if( *(void**)b == 0 ) return false;
  694. }
  695. // Execute object opCmp
  696. if( cache && cache->cmpFunc )
  697. {
  698. // TODO: Add proper error handling
  699. r = ctx->Prepare(cache->cmpFunc); assert(r >= 0);
  700. if( subTypeId & asTYPEID_OBJHANDLE )
  701. {
  702. r = ctx->SetObject(*((void**)a)); assert(r >= 0);
  703. r = ctx->SetArgObject(0, *((void**)b)); assert(r >= 0);
  704. }
  705. else
  706. {
  707. r = ctx->SetObject((void*)a); assert(r >= 0);
  708. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  709. }
  710. r = ctx->Execute();
  711. if( r == asEXECUTION_FINISHED )
  712. {
  713. return (int)ctx->GetReturnDWord() < 0;
  714. }
  715. }
  716. }
  717. return false;
  718. }
  719. void CScriptArray::Reverse()
  720. {
  721. asUINT size = GetSize();
  722. if( size >= 2 )
  723. {
  724. asBYTE TEMP[16];
  725. for( asUINT i = 0; i < size / 2; i++ )
  726. {
  727. Copy(TEMP, GetArrayItemPointer(i));
  728. Copy(GetArrayItemPointer(i), GetArrayItemPointer(size - i - 1));
  729. Copy(GetArrayItemPointer(size - i - 1), TEMP);
  730. }
  731. }
  732. }
  733. bool CScriptArray::operator==(const CScriptArray &other) const
  734. {
  735. if( objType != other.objType )
  736. return false;
  737. if( GetSize() != other.GetSize() )
  738. return false;
  739. asIScriptContext *cmpContext = 0;
  740. bool isNested = false;
  741. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  742. {
  743. // Try to reuse the active context
  744. cmpContext = asGetActiveContext();
  745. if( cmpContext )
  746. {
  747. if( cmpContext->PushState() >= 0 )
  748. isNested = true;
  749. else
  750. cmpContext = 0;
  751. }
  752. if( cmpContext == 0 )
  753. {
  754. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  755. // create a new one everytime. We could keep a context with the array object
  756. // but that would consume a lot of resources as each context is quite heavy.
  757. cmpContext = objType->GetEngine()->CreateContext();
  758. }
  759. }
  760. // Check if all elements are equal
  761. bool isEqual = true;
  762. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  763. for( asUINT n = 0; n < GetSize(); n++ )
  764. if( !Equals(At(n), other.At(n), cmpContext, cache) )
  765. {
  766. isEqual = false;
  767. break;
  768. }
  769. if( cmpContext )
  770. if( isNested )
  771. {
  772. asEContextState state = cmpContext->GetState();
  773. cmpContext->PopState();
  774. if( state == asEXECUTION_ABORTED )
  775. cmpContext->Abort();
  776. }
  777. else
  778. cmpContext->Release();
  779. return isEqual;
  780. }
  781. // internal
  782. bool CScriptArray::Equals(const void *a, const void *b, asIScriptContext *ctx, SArrayCache *cache) const
  783. {
  784. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  785. {
  786. // Simple compare of values
  787. switch( subTypeId )
  788. {
  789. #define COMPARE(T) *((T*)a) == *((T*)b)
  790. case asTYPEID_BOOL: return COMPARE(bool);
  791. case asTYPEID_INT8: return COMPARE(signed char);
  792. case asTYPEID_UINT8: return COMPARE(unsigned char);
  793. case asTYPEID_INT16: return COMPARE(signed short);
  794. case asTYPEID_UINT16: return COMPARE(unsigned short);
  795. case asTYPEID_INT32: return COMPARE(signed int);
  796. case asTYPEID_UINT32: return COMPARE(unsigned int);
  797. case asTYPEID_FLOAT: return COMPARE(float);
  798. case asTYPEID_DOUBLE: return COMPARE(double);
  799. default: return COMPARE(signed int); // All enums fall here
  800. #undef COMPARE
  801. }
  802. }
  803. else
  804. {
  805. int r = 0;
  806. if( subTypeId & asTYPEID_OBJHANDLE )
  807. {
  808. // Allow the find to work even if the array contains null handles
  809. if( *(void**)a == *(void**)b ) return true;
  810. }
  811. // Execute object opEquals if available
  812. if( cache && cache->eqFunc )
  813. {
  814. // TODO: Add proper error handling
  815. r = ctx->Prepare(cache->eqFunc); assert(r >= 0);
  816. if( subTypeId & asTYPEID_OBJHANDLE )
  817. {
  818. r = ctx->SetObject(*((void**)a)); assert(r >= 0);
  819. r = ctx->SetArgObject(0, *((void**)b)); assert(r >= 0);
  820. }
  821. else
  822. {
  823. r = ctx->SetObject((void*)a); assert(r >= 0);
  824. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  825. }
  826. r = ctx->Execute();
  827. if( r == asEXECUTION_FINISHED )
  828. return ctx->GetReturnByte() != 0;
  829. return false;
  830. }
  831. // Execute object opCmp if available
  832. if( cache && cache->cmpFunc )
  833. {
  834. // TODO: Add proper error handling
  835. r = ctx->Prepare(cache->cmpFunc); assert(r >= 0);
  836. if( subTypeId & asTYPEID_OBJHANDLE )
  837. {
  838. r = ctx->SetObject(*((void**)a)); assert(r >= 0);
  839. r = ctx->SetArgObject(0, *((void**)b)); assert(r >= 0);
  840. }
  841. else
  842. {
  843. r = ctx->SetObject((void*)a); assert(r >= 0);
  844. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  845. }
  846. r = ctx->Execute();
  847. if( r == asEXECUTION_FINISHED )
  848. return (int)ctx->GetReturnDWord() == 0;
  849. return false;
  850. }
  851. }
  852. return false;
  853. }
  854. int CScriptArray::Find(void *value) const
  855. {
  856. return Find(0, value);
  857. }
  858. int CScriptArray::Find(asUINT index, void *value) const
  859. {
  860. // Check if the subtype really supports find()
  861. // TODO: Can't this be done at compile time too by the template callback
  862. SArrayCache *cache = 0;
  863. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  864. {
  865. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  866. if( !cache || (cache->cmpFunc == 0 && cache->eqFunc == 0) )
  867. {
  868. asIScriptContext *ctx = asGetActiveContext();
  869. asIObjectType* subType = objType->GetEngine()->GetObjectTypeById(subTypeId);
  870. // Throw an exception
  871. if( ctx )
  872. {
  873. char tmp[512];
  874. if( cache && cache->eqFuncReturnCode == asMULTIPLE_FUNCTIONS )
  875. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  876. sprintf_s(tmp, 512, "Type '%s' has multiple matching opEquals or opCmp methods", subType->GetName());
  877. #else
  878. sprintf(tmp, "Type '%s' has multiple matching opEquals or opCmp methods", subType->GetName());
  879. #endif
  880. else
  881. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  882. sprintf_s(tmp, 512, "Type '%s' does not have a matching opEquals or opCmp method", subType->GetName());
  883. #else
  884. sprintf(tmp, "Type '%s' does not have a matching opEquals or opCmp method", subType->GetName());
  885. #endif
  886. ctx->SetException(tmp);
  887. }
  888. return -1;
  889. }
  890. }
  891. asIScriptContext *cmpContext = 0;
  892. bool isNested = false;
  893. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  894. {
  895. // Try to reuse the active context
  896. cmpContext = asGetActiveContext();
  897. if( cmpContext )
  898. {
  899. if( cmpContext->PushState() >= 0 )
  900. isNested = true;
  901. else
  902. cmpContext = 0;
  903. }
  904. if( cmpContext == 0 )
  905. {
  906. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  907. // create a new one everytime. We could keep a context with the array object
  908. // but that would consume a lot of resources as each context is quite heavy.
  909. cmpContext = objType->GetEngine()->CreateContext();
  910. }
  911. }
  912. // Find the matching element
  913. int ret = -1;
  914. asUINT size = GetSize();
  915. if( index < size )
  916. {
  917. for( asUINT i = index; i < size; i++ )
  918. {
  919. // value passed by reference
  920. if( Equals(At(i), (value), cmpContext, cache) )
  921. {
  922. ret = (int)i;
  923. break;
  924. }
  925. }
  926. }
  927. if( cmpContext )
  928. if( isNested )
  929. {
  930. asEContextState state = cmpContext->GetState();
  931. cmpContext->PopState();
  932. if( state == asEXECUTION_ABORTED )
  933. cmpContext->Abort();
  934. }
  935. else
  936. cmpContext->Release();
  937. return ret;
  938. }
  939. // internal
  940. // Copy object handle or primitive value
  941. void CScriptArray::Copy(void *dst, void *src)
  942. {
  943. memcpy(dst, src, elementSize);
  944. }
  945. // internal
  946. // Return pointer to array item (object handle or primitive value)
  947. void *CScriptArray::GetArrayItemPointer(int index)
  948. {
  949. return buffer->data + index * elementSize;
  950. }
  951. // internal
  952. // Return pointer to data in buffer (object or primitive)
  953. void *CScriptArray::GetDataPointer(void *buffer)
  954. {
  955. if ((subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  956. {
  957. // Real address of object
  958. return reinterpret_cast<void*>(*(size_t*)buffer);
  959. }
  960. else
  961. {
  962. // Primitive is just a raw data
  963. return buffer;
  964. }
  965. }
  966. // Sort ascending
  967. void CScriptArray::SortAsc()
  968. {
  969. Sort(0, GetSize(), true);
  970. }
  971. // Sort ascending
  972. void CScriptArray::SortAsc(asUINT index, asUINT count)
  973. {
  974. Sort(index, count, true);
  975. }
  976. // Sort descending
  977. void CScriptArray::SortDesc()
  978. {
  979. Sort(0, GetSize(), false);
  980. }
  981. // Sort descending
  982. void CScriptArray::SortDesc(asUINT index, asUINT count)
  983. {
  984. Sort(index, count, false);
  985. }
  986. // internal
  987. void CScriptArray::Sort(asUINT index, asUINT count, bool asc)
  988. {
  989. // Subtype isn't primitive and doesn't have opCmp
  990. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  991. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  992. {
  993. if( !cache || cache->cmpFunc == 0 )
  994. {
  995. asIScriptContext *ctx = asGetActiveContext();
  996. asIObjectType* subType = objType->GetEngine()->GetObjectTypeById(subTypeId);
  997. // Throw an exception
  998. if( ctx )
  999. {
  1000. char tmp[512];
  1001. if( cache && cache->cmpFuncReturnCode == asMULTIPLE_FUNCTIONS )
  1002. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  1003. sprintf_s(tmp, 512, "Type '%s' has multiple matching opCmp methods", subType->GetName());
  1004. #else
  1005. sprintf(tmp, "Type '%s' has multiple matching opCmp methods", subType->GetName());
  1006. #endif
  1007. else
  1008. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(__S3E__)
  1009. sprintf_s(tmp, 512, "Type '%s' does not have a matching opCmp method", subType->GetName());
  1010. #else
  1011. sprintf(tmp, "Type '%s' does not have a matching opCmp method", subType->GetName());
  1012. #endif
  1013. ctx->SetException(tmp);
  1014. }
  1015. return;
  1016. }
  1017. }
  1018. // No need to sort
  1019. if( count < 2 )
  1020. {
  1021. return;
  1022. }
  1023. int start = index;
  1024. int end = index + count;
  1025. // Check if we could access invalid item while sorting
  1026. if( start >= (int)buffer->numElements || end > (int)buffer->numElements )
  1027. {
  1028. asIScriptContext *ctx = asGetActiveContext();
  1029. // Throw an exception
  1030. if( ctx )
  1031. {
  1032. ctx->SetException("Index out of bounds");
  1033. }
  1034. return;
  1035. }
  1036. asBYTE tmp[16];
  1037. asIScriptContext *cmpContext = 0;
  1038. bool isNested = false;
  1039. if( subTypeId & ~asTYPEID_MASK_SEQNBR )
  1040. {
  1041. // Try to reuse the active context
  1042. cmpContext = asGetActiveContext();
  1043. if( cmpContext )
  1044. {
  1045. if( cmpContext->PushState() >= 0 )
  1046. isNested = true;
  1047. else
  1048. cmpContext = 0;
  1049. }
  1050. if( cmpContext == 0 )
  1051. {
  1052. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  1053. // create a new one everytime. We could keep a context with the array object
  1054. // but that would consume a lot of resources as each context is quite heavy.
  1055. cmpContext = objType->GetEngine()->CreateContext();
  1056. }
  1057. }
  1058. // Insertion sort
  1059. for( int i = start + 1; i < end; i++ )
  1060. {
  1061. Copy(tmp, GetArrayItemPointer(i));
  1062. int j = i - 1;
  1063. while( j >= start && Less(GetDataPointer(tmp), At(j), asc, cmpContext, cache) )
  1064. {
  1065. Copy(GetArrayItemPointer(j + 1), GetArrayItemPointer(j));
  1066. j--;
  1067. }
  1068. Copy(GetArrayItemPointer(j + 1), tmp);
  1069. }
  1070. if( cmpContext )
  1071. if( isNested )
  1072. {
  1073. asEContextState state = cmpContext->GetState();
  1074. cmpContext->PopState();
  1075. if( state == asEXECUTION_ABORTED )
  1076. cmpContext->Abort();
  1077. }
  1078. else
  1079. cmpContext->Release();
  1080. }
  1081. // internal
  1082. void CScriptArray::CopyBuffer(SArrayBuffer *dst, SArrayBuffer *src)
  1083. {
  1084. asIScriptEngine *engine = objType->GetEngine();
  1085. if( subTypeId & asTYPEID_OBJHANDLE )
  1086. {
  1087. // Copy the references and increase the reference counters
  1088. if( dst->numElements > 0 && src->numElements > 0 )
  1089. {
  1090. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  1091. void **max = (void**)(dst->data + count * sizeof(void*));
  1092. void **d = (void**)dst->data;
  1093. void **s = (void**)src->data;
  1094. for( ; d < max; d++, s++ )
  1095. {
  1096. void *tmp = *d;
  1097. *d = *s;
  1098. if( *d )
  1099. engine->AddRefScriptObject(*d, objType->GetSubType());
  1100. // Release the old ref after incrementing the new to avoid problem incase it is the same ref
  1101. if( tmp )
  1102. engine->ReleaseScriptObject(tmp, objType->GetSubType());
  1103. }
  1104. }
  1105. }
  1106. else
  1107. {
  1108. if( dst->numElements > 0 && src->numElements > 0 )
  1109. {
  1110. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  1111. if( subTypeId & asTYPEID_MASK_OBJECT )
  1112. {
  1113. // Call the assignment operator on all of the objects
  1114. void **max = (void**)(dst->data + count * sizeof(void*));
  1115. void **d = (void**)dst->data;
  1116. void **s = (void**)src->data;
  1117. asIObjectType *subType = objType->GetSubType();
  1118. for( ; d < max; d++, s++ )
  1119. engine->AssignScriptObject(*d, *s, subType);
  1120. }
  1121. else
  1122. {
  1123. // Primitives are copied byte for byte
  1124. memcpy(dst->data, src->data, count*elementSize);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. // internal
  1130. // Precache some info
  1131. void CScriptArray::Precache()
  1132. {
  1133. subTypeId = objType->GetSubTypeId();
  1134. // Check if it is an array of objects. Only for these do we need to cache anything
  1135. // Type ids for primitives and enums only has the sequence number part
  1136. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  1137. return;
  1138. // The opCmp and opEquals methods are cached because the searching for the
  1139. // methods is quite time consuming if a lot of array objects are created.
  1140. // First check if a cache already exists for this array type
  1141. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1142. if( cache ) return;
  1143. // We need to make sure the cache is created only once, even
  1144. // if multiple threads reach the same point at the same time
  1145. asAcquireExclusiveLock();
  1146. // Now that we got the lock, we need to check again to make sure the
  1147. // cache wasn't created while we were waiting for the lock
  1148. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  1149. if( cache )
  1150. {
  1151. asReleaseExclusiveLock();
  1152. return;
  1153. }
  1154. // Create the cache
  1155. cache = new SArrayCache();
  1156. memset(cache, 0, sizeof(SArrayCache));
  1157. // If the sub type is a handle to const, then the methods must be const too
  1158. bool mustBeConst = (subTypeId & asTYPEID_HANDLETOCONST) ? true : false;
  1159. asIObjectType *subType = objType->GetEngine()->GetObjectTypeById(subTypeId);
  1160. if( subType )
  1161. {
  1162. for( asUINT i = 0; i < subType->GetMethodCount(); i++ )
  1163. {
  1164. asIScriptFunction *func = subType->GetMethodByIndex(i);
  1165. if( func->GetParamCount() == 1 && (!mustBeConst || func->IsReadOnly()) )
  1166. {
  1167. asDWORD flags = 0;
  1168. int returnTypeId = func->GetReturnTypeId(&flags);
  1169. // The method must not return a reference
  1170. if( flags != asTM_NONE )
  1171. continue;
  1172. // opCmp returns an int and opEquals returns a bool
  1173. bool isCmp = false, isEq = false;
  1174. if( returnTypeId == asTYPEID_INT32 && strcmp(func->GetName(), "opCmp") == 0 )
  1175. isCmp = true;
  1176. if( returnTypeId == asTYPEID_BOOL && strcmp(func->GetName(), "opEquals") == 0 )
  1177. isEq = true;
  1178. if( !isCmp && !isEq )
  1179. continue;
  1180. // The parameter must either be a reference to the subtype or a handle to the subtype
  1181. int paramTypeId = func->GetParamTypeId(0, &flags);
  1182. if( (paramTypeId & ~(asTYPEID_OBJHANDLE|asTYPEID_HANDLETOCONST)) != (subTypeId & ~(asTYPEID_OBJHANDLE|asTYPEID_HANDLETOCONST)) )
  1183. continue;
  1184. if( (flags & asTM_INREF) )
  1185. {
  1186. if( (paramTypeId & asTYPEID_OBJHANDLE) || mustBeConst && !(flags & asTM_CONST) )
  1187. continue;
  1188. }
  1189. else if( paramTypeId & asTYPEID_OBJHANDLE )
  1190. {
  1191. if( mustBeConst && !(paramTypeId & asTYPEID_HANDLETOCONST) )
  1192. continue;
  1193. }
  1194. else
  1195. continue;
  1196. if( isCmp )
  1197. {
  1198. if( cache->cmpFunc || cache->cmpFuncReturnCode )
  1199. {
  1200. cache->cmpFunc = 0;
  1201. cache->cmpFuncReturnCode = asMULTIPLE_FUNCTIONS;
  1202. }
  1203. else
  1204. cache->cmpFunc = func;
  1205. }
  1206. else if( isEq )
  1207. {
  1208. if( cache->eqFunc || cache->eqFuncReturnCode )
  1209. {
  1210. cache->eqFunc = 0;
  1211. cache->eqFuncReturnCode = asMULTIPLE_FUNCTIONS;
  1212. }
  1213. else
  1214. cache->eqFunc = func;
  1215. }
  1216. }
  1217. }
  1218. }
  1219. if( cache->eqFunc == 0 && cache->eqFuncReturnCode == 0 )
  1220. cache->eqFuncReturnCode = asNO_FUNCTION;
  1221. if( cache->cmpFunc == 0 && cache->cmpFuncReturnCode == 0 )
  1222. cache->cmpFuncReturnCode = asNO_FUNCTION;
  1223. // Set the user data only at the end so others that retrieve it will know it is complete
  1224. objType->SetUserData(cache, ARRAY_CACHE);
  1225. asReleaseExclusiveLock();
  1226. }
  1227. // GC behaviour
  1228. void CScriptArray::EnumReferences(asIScriptEngine *engine)
  1229. {
  1230. // If the array is holding handles, then we need to notify the GC of them
  1231. if( subTypeId & asTYPEID_MASK_OBJECT )
  1232. {
  1233. void **d = (void**)buffer->data;
  1234. for( asUINT n = 0; n < buffer->numElements; n++ )
  1235. {
  1236. if( d[n] )
  1237. engine->GCEnumCallback(d[n]);
  1238. }
  1239. }
  1240. }
  1241. // GC behaviour
  1242. void CScriptArray::ReleaseAllHandles(asIScriptEngine *engine)
  1243. {
  1244. // Resizing to zero will release everything
  1245. Resize(0);
  1246. }
  1247. void CScriptArray::AddRef() const
  1248. {
  1249. // Clear the GC flag then increase the counter
  1250. gcFlag = false;
  1251. asAtomicInc(refCount);
  1252. }
  1253. void CScriptArray::Release() const
  1254. {
  1255. // Clearing the GC flag then descrease the counter
  1256. gcFlag = false;
  1257. if( asAtomicDec(refCount) == 0 )
  1258. {
  1259. // When reaching 0 no more references to this instance
  1260. // exists and the object should be destroyed
  1261. delete this;
  1262. }
  1263. }
  1264. // GC behaviour
  1265. int CScriptArray::GetRefCount()
  1266. {
  1267. return refCount;
  1268. }
  1269. // GC behaviour
  1270. void CScriptArray::SetFlag()
  1271. {
  1272. gcFlag = true;
  1273. }
  1274. // GC behaviour
  1275. bool CScriptArray::GetFlag()
  1276. {
  1277. return gcFlag;
  1278. }
  1279. static void ScriptArrayClear(CScriptArray* ptr)
  1280. {
  1281. ptr->Resize(0);
  1282. }
  1283. void RegisterArray(asIScriptEngine* engine)
  1284. {
  1285. // Register the object type user data clean up
  1286. engine->SetObjectTypeUserDataCleanupCallback(CleanupObjectTypeArrayCache, ARRAY_CACHE);
  1287. engine->RegisterObjectType("Array<class T>", 0, asOBJ_REF | asOBJ_TEMPLATE);
  1288. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int&in, bool&out)", asFUNCTION(ScriptArrayTemplateCallback), asCALL_CDECL);
  1289. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int& in)", asFUNCTIONPR(ScriptArrayFactory, (asIObjectType*), CScriptArray*), asCALL_CDECL);
  1290. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  1291. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int& in, uint, const T& in)", asFUNCTIONPR(ScriptArrayFactoryDefVal, (asIObjectType*, asUINT, void *), CScriptArray*), asCALL_CDECL);
  1292. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_LIST_FACTORY, "Array<T>@ f(int&in type, int&in list) {repeat T}", asFUNCTIONPR(ScriptArrayListFactory, (asIObjectType*, void*), CScriptArray*), asCALL_CDECL);
  1293. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptArray,AddRef), asCALL_THISCALL);
  1294. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptArray,Release), asCALL_THISCALL);
  1295. engine->RegisterObjectMethod("Array<T>", "T& opIndex(uint)", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1296. engine->RegisterObjectMethod("Array<T>", "const T& opIndex(uint) const", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1297. engine->RegisterObjectMethod("Array<T>", "Array<T>& opAssign(const Array<T>& in)", asMETHOD(CScriptArray, operator=), asCALL_THISCALL);
  1298. engine->RegisterObjectMethod("Array<T>", "void Insert(uint, const T& in)", asMETHOD(CScriptArray, InsertAt), asCALL_THISCALL);
  1299. engine->RegisterObjectMethod("Array<T>", "void Erase(uint)", asMETHOD(CScriptArray, RemoveAt), asCALL_THISCALL);
  1300. engine->RegisterObjectMethod("Array<T>", "void Push(const T& in)", asMETHOD(CScriptArray, InsertLast), asCALL_THISCALL);
  1301. engine->RegisterObjectMethod("Array<T>", "void Pop()", asMETHOD(CScriptArray, RemoveLast), asCALL_THISCALL);
  1302. engine->RegisterObjectMethod("Array<T>", "void Resize(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1303. engine->RegisterObjectMethod("Array<T>", "void Clear()", asFUNCTION(ScriptArrayClear), asCALL_CDECL_OBJLAST);
  1304. engine->RegisterObjectMethod("Array<T>", "void Sort()", asMETHODPR(CScriptArray, SortAsc, (), void), asCALL_THISCALL);
  1305. engine->RegisterObjectMethod("Array<T>", "void Sort(uint, uint)", asMETHODPR(CScriptArray, SortAsc, (asUINT, asUINT), void), asCALL_THISCALL);
  1306. engine->RegisterObjectMethod("Array<T>", "void SortReverse()", asMETHODPR(CScriptArray, SortDesc, (), void), asCALL_THISCALL);
  1307. engine->RegisterObjectMethod("Array<T>", "void SortReverse(uint, uint)", asMETHODPR(CScriptArray, SortDesc, (asUINT, asUINT), void), asCALL_THISCALL);
  1308. engine->RegisterObjectMethod("Array<T>", "void Reverse()", asMETHOD(CScriptArray, Reverse), asCALL_THISCALL);
  1309. engine->RegisterObjectMethod("Array<T>", "int Find(const T&in) const", asMETHODPR(CScriptArray, Find, (void*) const, int), asCALL_THISCALL);
  1310. engine->RegisterObjectMethod("Array<T>", "int Find(uint, const T&in) const", asMETHODPR(CScriptArray, Find, (asUINT, void*) const, int), asCALL_THISCALL);
  1311. engine->RegisterObjectMethod("Array<T>", "bool opEquals(const Array<T>&in) const", asMETHOD(CScriptArray, operator==), asCALL_THISCALL);
  1312. engine->RegisterObjectMethod("Array<T>", "uint get_length() const", asMETHOD(CScriptArray, GetSize), asCALL_THISCALL);
  1313. engine->RegisterObjectMethod("Array<T>", "void set_length(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1314. engine->RegisterObjectMethod("Array<T>", "bool get_empty() const", asMETHOD(CScriptArray, IsEmpty), asCALL_THISCALL);
  1315. engine->RegisterDefaultArrayType("Array<T>");
  1316. }
  1317. CScriptDictionary::CScriptDictionary(asIScriptEngine *engine)
  1318. {
  1319. // We start with one reference
  1320. refCount = 1;
  1321. gcFlag = false;
  1322. // Keep a reference to the engine for as long as we live
  1323. // We don't increment the reference counter, because the
  1324. // engine will hold a pointer to the object.
  1325. this->engine = engine;
  1326. // Urho3D: garbage collection disabled
  1327. /*
  1328. // Notify the garbage collector of this object
  1329. // TODO: The type id should be cached
  1330. engine->NotifyGarbageCollectorOfNewObject(this, engine->GetObjectTypeByName("dictionary"));
  1331. */
  1332. }
  1333. CScriptDictionary::CScriptDictionary(asBYTE *buffer)
  1334. {
  1335. // We start with one reference
  1336. refCount = 1;
  1337. gcFlag = false;
  1338. // This constructor will always be called from a script
  1339. // so we can get the engine from the active context
  1340. asIScriptContext *ctx = asGetActiveContext();
  1341. engine = ctx->GetEngine();
  1342. // Urho3D: garbage collection disable
  1343. /*
  1344. // Notify the garbage collector of this object
  1345. // TODO: The type id should be cached
  1346. engine->NotifyGarbageCollectorOfNewObject(this, engine->GetObjectTypeByName("dictionary"));
  1347. */
  1348. // Initialize the dictionary from the buffer
  1349. asUINT length = *(asUINT*)buffer;
  1350. buffer += 4;
  1351. while( length-- )
  1352. {
  1353. // Align the buffer pointer on a 4 byte boundary in
  1354. // case previous value was smaller than 4 bytes
  1355. if( asPWORD(buffer) & 0x3 )
  1356. buffer += 4 - (asPWORD(buffer) & 0x3);
  1357. // Get the name value pair from the buffer and insert it in the dictionary
  1358. String name = *(String*)buffer;
  1359. buffer += sizeof(String);
  1360. // Get the type id of the value
  1361. int typeId = *(int*)buffer;
  1362. buffer += sizeof(int);
  1363. // Depending on the type id, the value will inline in the buffer or a pointer
  1364. void *ref = (void*)buffer;
  1365. if( typeId >= asTYPEID_INT8 && typeId <= asTYPEID_DOUBLE )
  1366. {
  1367. // Convert primitive values to either int64 or double, so we can use the overloaded Set methods
  1368. asINT64 i64;
  1369. double d;
  1370. switch( typeId )
  1371. {
  1372. case asTYPEID_INT8: i64 = *(char*)ref; break;
  1373. case asTYPEID_INT16: i64 = *(short*)ref; break;
  1374. case asTYPEID_INT32: i64 = *(int*)ref; break;
  1375. case asTYPEID_INT64: i64 = *(asINT64*)ref; break;
  1376. case asTYPEID_UINT8: i64 = *(unsigned char*)ref; break;
  1377. case asTYPEID_UINT16: i64 = *(unsigned short*)ref; break;
  1378. case asTYPEID_UINT32: i64 = *(unsigned int*)ref; break;
  1379. case asTYPEID_UINT64: i64 = *(asINT64*)ref; break;
  1380. case asTYPEID_FLOAT: d = *(float*)ref; break;
  1381. case asTYPEID_DOUBLE: d = *(double*)ref; break;
  1382. }
  1383. if( typeId >= asTYPEID_FLOAT )
  1384. Set(name, d);
  1385. else
  1386. Set(name, i64);
  1387. }
  1388. else
  1389. {
  1390. if( (typeId & asTYPEID_MASK_OBJECT) &&
  1391. !(typeId & asTYPEID_OBJHANDLE) &&
  1392. (engine->GetObjectTypeById(typeId)->GetFlags() & asOBJ_REF) )
  1393. {
  1394. // Dereference the pointer to get the reference to the actual object
  1395. ref = *(void**)ref;
  1396. }
  1397. Set(name, ref, typeId);
  1398. }
  1399. // Advance the buffer pointer with the size of the value
  1400. if( typeId & asTYPEID_MASK_OBJECT )
  1401. {
  1402. asIObjectType *ot = engine->GetObjectTypeById(typeId);
  1403. if( ot->GetFlags() & asOBJ_VALUE )
  1404. buffer += ot->GetSize();
  1405. else
  1406. buffer += sizeof(void*);
  1407. }
  1408. else if( typeId == 0 )
  1409. {
  1410. // null pointer
  1411. buffer += sizeof(void*);
  1412. }
  1413. else
  1414. {
  1415. buffer += engine->GetSizeOfPrimitiveType(typeId);
  1416. }
  1417. }
  1418. }
  1419. CScriptDictionary::~CScriptDictionary()
  1420. {
  1421. // Delete all keys and values
  1422. DeleteAll();
  1423. }
  1424. void CScriptDictionary::AddRef() const
  1425. {
  1426. // We need to clear the GC flag
  1427. gcFlag = false;
  1428. asAtomicInc(refCount);
  1429. }
  1430. void CScriptDictionary::Release() const
  1431. {
  1432. // We need to clear the GC flag
  1433. gcFlag = false;
  1434. if( asAtomicDec(refCount) == 0 )
  1435. delete this;
  1436. }
  1437. int CScriptDictionary::GetRefCount()
  1438. {
  1439. return refCount;
  1440. }
  1441. void CScriptDictionary::SetGCFlag()
  1442. {
  1443. gcFlag = true;
  1444. }
  1445. bool CScriptDictionary::GetGCFlag()
  1446. {
  1447. return gcFlag;
  1448. }
  1449. void CScriptDictionary::EnumReferences(asIScriptEngine *engine)
  1450. {
  1451. // Call the gc enum callback for each of the objects
  1452. HashMap<String, valueStruct>::Iterator it;
  1453. for( it = dict.Begin(); it != dict.End(); it++ )
  1454. {
  1455. if( it->second_.typeId & asTYPEID_MASK_OBJECT )
  1456. engine->GCEnumCallback(it->second_.valueObj);
  1457. }
  1458. }
  1459. void CScriptDictionary::ReleaseAllReferences(asIScriptEngine * /*engine*/)
  1460. {
  1461. // We're being told to release all references in
  1462. // order to break circular references for dead objects
  1463. DeleteAll();
  1464. }
  1465. CScriptDictionary &CScriptDictionary::operator =(const CScriptDictionary &other)
  1466. {
  1467. // Clear everything we had before
  1468. DeleteAll();
  1469. // Do a shallow copy of the dictionary
  1470. HashMap<String, valueStruct>::ConstIterator it;
  1471. for( it = other.dict.Begin(); it != other.dict.End(); it++ )
  1472. {
  1473. if( it->second_.typeId & asTYPEID_OBJHANDLE )
  1474. Set(it->first_, (void*)&it->second_.valueObj, it->second_.typeId);
  1475. else if( it->second_.typeId & asTYPEID_MASK_OBJECT )
  1476. Set(it->first_, (void*)it->second_.valueObj, it->second_.typeId);
  1477. else
  1478. Set(it->first_, (void*)&it->second_.valueInt, it->second_.typeId);
  1479. }
  1480. return *this;
  1481. }
  1482. void CScriptDictionary::Set(const String &key, void *value, int typeId)
  1483. {
  1484. valueStruct valStruct = {{0},0};
  1485. valStruct.typeId = typeId;
  1486. if( typeId & asTYPEID_OBJHANDLE )
  1487. {
  1488. // We're receiving a reference to the handle, so we need to dereference it
  1489. valStruct.valueObj = *(void**)value;
  1490. engine->AddRefScriptObject(valStruct.valueObj, engine->GetObjectTypeById(typeId));
  1491. }
  1492. else if( typeId & asTYPEID_MASK_OBJECT )
  1493. {
  1494. // Create a copy of the object
  1495. valStruct.valueObj = engine->CreateScriptObjectCopy(value, engine->GetObjectTypeById(typeId));
  1496. }
  1497. else
  1498. {
  1499. // Copy the primitive value
  1500. // We receive a pointer to the value.
  1501. int size = engine->GetSizeOfPrimitiveType(typeId);
  1502. memcpy(&valStruct.valueInt, value, size);
  1503. }
  1504. HashMap<String, valueStruct>::Iterator it;
  1505. it = dict.Find(key);
  1506. if( it != dict.End() )
  1507. {
  1508. FreeValue(it->second_);
  1509. // Insert the new value
  1510. it->second_ = valStruct;
  1511. }
  1512. else
  1513. {
  1514. dict.Insert(MakePair(key, valStruct));
  1515. }
  1516. }
  1517. // This overloaded method is implemented so that all integer and
  1518. // unsigned integers types will be stored in the dictionary as int64
  1519. // through implicit conversions. This simplifies the management of the
  1520. // numeric types when the script retrieves the stored value using a
  1521. // different type.
  1522. void CScriptDictionary::Set(const String &key, asINT64 &value)
  1523. {
  1524. Set(key, &value, asTYPEID_INT64);
  1525. }
  1526. // This overloaded method is implemented so that all floating point types
  1527. // will be stored in the dictionary as double through implicit conversions.
  1528. // This simplifies the management of the numeric types when the script
  1529. // retrieves the stored value using a different type.
  1530. void CScriptDictionary::Set(const String &key, double &value)
  1531. {
  1532. Set(key, &value, asTYPEID_DOUBLE);
  1533. }
  1534. // Returns true if the value was successfully retrieved
  1535. bool CScriptDictionary::Get(const String &key, void *value, int typeId) const
  1536. {
  1537. HashMap<String, valueStruct>::ConstIterator it;
  1538. it = dict.Find(key);
  1539. if( it != dict.End() )
  1540. {
  1541. // Return the value
  1542. if( typeId & asTYPEID_OBJHANDLE )
  1543. {
  1544. // A handle can be retrieved if the stored type is a handle of same or compatible type
  1545. // or if the stored type is an object that implements the interface that the handle refer to.
  1546. if( (it->second_.typeId & asTYPEID_MASK_OBJECT) &&
  1547. engine->IsHandleCompatibleWithObject(it->second_.valueObj, it->second_.typeId, typeId) )
  1548. {
  1549. engine->AddRefScriptObject(it->second_.valueObj, engine->GetObjectTypeById(it->second_.typeId));
  1550. *(void**)value = it->second_.valueObj;
  1551. return true;
  1552. }
  1553. }
  1554. else if( typeId & asTYPEID_MASK_OBJECT )
  1555. {
  1556. // Verify that the copy can be made
  1557. bool isCompatible = false;
  1558. if( it->second_.typeId == typeId )
  1559. isCompatible = true;
  1560. // Copy the object into the given reference
  1561. if( isCompatible )
  1562. {
  1563. engine->AssignScriptObject(value, it->second_.valueObj, engine->GetObjectTypeById(typeId));
  1564. return true;
  1565. }
  1566. }
  1567. else
  1568. {
  1569. if( it->second_.typeId == typeId )
  1570. {
  1571. int size = engine->GetSizeOfPrimitiveType(typeId);
  1572. memcpy(value, &it->second_.valueInt, size);
  1573. return true;
  1574. }
  1575. // We know all numbers are stored as either int64 or double, since we register overloaded functions for those
  1576. if( it->second_.typeId == asTYPEID_INT64 && typeId == asTYPEID_DOUBLE )
  1577. {
  1578. *(double*)value = double(it->second_.valueInt);
  1579. return true;
  1580. }
  1581. else if( it->second_.typeId == asTYPEID_DOUBLE && typeId == asTYPEID_INT64 )
  1582. {
  1583. *(asINT64*)value = asINT64(it->second_.valueFlt);
  1584. return true;
  1585. }
  1586. }
  1587. }
  1588. // AngelScript has already initialized the value with a default value,
  1589. // so we don't have to do anything if we don't find the element, or if
  1590. // the element is incompatible with the requested type.
  1591. return false;
  1592. }
  1593. bool CScriptDictionary::Get(const String &key, asINT64 &value) const
  1594. {
  1595. return Get(key, &value, asTYPEID_INT64);
  1596. }
  1597. bool CScriptDictionary::Get(const String &key, double &value) const
  1598. {
  1599. return Get(key, &value, asTYPEID_DOUBLE);
  1600. }
  1601. bool CScriptDictionary::Exists(const String &key) const
  1602. {
  1603. HashMap<String, valueStruct>::ConstIterator it;
  1604. it = dict.Find(key);
  1605. if( it != dict.End() )
  1606. return true;
  1607. return false;
  1608. }
  1609. bool CScriptDictionary::IsEmpty() const
  1610. {
  1611. if( dict.Size() == 0 )
  1612. return true;
  1613. return false;
  1614. }
  1615. asUINT CScriptDictionary::GetSize() const
  1616. {
  1617. return asUINT(dict.Size());
  1618. }
  1619. void CScriptDictionary::Delete(const String &key)
  1620. {
  1621. HashMap<String, valueStruct>::Iterator it;
  1622. it = dict.Find(key);
  1623. if( it != dict.End() )
  1624. {
  1625. FreeValue(it->second_);
  1626. dict.Erase(it);
  1627. }
  1628. }
  1629. void CScriptDictionary::DeleteAll()
  1630. {
  1631. HashMap<String, valueStruct>::Iterator it;
  1632. for( it = dict.Begin(); it != dict.End(); it++ )
  1633. FreeValue(it->second_);
  1634. dict.Clear();
  1635. }
  1636. void CScriptDictionary::FreeValue(valueStruct &value)
  1637. {
  1638. // If it is a handle or a ref counted object, call release
  1639. if( value.typeId & asTYPEID_MASK_OBJECT )
  1640. {
  1641. // Let the engine release the object
  1642. engine->ReleaseScriptObject(value.valueObj, engine->GetObjectTypeById(value.typeId));
  1643. value.valueObj = 0;
  1644. value.typeId = 0;
  1645. }
  1646. // For primitives, there's nothing to do
  1647. }
  1648. CScriptArray* CScriptDictionary::GetKeys() const
  1649. {
  1650. // TODO: optimize: The String array type should only be determined once.
  1651. // It should be recomputed when registering the dictionary class.
  1652. // Only problem is if multiple engines are used, as they may not
  1653. // share the same type id. Alternatively it can be stored in the
  1654. // user data for the dictionary type.
  1655. int StringArrayType = engine->GetTypeIdByDecl("Array<String>");
  1656. asIObjectType *ot = engine->GetObjectTypeById(StringArrayType);
  1657. // Create the array object
  1658. CScriptArray *arr = new CScriptArray(asUINT(dict.Size()), ot);
  1659. long current = -1;
  1660. HashMap<String, valueStruct>::ConstIterator it;
  1661. for( it = dict.Begin(); it != dict.End(); it++ )
  1662. {
  1663. current++;
  1664. *(String*)arr->At(current) = it->first_;
  1665. }
  1666. return arr;
  1667. }
  1668. void ScriptDictionaryFactory_Generic(asIScriptGeneric *gen)
  1669. {
  1670. *(CScriptDictionary**)gen->GetAddressOfReturnLocation() = new CScriptDictionary(gen->GetEngine());
  1671. }
  1672. void ScriptDictionaryListFactory_Generic(asIScriptGeneric *gen)
  1673. {
  1674. asBYTE *buffer = (asBYTE*)gen->GetArgAddress(0);
  1675. *(CScriptDictionary**)gen->GetAddressOfReturnLocation() = new CScriptDictionary(buffer);
  1676. }
  1677. void RegisterDictionary(asIScriptEngine *engine)
  1678. {
  1679. engine->RegisterObjectType("Dictionary", sizeof(CScriptDictionary), asOBJ_REF);
  1680. // Use the generic interface to construct the object since we need the engine pointer, we could also have retrieved the engine pointer from the active context
  1681. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_FACTORY, "Dictionary@ f()", asFUNCTION(ScriptDictionaryFactory_Generic), asCALL_GENERIC);
  1682. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_LIST_FACTORY, "Dictionary @f(int &in) {repeat {String, ?}}", asFUNCTION(ScriptDictionaryListFactory_Generic), asCALL_GENERIC);
  1683. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptDictionary,AddRef), asCALL_THISCALL);
  1684. engine->RegisterObjectBehaviour("Dictionary", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptDictionary,Release), asCALL_THISCALL);
  1685. engine->RegisterObjectMethod("Dictionary", "Dictionary &opAssign(const Dictionary &in)", asMETHODPR(CScriptDictionary, operator=, (const CScriptDictionary &), CScriptDictionary&), asCALL_THISCALL);
  1686. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, ?&in)", asMETHODPR(CScriptDictionary,Set,(const String&,void*,int),void), asCALL_THISCALL);
  1687. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, ?&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,void*,int) const,bool), asCALL_THISCALL);
  1688. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, int64&in)", asMETHODPR(CScriptDictionary,Set,(const String&,asINT64&),void), asCALL_THISCALL);
  1689. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, int64&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,asINT64&) const,bool), asCALL_THISCALL);
  1690. engine->RegisterObjectMethod("Dictionary", "void Set(const String &in, double&in)", asMETHODPR(CScriptDictionary,Set,(const String&,double&),void), asCALL_THISCALL);
  1691. engine->RegisterObjectMethod("Dictionary", "bool Get(const String &in, double&out) const", asMETHODPR(CScriptDictionary,Get,(const String&,double&) const,bool), asCALL_THISCALL);
  1692. engine->RegisterObjectMethod("Dictionary", "bool Exists(const String &in) const", asMETHOD(CScriptDictionary,Exists), asCALL_THISCALL);
  1693. engine->RegisterObjectMethod("Dictionary", "bool get_empty() const", asMETHOD(CScriptDictionary, IsEmpty), asCALL_THISCALL);
  1694. engine->RegisterObjectMethod("Dictionary", "uint get_length() const", asMETHOD(CScriptDictionary, GetSize), asCALL_THISCALL);
  1695. engine->RegisterObjectMethod("Dictionary", "void Erase(const String &in)", asMETHOD(CScriptDictionary,Delete), asCALL_THISCALL);
  1696. engine->RegisterObjectMethod("Dictionary", "void Clear()", asMETHOD(CScriptDictionary,DeleteAll), asCALL_THISCALL);
  1697. engine->RegisterObjectMethod("Dictionary", "Array<String> @get_keys() const", asMETHOD(CScriptDictionary,GetKeys), asCALL_THISCALL);
  1698. }
  1699. static String StringFactory(asUINT length, const char* s)
  1700. {
  1701. return String(s, length);
  1702. }
  1703. static void ConstructString(String* ptr)
  1704. {
  1705. new(ptr) String();
  1706. }
  1707. static void ConstructStringCopy(const String& str, String* ptr)
  1708. {
  1709. new(ptr) String(str);
  1710. }
  1711. static void DestructString(String* ptr)
  1712. {
  1713. ptr->~String();
  1714. }
  1715. static char* StringCharAt(unsigned int i, String& str)
  1716. {
  1717. if (i >= str.Length())
  1718. {
  1719. asIScriptContext* context = asGetActiveContext();
  1720. if (context)
  1721. context->SetException("Index out of bounds");
  1722. return 0;
  1723. }
  1724. return &str[i];
  1725. }
  1726. static int StringCmp(const String& lhs, const String& rhs)
  1727. {
  1728. int cmp = 0;
  1729. if (lhs < rhs)
  1730. cmp = -1;
  1731. else if (lhs > rhs)
  1732. cmp = 1;
  1733. return cmp;
  1734. }
  1735. void StringResize(unsigned newSize, String& str)
  1736. {
  1737. unsigned oldSize = str.Length();
  1738. str.Resize(newSize);
  1739. for (unsigned i = oldSize; i < newSize; ++i)
  1740. str[i] = ' ';
  1741. }
  1742. static void ConstructStringInt(int value, String* ptr)
  1743. {
  1744. new(ptr) String(value);
  1745. }
  1746. static void ConstructStringUInt(unsigned value, String* ptr)
  1747. {
  1748. new(ptr) String(value);
  1749. }
  1750. static void ConstructStringFloat(float value, String* ptr)
  1751. {
  1752. new(ptr) String(value);
  1753. }
  1754. static void ConstructStringBool(bool value, String* ptr)
  1755. {
  1756. new(ptr) String(value);
  1757. }
  1758. static String& StringAssignInt(int value, String& str)
  1759. {
  1760. str = String(value);
  1761. return str;
  1762. }
  1763. static String& StringAddAssignInt(int value, String& str)
  1764. {
  1765. str += String(value);
  1766. return str;
  1767. }
  1768. static String StringAddInt(int value, const String& str)
  1769. {
  1770. return str + String(value);
  1771. }
  1772. static String StringAddIntReverse(int value, const String& str)
  1773. {
  1774. return String(value) + str;
  1775. }
  1776. static String& StringAssignUInt(unsigned value, String& str)
  1777. {
  1778. str = String(value);
  1779. return str;
  1780. }
  1781. static String& StringAddAssignUInt(unsigned value, String& str)
  1782. {
  1783. str += String(value);
  1784. return str;
  1785. }
  1786. static String StringAddUInt(unsigned value, const String& str)
  1787. {
  1788. return str + String(value);
  1789. }
  1790. static String StringAddUIntReverse(unsigned value, const String& str)
  1791. {
  1792. return String(value) + str;
  1793. }
  1794. static String& StringAssignFloat(float value, String& str)
  1795. {
  1796. str = String(value);
  1797. return str;
  1798. }
  1799. static String& StringAddAssignFloat(float value, String& str)
  1800. {
  1801. str += String(value);
  1802. return str;
  1803. }
  1804. static String StringAddFloat(float value, const String& str)
  1805. {
  1806. return str + String(value);
  1807. }
  1808. static String StringAddFloatReverse(float value, const String& str)
  1809. {
  1810. return String(value) + str;
  1811. }
  1812. static String& StringAssignBool(bool value, String& str)
  1813. {
  1814. str = String(value);
  1815. return str;
  1816. }
  1817. static String& StringAddAssignBool(bool value, String& str)
  1818. {
  1819. str += String(value);
  1820. return str;
  1821. }
  1822. static String StringAddBool(bool value, const String& str)
  1823. {
  1824. return str + String(value);
  1825. }
  1826. static String StringAddBoolReverse(bool value, const String& str)
  1827. {
  1828. return String(value) + str;
  1829. }
  1830. static void StringSetUTF8FromLatin1(const String& src, String& str)
  1831. {
  1832. str.SetUTF8FromLatin1(src.CString());
  1833. }
  1834. void RegisterString(asIScriptEngine *engine)
  1835. {
  1836. engine->RegisterObjectType("String", sizeof(String), asOBJ_VALUE | asOBJ_APP_CLASS_CDAK);
  1837. engine->RegisterStringFactory("String", asFUNCTION(StringFactory), asCALL_CDECL);
  1838. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ConstructString), asCALL_CDECL_OBJLAST);
  1839. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(const String&in)", asFUNCTION(ConstructStringCopy), asCALL_CDECL_OBJLAST);
  1840. engine->RegisterObjectBehaviour("String", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(DestructString), asCALL_CDECL_OBJLAST);
  1841. engine->RegisterObjectMethod("String", "String& opAssign(const String&in)", asMETHODPR(String, operator =, (const String&), String&), asCALL_THISCALL);
  1842. engine->RegisterObjectMethod("String", "String& opAddAssign(const String&in)", asMETHODPR(String, operator +=, (const String&), String&), asCALL_THISCALL);
  1843. engine->RegisterObjectMethod("String", "bool opEquals(const String&in) const", asMETHODPR(String, operator ==, (const String&) const, bool), asCALL_THISCALL);
  1844. engine->RegisterObjectMethod("String", "int opCmp(const String&in) const", asFUNCTION(StringCmp), asCALL_CDECL_OBJFIRST);
  1845. engine->RegisterObjectMethod("String", "String opAdd(const String&in) const", asMETHODPR(String, operator +, (const String&) const, String), asCALL_THISCALL);
  1846. engine->RegisterObjectMethod("String", "uint8 &opIndex(uint)", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  1847. engine->RegisterObjectMethod("String", "const uint8 &opIndex(uint) const", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  1848. engine->RegisterObjectMethod("String", "void Replace(uint8, uint8, bool caseSensitive = true)", asMETHODPR(String, Replace, (char, char, bool), void), asCALL_THISCALL);
  1849. engine->RegisterObjectMethod("String", "void Replace(const String&in, const String&in, bool caseSensitive = true)", asMETHODPR(String, Replace, (const String&, const String&, bool), void), asCALL_THISCALL);
  1850. engine->RegisterObjectMethod("String", "String Replaced(uint8, uint8, bool caseSensitive = true) const", asMETHODPR(String, Replaced, (char, char, bool) const, String), asCALL_THISCALL);
  1851. engine->RegisterObjectMethod("String", "String Replaced(const String&in, const String&in, bool caseSensitive = true) const", asMETHODPR(String, Replaced, (const String&, const String&, bool) const, String), asCALL_THISCALL);
  1852. engine->RegisterObjectMethod("String", "void Resize(uint)", asFUNCTION(StringResize), asCALL_CDECL_OBJLAST);
  1853. engine->RegisterObjectMethod("String", "uint Find(const String&in, uint start = 0, bool caseSensitive = true) const", asMETHODPR(String, Find, (const String&, unsigned, bool) const, unsigned), asCALL_THISCALL);
  1854. engine->RegisterObjectMethod("String", "uint Find(uint8, uint start = 0, bool caseSensitive = true) const", asMETHODPR(String, Find, (char, unsigned, bool) const, unsigned), asCALL_THISCALL);
  1855. engine->RegisterObjectMethod("String", "uint FindLast(const String&in, uint start = 0xffffffff, bool caseSensitive = true) const", asMETHODPR(String, FindLast, (const String&, unsigned, bool) const, unsigned), asCALL_THISCALL);
  1856. engine->RegisterObjectMethod("String", "uint FindLast(uint8, uint start = 0xffffffff, bool caseSensitive = true) const", asMETHODPR(String, FindLast, (char, unsigned, bool) const, unsigned), asCALL_THISCALL);
  1857. engine->RegisterObjectMethod("String", "bool StartsWith(const String&in, bool caseSensitive = true) const", asMETHOD(String, StartsWith), asCALL_THISCALL);
  1858. engine->RegisterObjectMethod("String", "bool EndsWith(const String&in, bool caseSensitive = true) const", asMETHOD(String, EndsWith), asCALL_THISCALL);
  1859. engine->RegisterObjectMethod("String", "String Substring(uint) const", asMETHODPR(String, Substring, (unsigned) const, String), asCALL_THISCALL);
  1860. engine->RegisterObjectMethod("String", "String Substring(uint, uint) const", asMETHODPR(String, Substring, (unsigned, unsigned) const, String), asCALL_THISCALL);
  1861. engine->RegisterObjectMethod("String", "String ToUpper() const", asMETHOD(String, ToUpper), asCALL_THISCALL);
  1862. engine->RegisterObjectMethod("String", "String ToLower() const", asMETHOD(String, ToLower), asCALL_THISCALL);
  1863. engine->RegisterObjectMethod("String", "String Trimmed() const", asMETHOD(String, Trimmed), asCALL_THISCALL);
  1864. engine->RegisterObjectMethod("String", "void SetUTF8FromLatin1(const String& in)", asFUNCTION(StringSetUTF8FromLatin1), asCALL_CDECL_OBJLAST);
  1865. engine->RegisterObjectMethod("String", "uint get_utf8Length() const", asMETHOD(String, LengthUTF8), asCALL_THISCALL);
  1866. engine->RegisterObjectMethod("String", "uint ByteOffsetUTF8(uint) const", asMETHOD(String, ByteOffsetUTF8), asCALL_THISCALL);
  1867. engine->RegisterObjectMethod("String", "uint NextUTF8Char(uint&) const", asMETHOD(String, NextUTF8Char), asCALL_THISCALL);
  1868. engine->RegisterObjectMethod("String", "uint AtUTF8(uint) const", asMETHOD(String, AtUTF8), asCALL_THISCALL);
  1869. engine->RegisterObjectMethod("String", "void ReplaceUTF8(uint, uint)", asMETHOD(String, ReplaceUTF8), asCALL_THISCALL);
  1870. engine->RegisterObjectMethod("String", "void AppendUTF8(uint)", asMETHOD(String, AppendUTF8), asCALL_THISCALL);
  1871. engine->RegisterObjectMethod("String", "String SubstringUTF8(uint) const", asMETHODPR(String, SubstringUTF8, (unsigned) const, String), asCALL_THISCALL);
  1872. engine->RegisterObjectMethod("String", "String SubstringUTF8(uint, uint) const", asMETHODPR(String, SubstringUTF8, (unsigned, unsigned) const, String), asCALL_THISCALL);
  1873. engine->RegisterObjectMethod("String", "uint get_length() const", asMETHOD(String, Length), asCALL_THISCALL);
  1874. engine->RegisterObjectMethod("String", "bool get_empty() const", asMETHOD(String, Empty), asCALL_THISCALL);
  1875. engine->RegisterObjectMethod("String", "int Compare(const String&in, bool caseSensitive = true) const", asMETHODPR(String, Compare, (const String&, bool) const, int), asCALL_THISCALL);
  1876. engine->RegisterObjectMethod("String", "bool Contains(const String&in, bool caseSensitive = true) const", asMETHODPR(String, Contains, (const String&, bool) const, bool), asCALL_THISCALL);
  1877. engine->RegisterObjectMethod("String", "bool Contains(uint8, bool caseSensitive = true) const", asMETHODPR(String, Contains, (char, bool) const, bool), asCALL_THISCALL);
  1878. engine->RegisterObjectMethod("String", "void Clear()", asMETHOD(String, Clear), asCALL_THISCALL);
  1879. // Register automatic conversion functions for convenience
  1880. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(int)", asFUNCTION(ConstructStringInt), asCALL_CDECL_OBJLAST);
  1881. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(uint)", asFUNCTION(ConstructStringUInt), asCALL_CDECL_OBJLAST);
  1882. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(float)", asFUNCTION(ConstructStringFloat), asCALL_CDECL_OBJLAST);
  1883. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(bool)", asFUNCTION(ConstructStringBool), asCALL_CDECL_OBJLAST);
  1884. engine->RegisterObjectMethod("String", "String& opAssign(int)", asFUNCTION(StringAssignInt), asCALL_CDECL_OBJLAST);
  1885. engine->RegisterObjectMethod("String", "String& opAddAssign(int)", asFUNCTION(StringAddAssignInt), asCALL_CDECL_OBJLAST);
  1886. engine->RegisterObjectMethod("String", "String opAdd(int) const", asFUNCTION(StringAddInt), asCALL_CDECL_OBJLAST);
  1887. engine->RegisterObjectMethod("String", "String opAdd_r(int) const", asFUNCTION(StringAddIntReverse), asCALL_CDECL_OBJLAST);
  1888. engine->RegisterObjectMethod("String", "String& opAssign(uint)", asFUNCTION(StringAssignUInt), asCALL_CDECL_OBJLAST);
  1889. engine->RegisterObjectMethod("String", "String& opAddAssign(uint)", asFUNCTION(StringAddAssignUInt), asCALL_CDECL_OBJLAST);
  1890. engine->RegisterObjectMethod("String", "String opAdd(uint) const", asFUNCTION(StringAddUInt), asCALL_CDECL_OBJLAST);
  1891. engine->RegisterObjectMethod("String", "String opAdd_r(uint) const", asFUNCTION(StringAddUIntReverse), asCALL_CDECL_OBJLAST);
  1892. engine->RegisterObjectMethod("String", "String& opAssign(float)", asFUNCTION(StringAssignFloat), asCALL_CDECL_OBJLAST);
  1893. engine->RegisterObjectMethod("String", "String& opAddAssign(float)", asFUNCTION(StringAddAssignFloat), asCALL_CDECL_OBJLAST);
  1894. engine->RegisterObjectMethod("String", "String opAdd(float) const", asFUNCTION(StringAddFloat), asCALL_CDECL_OBJLAST);
  1895. engine->RegisterObjectMethod("String", "String opAdd_r(float) const", asFUNCTION(StringAddFloatReverse), asCALL_CDECL_OBJLAST);
  1896. engine->RegisterObjectMethod("String", "String& opAssign(bool)", asFUNCTION(StringAssignBool), asCALL_CDECL_OBJLAST);
  1897. engine->RegisterObjectMethod("String", "String& opAddAssign(bool)", asFUNCTION(StringAddAssignBool), asCALL_CDECL_OBJLAST);
  1898. engine->RegisterObjectMethod("String", "String opAdd(bool) const", asFUNCTION(StringAddBool), asCALL_CDECL_OBJLAST);
  1899. engine->RegisterObjectMethod("String", "String opAdd_r(bool) const", asFUNCTION(StringAddBoolReverse), asCALL_CDECL_OBJLAST);
  1900. }
  1901. }