array.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /*************************************************************************/
  2. /* array.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "array.h"
  31. #include "container_type_validate.h"
  32. #include "core/object/class_db.h"
  33. #include "core/object/script_language.h"
  34. #include "core/templates/hashfuncs.h"
  35. #include "core/templates/vector.h"
  36. #include "core/variant/variant.h"
  37. class ArrayPrivate {
  38. public:
  39. SafeRefCount refcount;
  40. Vector<Variant> array;
  41. ContainerTypeValidate typed;
  42. };
  43. void Array::_ref(const Array &p_from) const {
  44. ArrayPrivate *_fp = p_from._p;
  45. ERR_FAIL_COND(!_fp); // should NOT happen.
  46. if (_fp == _p) {
  47. return; // whatever it is, nothing to do here move along
  48. }
  49. bool success = _fp->refcount.ref();
  50. ERR_FAIL_COND(!success); // should really not happen either
  51. _unref();
  52. _p = p_from._p;
  53. }
  54. void Array::_unref() const {
  55. if (!_p) {
  56. return;
  57. }
  58. if (_p->refcount.unref()) {
  59. memdelete(_p);
  60. }
  61. _p = nullptr;
  62. }
  63. Variant &Array::operator[](int p_idx) {
  64. return _p->array.write[p_idx];
  65. }
  66. const Variant &Array::operator[](int p_idx) const {
  67. return _p->array[p_idx];
  68. }
  69. int Array::size() const {
  70. return _p->array.size();
  71. }
  72. bool Array::is_empty() const {
  73. return _p->array.is_empty();
  74. }
  75. void Array::clear() {
  76. _p->array.clear();
  77. }
  78. bool Array::operator==(const Array &p_array) const {
  79. return _p == p_array._p;
  80. }
  81. bool Array::operator!=(const Array &p_array) const {
  82. return !operator==(p_array);
  83. }
  84. bool Array::operator<(const Array &p_array) const {
  85. int a_len = size();
  86. int b_len = p_array.size();
  87. int min_cmp = MIN(a_len, b_len);
  88. for (int i = 0; i < min_cmp; i++) {
  89. if (operator[](i) < p_array[i]) {
  90. return true;
  91. } else if (p_array[i] < operator[](i)) {
  92. return false;
  93. }
  94. }
  95. return a_len < b_len;
  96. }
  97. bool Array::operator<=(const Array &p_array) const {
  98. return !operator>(p_array);
  99. }
  100. bool Array::operator>(const Array &p_array) const {
  101. return p_array < *this;
  102. }
  103. bool Array::operator>=(const Array &p_array) const {
  104. return !operator<(p_array);
  105. }
  106. uint32_t Array::hash() const {
  107. uint32_t h = hash_djb2_one_32(0);
  108. for (int i = 0; i < _p->array.size(); i++) {
  109. h = hash_djb2_one_32(_p->array[i].hash(), h);
  110. }
  111. return h;
  112. }
  113. void Array::_assign(const Array &p_array) {
  114. if (_p->typed.type != Variant::OBJECT && _p->typed.type == p_array._p->typed.type) {
  115. //same type or untyped, just reference, shuold be fine
  116. _ref(p_array);
  117. } else if (_p->typed.type == Variant::NIL) { //from typed to untyped, must copy, but this is cheap anyway
  118. _p->array = p_array._p->array;
  119. } else if (p_array._p->typed.type == Variant::NIL) { //from untyped to typed, must try to check if they are all valid
  120. if (_p->typed.type == Variant::OBJECT) {
  121. //for objects, it needs full validation, either can be converted or fail
  122. for (int i = 0; i < p_array._p->array.size(); i++) {
  123. if (!_p->typed.validate(p_array._p->array[i], "assign")) {
  124. return;
  125. }
  126. }
  127. _p->array = p_array._p->array; //then just copy, which is cheap anyway
  128. } else {
  129. //for non objects, we need to check if there is a valid conversion, which needs to happen one by one, so this is the worst case.
  130. Vector<Variant> new_array;
  131. new_array.resize(p_array._p->array.size());
  132. for (int i = 0; i < p_array._p->array.size(); i++) {
  133. Variant src_val = p_array._p->array[i];
  134. if (src_val.get_type() == _p->typed.type) {
  135. new_array.write[i] = src_val;
  136. } else if (Variant::can_convert_strict(src_val.get_type(), _p->typed.type)) {
  137. Variant *ptr = &src_val;
  138. Callable::CallError ce;
  139. Variant::construct(_p->typed.type, new_array.write[i], (const Variant **)&ptr, 1, ce);
  140. if (ce.error != Callable::CallError::CALL_OK) {
  141. ERR_FAIL_MSG("Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  142. }
  143. } else {
  144. ERR_FAIL_MSG("Unable to convert array index " + itos(i) + " from '" + Variant::get_type_name(src_val.get_type()) + "' to '" + Variant::get_type_name(_p->typed.type) + "'.");
  145. }
  146. }
  147. _p->array = new_array;
  148. }
  149. } else if (_p->typed.can_reference(p_array._p->typed)) { //same type or compatible
  150. _ref(p_array);
  151. } else {
  152. ERR_FAIL_MSG("Assignment of arrays of incompatible types.");
  153. }
  154. }
  155. void Array::operator=(const Array &p_array) {
  156. _assign(p_array);
  157. }
  158. void Array::push_back(const Variant &p_value) {
  159. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_back"));
  160. _p->array.push_back(p_value);
  161. }
  162. void Array::append_array(const Array &p_array) {
  163. ERR_FAIL_COND(!_p->typed.validate(p_array, "append_array"));
  164. _p->array.append_array(p_array._p->array);
  165. }
  166. Error Array::resize(int p_new_size) {
  167. return _p->array.resize(p_new_size);
  168. }
  169. void Array::insert(int p_pos, const Variant &p_value) {
  170. ERR_FAIL_COND(!_p->typed.validate(p_value, "insert"));
  171. _p->array.insert(p_pos, p_value);
  172. }
  173. void Array::erase(const Variant &p_value) {
  174. ERR_FAIL_COND(!_p->typed.validate(p_value, "erase"));
  175. _p->array.erase(p_value);
  176. }
  177. Variant Array::front() const {
  178. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  179. return operator[](0);
  180. }
  181. Variant Array::back() const {
  182. ERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), "Can't take value from empty array.");
  183. return operator[](_p->array.size() - 1);
  184. }
  185. int Array::find(const Variant &p_value, int p_from) const {
  186. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find"), -1);
  187. return _p->array.find(p_value, p_from);
  188. }
  189. int Array::rfind(const Variant &p_value, int p_from) const {
  190. if (_p->array.size() == 0) {
  191. return -1;
  192. }
  193. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "rfind"), -1);
  194. if (p_from < 0) {
  195. // Relative offset from the end
  196. p_from = _p->array.size() + p_from;
  197. }
  198. if (p_from < 0 || p_from >= _p->array.size()) {
  199. // Limit to array boundaries
  200. p_from = _p->array.size() - 1;
  201. }
  202. for (int i = p_from; i >= 0; i--) {
  203. if (_p->array[i] == p_value) {
  204. return i;
  205. }
  206. }
  207. return -1;
  208. }
  209. int Array::find_last(const Variant &p_value) const {
  210. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "find_last"), -1);
  211. return rfind(p_value);
  212. }
  213. int Array::count(const Variant &p_value) const {
  214. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "count"), 0);
  215. if (_p->array.size() == 0) {
  216. return 0;
  217. }
  218. int amount = 0;
  219. for (int i = 0; i < _p->array.size(); i++) {
  220. if (_p->array[i] == p_value) {
  221. amount++;
  222. }
  223. }
  224. return amount;
  225. }
  226. bool Array::has(const Variant &p_value) const {
  227. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "use 'has'"), false);
  228. return _p->array.find(p_value, 0) != -1;
  229. }
  230. void Array::remove(int p_pos) {
  231. _p->array.remove(p_pos);
  232. }
  233. void Array::set(int p_idx, const Variant &p_value) {
  234. ERR_FAIL_COND(!_p->typed.validate(p_value, "set"));
  235. operator[](p_idx) = p_value;
  236. }
  237. const Variant &Array::get(int p_idx) const {
  238. return operator[](p_idx);
  239. }
  240. Array Array::duplicate(bool p_deep) const {
  241. Array new_arr;
  242. int element_count = size();
  243. new_arr.resize(element_count);
  244. new_arr._p->typed = _p->typed;
  245. for (int i = 0; i < element_count; i++) {
  246. new_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);
  247. }
  248. return new_arr;
  249. }
  250. int Array::_clamp_slice_index(int p_index) const {
  251. int arr_size = size();
  252. int fixed_index = CLAMP(p_index, -arr_size, arr_size - 1);
  253. if (fixed_index < 0) {
  254. fixed_index = arr_size + fixed_index;
  255. }
  256. return fixed_index;
  257. }
  258. Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { // like python, but inclusive on upper bound
  259. Array new_arr;
  260. ERR_FAIL_COND_V_MSG(p_step == 0, new_arr, "Array slice step size cannot be zero.");
  261. if (is_empty()) { // Don't try to slice empty arrays.
  262. return new_arr;
  263. }
  264. if (p_step > 0) {
  265. if (p_begin >= size() || p_end < -size()) {
  266. return new_arr;
  267. }
  268. } else { // p_step < 0
  269. if (p_begin < -size() || p_end >= size()) {
  270. return new_arr;
  271. }
  272. }
  273. int begin = _clamp_slice_index(p_begin);
  274. int end = _clamp_slice_index(p_end);
  275. int new_arr_size = MAX(((end - begin + p_step) / p_step), 0);
  276. new_arr.resize(new_arr_size);
  277. if (p_step > 0) {
  278. int dest_idx = 0;
  279. for (int idx = begin; idx <= end; idx += p_step) {
  280. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  281. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  282. }
  283. } else { // p_step < 0
  284. int dest_idx = 0;
  285. for (int idx = begin; idx >= end; idx += p_step) {
  286. ERR_FAIL_COND_V_MSG(dest_idx < 0 || dest_idx >= new_arr_size, Array(), "Bug in Array slice()");
  287. new_arr[dest_idx++] = p_deep ? get(idx).duplicate(p_deep) : get(idx);
  288. }
  289. }
  290. return new_arr;
  291. }
  292. struct _ArrayVariantSort {
  293. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  294. bool valid = false;
  295. Variant res;
  296. Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
  297. if (!valid) {
  298. res = false;
  299. }
  300. return res;
  301. }
  302. };
  303. void Array::sort() {
  304. _p->array.sort_custom<_ArrayVariantSort>();
  305. }
  306. struct _ArrayVariantSortCustom {
  307. Object *obj = nullptr;
  308. StringName func;
  309. _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
  310. const Variant *args[2] = { &p_l, &p_r };
  311. Callable::CallError err;
  312. bool res = obj->call(func, args, 2, err);
  313. if (err.error != Callable::CallError::CALL_OK) {
  314. res = false;
  315. }
  316. return res;
  317. }
  318. };
  319. void Array::sort_custom(Object *p_obj, const StringName &p_function) {
  320. ERR_FAIL_NULL(p_obj);
  321. SortArray<Variant, _ArrayVariantSortCustom, true> avs;
  322. avs.compare.obj = p_obj;
  323. avs.compare.func = p_function;
  324. avs.sort(_p->array.ptrw(), _p->array.size());
  325. }
  326. void Array::shuffle() {
  327. const int n = _p->array.size();
  328. if (n < 2) {
  329. return;
  330. }
  331. Variant *data = _p->array.ptrw();
  332. for (int i = n - 1; i >= 1; i--) {
  333. const int j = Math::rand() % (i + 1);
  334. const Variant tmp = data[j];
  335. data[j] = data[i];
  336. data[i] = tmp;
  337. }
  338. }
  339. template <typename Less>
  340. _FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {
  341. int lo = 0;
  342. int hi = p_array.size();
  343. if (p_before) {
  344. while (lo < hi) {
  345. const int mid = (lo + hi) / 2;
  346. if (p_less(p_array.get(mid), p_value)) {
  347. lo = mid + 1;
  348. } else {
  349. hi = mid;
  350. }
  351. }
  352. } else {
  353. while (lo < hi) {
  354. const int mid = (lo + hi) / 2;
  355. if (p_less(p_value, p_array.get(mid))) {
  356. hi = mid;
  357. } else {
  358. lo = mid + 1;
  359. }
  360. }
  361. }
  362. return lo;
  363. }
  364. int Array::bsearch(const Variant &p_value, bool p_before) {
  365. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "binary search"), -1);
  366. return bisect(_p->array, p_value, p_before, _ArrayVariantSort());
  367. }
  368. int Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {
  369. ERR_FAIL_COND_V(!_p->typed.validate(p_value, "custom binary search"), -1);
  370. ERR_FAIL_NULL_V(p_obj, 0);
  371. _ArrayVariantSortCustom less;
  372. less.obj = p_obj;
  373. less.func = p_function;
  374. return bisect(_p->array, p_value, p_before, less);
  375. }
  376. void Array::invert() {
  377. _p->array.invert();
  378. }
  379. void Array::push_front(const Variant &p_value) {
  380. ERR_FAIL_COND(!_p->typed.validate(p_value, "push_front"));
  381. _p->array.insert(0, p_value);
  382. }
  383. Variant Array::pop_back() {
  384. if (!_p->array.is_empty()) {
  385. int n = _p->array.size() - 1;
  386. Variant ret = _p->array.get(n);
  387. _p->array.resize(n);
  388. return ret;
  389. }
  390. return Variant();
  391. }
  392. Variant Array::pop_front() {
  393. if (!_p->array.is_empty()) {
  394. Variant ret = _p->array.get(0);
  395. _p->array.remove(0);
  396. return ret;
  397. }
  398. return Variant();
  399. }
  400. Variant Array::min() const {
  401. Variant minval;
  402. for (int i = 0; i < size(); i++) {
  403. if (i == 0) {
  404. minval = get(i);
  405. } else {
  406. bool valid;
  407. Variant ret;
  408. Variant test = get(i);
  409. Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
  410. if (!valid) {
  411. return Variant(); //not a valid comparison
  412. }
  413. if (bool(ret)) {
  414. //is less
  415. minval = test;
  416. }
  417. }
  418. }
  419. return minval;
  420. }
  421. Variant Array::max() const {
  422. Variant maxval;
  423. for (int i = 0; i < size(); i++) {
  424. if (i == 0) {
  425. maxval = get(i);
  426. } else {
  427. bool valid;
  428. Variant ret;
  429. Variant test = get(i);
  430. Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
  431. if (!valid) {
  432. return Variant(); //not a valid comparison
  433. }
  434. if (bool(ret)) {
  435. //is less
  436. maxval = test;
  437. }
  438. }
  439. }
  440. return maxval;
  441. }
  442. const void *Array::id() const {
  443. return _p->array.ptr();
  444. }
  445. Array::Array(const Array &p_from, uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  446. _p = memnew(ArrayPrivate);
  447. _p->refcount.init();
  448. set_typed(p_type, p_class_name, p_script);
  449. _assign(p_from);
  450. }
  451. void Array::set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script) {
  452. ERR_FAIL_COND_MSG(_p->array.size() > 0, "Type can only be set when array is empty.");
  453. ERR_FAIL_COND_MSG(_p->refcount.get() > 1, "Type can only be set when array has no more than one user.");
  454. ERR_FAIL_COND_MSG(_p->typed.type != Variant::NIL, "Type can only be set once.");
  455. ERR_FAIL_COND_MSG(p_class_name != StringName() && p_type != Variant::OBJECT, "Class names can only be set for type OBJECT");
  456. Ref<Script> script = p_script;
  457. ERR_FAIL_COND_MSG(script.is_valid() && p_class_name == StringName(), "Script class can only be set together with base class name");
  458. _p->typed.type = Variant::Type(p_type);
  459. _p->typed.class_name = p_class_name;
  460. _p->typed.script = script;
  461. _p->typed.where = "TypedArray";
  462. }
  463. Array::Array(const Array &p_from) {
  464. _p = nullptr;
  465. _ref(p_from);
  466. }
  467. Array::Array() {
  468. _p = memnew(ArrayPrivate);
  469. _p->refcount.init();
  470. }
  471. Array::~Array() {
  472. _unref();
  473. }