1 /* 2 * Copyright (C) 2002-2020 by the Widelands Development Team 3 * 4 * This program is free software; you can redistribute it and/or 5 * modify it under the terms of the GNU General Public License 6 * as published by the Free Software Foundation; either version 2 7 * of the License, or (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 * 18 */ 19 20 #ifndef WL_EDITOR_TOOLS_MULTI_SELECT_H 21 #define WL_EDITOR_TOOLS_MULTI_SELECT_H 22 23 #include <cassert> 24 #include <cstdint> 25 #include <cstdlib> 26 #include <vector> 27 28 /** 29 * This class allows for selection of more than just one 30 * thing. Like more than one texture, more than one map object 31 * 32 * This is a helper class, no Editor Tool (might be usable in game too) 33 */ 34 struct MultiSelect { MultiSelectMultiSelect35 MultiSelect() : nr_enabled_(0) { 36 } ~MultiSelectMultiSelect37 ~MultiSelect() { 38 } 39 enableMultiSelect40 void enable(int32_t n, bool t) { 41 if (static_cast<int32_t>(enabled_.size()) < n + 1) 42 enabled_.resize(n + 1, false); 43 44 if (enabled_[n] == t) 45 return; 46 enabled_[n] = t; 47 if (t) 48 ++nr_enabled_; 49 else 50 --nr_enabled_; 51 assert(0 <= nr_enabled_); 52 } is_enabledMultiSelect53 bool is_enabled(int32_t n) const { 54 if (static_cast<int32_t>(enabled_.size()) < n + 1) 55 return false; 56 return enabled_[n]; 57 } get_nr_enabledMultiSelect58 int32_t get_nr_enabled() const { 59 return nr_enabled_; 60 } get_random_enabledMultiSelect61 int32_t get_random_enabled() const { 62 const int32_t rand_value = 63 static_cast<int32_t>(static_cast<double>(get_nr_enabled()) * rand() / (RAND_MAX + 1.0)); 64 int32_t i = 0; 65 int32_t j = rand_value + 1; 66 while (j) { 67 if (is_enabled(i)) 68 --j; 69 ++i; 70 } 71 return i - 1; 72 } 73 74 private: 75 int32_t nr_enabled_; 76 std::vector<bool> enabled_; 77 }; 78 79 #endif // end of include guard: WL_EDITOR_TOOLS_MULTI_SELECT_H 80