├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── ProjetAI.md ├── README.md ├── bin ├── BotConfig.txt ├── data │ └── opponents │ │ ├── ai-Protoss.json │ │ ├── ai-Terran.json │ │ ├── ai-Zerg.json │ │ ├── human-Protoss.json │ │ └── human-Zerg.json └── ladderbots.json ├── cereal ├── access.hpp ├── archives │ ├── adapters.hpp │ ├── binary.hpp │ ├── json.hpp │ ├── portable_binary.hpp │ └── xml.hpp ├── cereal.hpp ├── details │ ├── helpers.hpp │ ├── polymorphic_impl.hpp │ ├── polymorphic_impl_fwd.hpp │ ├── static_object.hpp │ ├── traits.hpp │ └── util.hpp ├── external │ ├── base64.hpp │ ├── rapidjson │ │ ├── allocators.h │ │ ├── document.h │ │ ├── encodedstream.h │ │ ├── encodings.h │ │ ├── error │ │ │ ├── en.h │ │ │ └── error.h │ │ ├── filereadstream.h │ │ ├── filewritestream.h │ │ ├── fwd.h │ │ ├── internal │ │ │ ├── biginteger.h │ │ │ ├── diyfp.h │ │ │ ├── dtoa.h │ │ │ ├── ieee754.h │ │ │ ├── itoa.h │ │ │ ├── meta.h │ │ │ ├── pow10.h │ │ │ ├── regex.h │ │ │ ├── stack.h │ │ │ ├── strfunc.h │ │ │ ├── strtod.h │ │ │ └── swap.h │ │ ├── istreamwrapper.h │ │ ├── memorybuffer.h │ │ ├── memorystream.h │ │ ├── msinttypes │ │ │ ├── inttypes.h │ │ │ └── stdint.h │ │ ├── ostreamwrapper.h │ │ ├── pointer.h │ │ ├── prettywriter.h │ │ ├── rapidjson.h │ │ ├── reader.h │ │ ├── schema.h │ │ ├── stream.h │ │ ├── stringbuffer.h │ │ └── writer.h │ └── rapidxml │ │ ├── license.txt │ │ ├── manual.html │ │ ├── rapidxml.hpp │ │ ├── rapidxml_iterators.hpp │ │ ├── rapidxml_print.hpp │ │ └── rapidxml_utils.hpp ├── macros.hpp └── types │ ├── array.hpp │ ├── base_class.hpp │ ├── bitset.hpp │ ├── boost_variant.hpp │ ├── chrono.hpp │ ├── common.hpp │ ├── complex.hpp │ ├── concepts │ └── pair_associative_container.hpp │ ├── deque.hpp │ ├── forward_list.hpp │ ├── functional.hpp │ ├── list.hpp │ ├── map.hpp │ ├── memory.hpp │ ├── polymorphic.hpp │ ├── queue.hpp │ ├── set.hpp │ ├── stack.hpp │ ├── string.hpp │ ├── tuple.hpp │ ├── unordered_map.hpp │ ├── unordered_set.hpp │ ├── utility.hpp │ ├── valarray.hpp │ └── vector.hpp ├── cmake └── FindSC2Api.cmake ├── copy_bot_to_ladder.bat ├── custom_maps ├── DefeatBunker.SC2Map ├── DefeatMarines.SC2Map ├── DefeatPlanetaryFortress.SC2Map ├── DefeatSpineCrawlers.SC2Map └── DefeatWingedZerglings.SC2Map ├── linux_build.bat ├── linux_partial_build_debug.bat ├── linux_partial_build_release.bat ├── release └── CommandCenter.zip ├── run_ladder_manager.bat ├── src ├── BaseLocation.cpp ├── BaseLocation.h ├── BaseLocationManager.cpp ├── BaseLocationManager.h ├── Behavior.h ├── BehaviorTreeBuilder.h ├── BotAssert.cpp ├── BotAssert.h ├── BotConfig.cpp ├── BotConfig.h ├── BuildOrder.cpp ├── BuildOrder.h ├── BuildOrderQueue.cpp ├── BuildOrderQueue.h ├── Building.cpp ├── Building.h ├── BuildingData.cpp ├── BuildingData.h ├── BuildingManager.cpp ├── BuildingManager.h ├── BuildingPlacer.cpp ├── BuildingPlacer.h ├── CCBot.cpp ├── CCBot.h ├── CMakeLists.txt ├── CombatAnalyzer.cpp ├── CombatAnalyzer.h ├── CombatCommander.cpp ├── CombatCommander.h ├── Common.h ├── Condition.cpp ├── Condition.h ├── DistanceMap.cpp ├── DistanceMap.h ├── GameCommander.cpp ├── GameCommander.h ├── JSONTools.cpp ├── JSONTools.h ├── LadderInterface.h ├── MapTools.cpp ├── MapTools.h ├── MeleeManager.cpp ├── MeleeManager.h ├── MetaType.cpp ├── MetaType.h ├── MetaTypeEnum.cpp ├── MetaTypeEnum.h ├── Micro.cpp ├── Micro.h ├── MicroManager.cpp ├── MicroManager.h ├── ProductionManager.cpp ├── ProductionManager.h ├── RangedManager.cpp ├── RangedManager.h ├── RepairStationManager.cpp ├── RepairStationManager.h ├── ScoutManager.cpp ├── ScoutManager.h ├── Squad.cpp ├── Squad.h ├── SquadData.cpp ├── SquadData.h ├── SquadOrder.cpp ├── SquadOrder.h ├── StackWalker.cpp ├── StackWalker.h ├── Strategy.h ├── StrategyManager.cpp ├── StrategyManager.h ├── TechTree.cpp ├── TechTree.h ├── TechTree.json ├── Timer.hpp ├── Unit.cpp ├── Unit.h ├── UnitData.cpp ├── UnitData.h ├── UnitInfoManager.cpp ├── UnitInfoManager.h ├── UnitState.cpp ├── UnitState.h ├── UnitType.cpp ├── UnitType.h ├── Util.cpp ├── Util.h ├── WorkerData.cpp ├── WorkerData.h ├── WorkerManager.cpp ├── WorkerManager.h ├── json │ └── json.hpp ├── libvoxelbot │ ├── buildorder │ │ ├── build_order.cpp │ │ ├── build_order.h │ │ ├── build_state.cpp │ │ ├── build_state.h │ │ ├── build_time_estimator.cpp │ │ ├── build_time_estimator.h │ │ ├── optimizer.cpp │ │ ├── optimizer.h │ │ ├── tracker.cpp │ │ └── tracker.h │ ├── caching │ │ ├── caching.cpp │ │ ├── dependency_analyzer.cpp │ │ └── dependency_analyzer.h │ ├── combat │ │ ├── combat_environment.cpp │ │ ├── combat_environment.h │ │ ├── combat_upgrades.cpp │ │ ├── combat_upgrades.h │ │ ├── simulator.cpp │ │ └── simulator.h │ ├── common │ │ ├── unit_lists.cpp │ │ └── unit_lists.h │ ├── generated │ │ ├── abilities.cpp │ │ ├── abilities.h │ │ ├── abilities.txt │ │ ├── abilities_data.h │ │ ├── units.data │ │ ├── units.txt │ │ ├── units_data.h │ │ ├── units_verify.txt │ │ ├── units_with_tech.txt │ │ └── upgrades_data.h │ └── utilities │ │ ├── build_state_serialization.h │ │ ├── bump_allocator.h │ │ ├── cereal_json.h │ │ ├── influence.cpp │ │ ├── influence.h │ │ ├── ladder_interface.h │ │ ├── mappings.cpp │ │ ├── mappings.h │ │ ├── pathfinding.cpp │ │ ├── pathfinding.h │ │ ├── predicates.cpp │ │ ├── predicates.h │ │ ├── profiler.cpp │ │ ├── profiler.h │ │ ├── python_utils.cpp │ │ ├── python_utils.h │ │ ├── sc2_serialization.h │ │ ├── stdutils.h │ │ ├── unit_data_caching.cpp │ │ └── unit_data_caching.h └── main.cpp └── vs ├── CommandCenter.aps ├── CommandCenter.rc ├── CommandCenter.sdf ├── CommandCenter.sln ├── CommandCenter.vcxproj.filters ├── CommandCenter.vcxproj.user └── resource.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Cmake build routine 2 | CMakeCache.txt 3 | CMakeFiles/ 4 | Makefile 5 | cmake_install.cmake 6 | 7 | # IDEs 8 | .vscode/ 9 | 10 | **/vs/.vs/ 11 | **/vs/commandcenter 12 | **/vs/*.user 13 | **/vs/CommandCenter.vcxproj 14 | **/Debug # **/ not working ? 15 | **/Release 16 | 17 | **/bin/CommandCenter 18 | **/bin/*.exe 19 | **/bin/*.ilk 20 | **/bin/TechTree.json 21 | commandcenter/vs/CommandCenter/Debug 22 | commandcenter/vs/CommandCenter/Release 23 | 24 | vs/.vs/ 25 | vs/commandcenter 26 | 27 | bin/CommandCenter 28 | bin/*.exe 29 | bin/*.ilk 30 | bin/TechTree.json 31 | bin/data/*.json 32 | *.tlog 33 | *.obj 34 | vs/RelWithDebInfo/CommandCenter.log 35 | *.log 36 | *.pdb 37 | vs/CommandCenter.vcxproj 38 | vs/CommandCenter.VC.db 39 | src/*.TMP 40 | Cmder.exe.lnk -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.1) 2 | 3 | project(CommandCenter) 4 | 5 | # Specify output directories. 6 | set(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin") 7 | 8 | # Include custom macros to find SC2Api. 9 | set (CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") 10 | 11 | find_package(SC2Api REQUIRED) 12 | 13 | # Build with c++14 support, required by sc2api. 14 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++14") 15 | set(CMAKE_CXX_STANDARD 14) 16 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 17 | set(CMAKE_CXX_EXTENSIONS OFF) 18 | 19 | # Activate dynamic linking to allow the backtrace to find symbol info 20 | SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "-rdynamic") 21 | 22 | add_subdirectory("src") 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 David Churchill 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ProjetAI.md: -------------------------------------------------------------------------------- 1 | # Équipe Symbolique: CommandCenter-Clone 2 | Projet largement basé sur le projet CommandCenter écrit par [David Churchill](http://www.cs.mun.ca/~dchurchill/), qui est basé sur l'architecture de [UAlbertaBot](https://github.com/davechurchill/ualbertabot/wiki). Le bot est écrit en C++ et utilise l'API [StarCraft II AI API](https://github.com/Blizzard/s2client-api). Pour plus d'information du projet de base CommandCenter, lisez la [documentation officielle](README.md). 3 | 4 | # Installation et compilation du projet (Windows) 5 | 6 | * Télécharger et installer [Visual Studio 2017](https://www.visualstudio.com/downloads/) 7 | * Télécharger et installer la [version précompiler de StarCraft II AI API](https://github.com/Blizzard/s2client-api#precompiled-libs). 8 | * Télécharger et installer StarCraft II 9 | * Télécharger les "Map Packs" du jeu (Vous pouvez trouver les cartes [ici](https://github.com/Blizzard/s2client-proto#downloads)) 10 | * Ajouter les cartes à la racine de `C:\Program Files (x86)\StarCraft II\Maps`. 11 | * Ajouter les variable système suivante: 12 | * `SC2API_DIR`: chemin vers la SC2API (ex: `C:\Libraries\SC2API_Binary_vs2017`) 13 | * `SC2PATH`: chemin vers le jeu StarCraft II (ex: `C:\Program Files (x86)\StarCraft II`) 14 | * Cloner le projer 15 | * Ouvrir "CommandCenter/vs/CommandCenter.sln" dans VS2017 16 | * Définir SC2API dans les librairies à inclure dans le projet Visual Studio. 17 | * Clic droit sur le projet CommandCenter dans VS2017 18 | * Sélectionner "Properties" 19 | * Sélectionner la configuration de compilation dans le coin gauche ("Release" ou "Debug") 20 | * Sélectionner "VC++ Directories" dans le menu à gauche 21 | * Modifier l'option "Include Directories" dans la table à droite pour `$(SC2API_DIR)\include;$(IncludePath)` 22 | * Modifier l'option "Library Directories" dans la table à droite pour `$(SC2API_DIR)\lib;$(LibraryPath)` 23 | * Encore dans la fenêtre "Properties", sélectionner "Working Directory" dans le menu à gauche. 24 | * Modifier l'option "Debugging" pour `$(ProjectDir)/../bin/` 25 | * Lancer l'exécution en appuyant sur la touche `F5` 26 | 27 | # Changements apportés au projet de base CommandCenter 28 | 29 | TODO 30 | -------------------------------------------------------------------------------- /bin/data/opponents/ai-Protoss.json: -------------------------------------------------------------------------------- 1 | {"strategies":[{"losses":1,"wins":30},{"losses":0,"wins":0},{"losses":0,"wins":0},{"losses":0,"wins":0},{"losses":0,"wins":17}]} -------------------------------------------------------------------------------- /bin/data/opponents/ai-Terran.json: -------------------------------------------------------------------------------- 1 | {"strategies":[{"losses":11,"wins":0},{"losses":25,"wins":100},{"losses":1,"wins":0},{"losses":0,"wins":0},{"losses":1,"wins":0},{"losses":1,"wins":0}]} -------------------------------------------------------------------------------- /bin/data/opponents/ai-Zerg.json: -------------------------------------------------------------------------------- 1 | {"strategies":[{"losses":1,"wins":69},{"losses":1,"wins":0},{"losses":1,"wins":0},{"losses":0,"wins":0},{"losses":1,"wins":0},{"losses":1,"wins":0}]} -------------------------------------------------------------------------------- /bin/data/opponents/human-Protoss.json: -------------------------------------------------------------------------------- 1 | {"strategies":[{"losses":1,"wins":1},{"losses":1,"wins":0},{"losses":1,"wins":0},{"losses":0,"wins":0},{"losses":2,"wins":9},{"losses":1,"wins":0}]} -------------------------------------------------------------------------------- /bin/data/opponents/human-Zerg.json: -------------------------------------------------------------------------------- 1 | {"strategies":[{"losses":0,"wins":2},{"losses":0,"wins":0},{"losses":0,"wins":0},{"losses":0,"wins":0},{"losses":0,"wins":0}]} -------------------------------------------------------------------------------- /bin/ladderbots.json: -------------------------------------------------------------------------------- 1 | { 2 | "Bots": { 3 | "MicroMachine": { 4 | "Race": "Terran", 5 | "Type": "BinaryCpp", 6 | "RootPath": "./", 7 | "FileName": "MicroMachine.exe" 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /cereal/details/polymorphic_impl_fwd.hpp: -------------------------------------------------------------------------------- 1 | /*! \file polymorphic_impl_fwd.hpp 2 | \brief Internal polymorphism support forward declarations 3 | \ingroup Internal */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | /* This code is heavily inspired by the boost serialization implementation by the following authors 32 | 33 | (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . 34 | Use, modification and distribution is subject to the Boost Software 35 | License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt) 36 | 37 | See http://www.boost.org for updates, documentation, and revision history. 38 | 39 | (C) Copyright 2006 David Abrahams - http://www.boost.org. 40 | 41 | See /boost/serialization/export.hpp and /boost/archive/detail/register_archive.hpp for their 42 | implementation. 43 | */ 44 | 45 | #ifndef CEREAL_DETAILS_POLYMORPHIC_IMPL_FWD_HPP_ 46 | #define CEREAL_DETAILS_POLYMORPHIC_IMPL_FWD_HPP_ 47 | 48 | namespace cereal 49 | { 50 | namespace detail 51 | { 52 | //! Forward declaration, see polymorphic_impl.hpp for more information 53 | template 54 | struct RegisterPolymorphicCaster; 55 | 56 | //! Forward declaration, see polymorphic_impl.hpp for more information 57 | struct PolymorphicCasters; 58 | 59 | //! Forward declaration, see polymorphic_impl.hpp for more information 60 | template 61 | struct PolymorphicRelation; 62 | } // namespace detail 63 | } // namespace cereal 64 | 65 | #endif // CEREAL_DETAILS_POLYMORPHIC_IMPL_FWD_HPP_ 66 | -------------------------------------------------------------------------------- /cereal/details/util.hpp: -------------------------------------------------------------------------------- 1 | /*! \file util.hpp 2 | \brief Internal misc utilities 3 | \ingroup Internal */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_DETAILS_UTIL_HPP_ 31 | #define CEREAL_DETAILS_UTIL_HPP_ 32 | 33 | #include 34 | #include 35 | 36 | #ifdef _MSC_VER 37 | namespace cereal 38 | { 39 | namespace util 40 | { 41 | //! Demangles the type encoded in a string 42 | /*! @internal */ 43 | inline std::string demangle( std::string const & name ) 44 | { return name; } 45 | 46 | //! Gets the demangled name of a type 47 | /*! @internal */ 48 | template inline 49 | std::string demangledName() 50 | { return typeid( T ).name(); } 51 | } // namespace util 52 | } // namespace cereal 53 | #else // clang or gcc 54 | #include 55 | #include 56 | namespace cereal 57 | { 58 | namespace util 59 | { 60 | //! Demangles the type encoded in a string 61 | /*! @internal */ 62 | inline std::string demangle(std::string mangledName) 63 | { 64 | int status = 0; 65 | char *demangledName = nullptr; 66 | std::size_t len; 67 | 68 | demangledName = abi::__cxa_demangle(mangledName.c_str(), 0, &len, &status); 69 | 70 | std::string retName(demangledName); 71 | free(demangledName); 72 | 73 | return retName; 74 | } 75 | 76 | //! Gets the demangled name of a type 77 | /*! @internal */ 78 | template inline 79 | std::string demangledName() 80 | { return demangle(typeid(T).name()); } 81 | } 82 | } // namespace cereal 83 | #endif // clang or gcc branch of _MSC_VER 84 | #endif // CEREAL_DETAILS_UTIL_HPP_ 85 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/filereadstream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_FILEREADSTREAM_H_ 16 | #define CEREAL_RAPIDJSON_FILEREADSTREAM_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | CEREAL_RAPIDJSON_DIAG_PUSH 23 | CEREAL_RAPIDJSON_DIAG_OFF(padded) 24 | CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) 25 | CEREAL_RAPIDJSON_DIAG_OFF(missing-noreturn) 26 | #endif 27 | 28 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 29 | 30 | //! File byte stream for input using fread(). 31 | /*! 32 | \note implements Stream concept 33 | */ 34 | class FileReadStream { 35 | public: 36 | typedef char Ch; //!< Character type (byte). 37 | 38 | //! Constructor. 39 | /*! 40 | \param fp File pointer opened for read. 41 | \param buffer user-supplied buffer. 42 | \param bufferSize size of buffer in bytes. Must >=4 bytes. 43 | */ 44 | FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { 45 | CEREAL_RAPIDJSON_ASSERT(fp_ != 0); 46 | CEREAL_RAPIDJSON_ASSERT(bufferSize >= 4); 47 | Read(); 48 | } 49 | 50 | Ch Peek() const { return *current_; } 51 | Ch Take() { Ch c = *current_; Read(); return c; } 52 | size_t Tell() const { return count_ + static_cast(current_ - buffer_); } 53 | 54 | // Not implemented 55 | void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } 56 | void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } 57 | Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 58 | size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 59 | 60 | // For encoding detection only. 61 | const Ch* Peek4() const { 62 | return (current_ + 4 <= bufferLast_) ? current_ : 0; 63 | } 64 | 65 | private: 66 | void Read() { 67 | if (current_ < bufferLast_) 68 | ++current_; 69 | else if (!eof_) { 70 | count_ += readCount_; 71 | readCount_ = fread(buffer_, 1, bufferSize_, fp_); 72 | bufferLast_ = buffer_ + readCount_ - 1; 73 | current_ = buffer_; 74 | 75 | if (readCount_ < bufferSize_) { 76 | buffer_[readCount_] = '\0'; 77 | ++bufferLast_; 78 | eof_ = true; 79 | } 80 | } 81 | } 82 | 83 | std::FILE* fp_; 84 | Ch *buffer_; 85 | size_t bufferSize_; 86 | Ch *bufferLast_; 87 | Ch *current_; 88 | size_t readCount_; 89 | size_t count_; //!< Number of characters read 90 | bool eof_; 91 | }; 92 | 93 | CEREAL_RAPIDJSON_NAMESPACE_END 94 | 95 | #ifdef __clang__ 96 | CEREAL_RAPIDJSON_DIAG_POP 97 | #endif 98 | 99 | #endif // CEREAL_RAPIDJSON_FILESTREAM_H_ 100 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/filewritestream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_FILEWRITESTREAM_H_ 16 | #define CEREAL_RAPIDJSON_FILEWRITESTREAM_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | CEREAL_RAPIDJSON_DIAG_PUSH 23 | CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) 24 | #endif 25 | 26 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Wrapper of C file stream for input using fread(). 29 | /*! 30 | \note implements Stream concept 31 | */ 32 | class FileWriteStream { 33 | public: 34 | typedef char Ch; //!< Character type. Only support char. 35 | 36 | FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { 37 | CEREAL_RAPIDJSON_ASSERT(fp_ != 0); 38 | } 39 | 40 | void Put(char c) { 41 | if (current_ >= bufferEnd_) 42 | Flush(); 43 | 44 | *current_++ = c; 45 | } 46 | 47 | void PutN(char c, size_t n) { 48 | size_t avail = static_cast(bufferEnd_ - current_); 49 | while (n > avail) { 50 | std::memset(current_, c, avail); 51 | current_ += avail; 52 | Flush(); 53 | n -= avail; 54 | avail = static_cast(bufferEnd_ - current_); 55 | } 56 | 57 | if (n > 0) { 58 | std::memset(current_, c, n); 59 | current_ += n; 60 | } 61 | } 62 | 63 | void Flush() { 64 | if (current_ != buffer_) { 65 | size_t result = fwrite(buffer_, 1, static_cast(current_ - buffer_), fp_); 66 | if (result < static_cast(current_ - buffer_)) { 67 | // failure deliberately ignored at this time 68 | // added to avoid warn_unused_result build errors 69 | } 70 | current_ = buffer_; 71 | } 72 | } 73 | 74 | // Not implemented 75 | char Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 76 | char Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 77 | size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 78 | char* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 79 | size_t PutEnd(char*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 80 | 81 | private: 82 | // Prohibit copy constructor & assignment operator. 83 | FileWriteStream(const FileWriteStream&); 84 | FileWriteStream& operator=(const FileWriteStream&); 85 | 86 | std::FILE* fp_; 87 | char *buffer_; 88 | char *bufferEnd_; 89 | char *current_; 90 | }; 91 | 92 | //! Implement specialized version of PutN() with memset() for better performance. 93 | template<> 94 | inline void PutN(FileWriteStream& stream, char c, size_t n) { 95 | stream.PutN(c, n); 96 | } 97 | 98 | CEREAL_RAPIDJSON_NAMESPACE_END 99 | 100 | #ifdef __clang__ 101 | CEREAL_RAPIDJSON_DIAG_POP 102 | #endif 103 | 104 | #endif // CEREAL_RAPIDJSON_FILESTREAM_H_ 105 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/internal/ieee754.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_IEEE754_ 16 | #define CEREAL_RAPIDJSON_IEEE754_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | class Double { 24 | public: 25 | Double() {} 26 | Double(double d) : d_(d) {} 27 | Double(uint64_t u) : u_(u) {} 28 | 29 | double Value() const { return d_; } 30 | uint64_t Uint64Value() const { return u_; } 31 | 32 | double NextPositiveDouble() const { 33 | CEREAL_RAPIDJSON_ASSERT(!Sign()); 34 | return Double(u_ + 1).Value(); 35 | } 36 | 37 | bool Sign() const { return (u_ & kSignMask) != 0; } 38 | uint64_t Significand() const { return u_ & kSignificandMask; } 39 | int Exponent() const { return static_cast(((u_ & kExponentMask) >> kSignificandSize) - kExponentBias); } 40 | 41 | bool IsNan() const { return (u_ & kExponentMask) == kExponentMask && Significand() != 0; } 42 | bool IsInf() const { return (u_ & kExponentMask) == kExponentMask && Significand() == 0; } 43 | bool IsNanOrInf() const { return (u_ & kExponentMask) == kExponentMask; } 44 | bool IsNormal() const { return (u_ & kExponentMask) != 0 || Significand() == 0; } 45 | bool IsZero() const { return (u_ & (kExponentMask | kSignificandMask)) == 0; } 46 | 47 | uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); } 48 | int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; } 49 | uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; } 50 | 51 | static unsigned EffectiveSignificandSize(int order) { 52 | if (order >= -1021) 53 | return 53; 54 | else if (order <= -1074) 55 | return 0; 56 | else 57 | return static_cast(order) + 1074; 58 | } 59 | 60 | private: 61 | static const int kSignificandSize = 52; 62 | static const int kExponentBias = 0x3FF; 63 | static const int kDenormalExponent = 1 - kExponentBias; 64 | static const uint64_t kSignMask = CEREAL_RAPIDJSON_UINT64_C2(0x80000000, 0x00000000); 65 | static const uint64_t kExponentMask = CEREAL_RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); 66 | static const uint64_t kSignificandMask = CEREAL_RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); 67 | static const uint64_t kHiddenBit = CEREAL_RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); 68 | 69 | union { 70 | double d_; 71 | uint64_t u_; 72 | }; 73 | }; 74 | 75 | } // namespace internal 76 | CEREAL_RAPIDJSON_NAMESPACE_END 77 | 78 | #endif // CEREAL_RAPIDJSON_IEEE754_ 79 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/internal/pow10.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_POW10_ 16 | #define CEREAL_RAPIDJSON_POW10_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | //! Computes integer powers of 10 in double (10.0^n). 24 | /*! This function uses lookup table for fast and accurate results. 25 | \param n non-negative exponent. Must <= 308. 26 | \return 10.0^n 27 | */ 28 | inline double Pow10(int n) { 29 | static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes 30 | 1e+0, 31 | 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, 32 | 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, 33 | 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, 34 | 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, 35 | 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, 36 | 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120, 37 | 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140, 38 | 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160, 39 | 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180, 40 | 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200, 41 | 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220, 42 | 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240, 43 | 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260, 44 | 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280, 45 | 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300, 46 | 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308 47 | }; 48 | CEREAL_RAPIDJSON_ASSERT(n >= 0 && n <= 308); 49 | return e[n]; 50 | } 51 | 52 | } // namespace internal 53 | CEREAL_RAPIDJSON_NAMESPACE_END 54 | 55 | #endif // CEREAL_RAPIDJSON_POW10_ 56 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/internal/strfunc.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ 16 | #define CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ 17 | 18 | #include "../stream.h" 19 | 20 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 21 | namespace internal { 22 | 23 | //! Custom strlen() which works on different character types. 24 | /*! \tparam Ch Character type (e.g. char, wchar_t, short) 25 | \param s Null-terminated input string. 26 | \return Number of characters in the string. 27 | \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. 28 | */ 29 | template 30 | inline SizeType StrLen(const Ch* s) { 31 | const Ch* p = s; 32 | while (*p) ++p; 33 | return SizeType(p - s); 34 | } 35 | 36 | //! Returns number of code points in a encoded string. 37 | template 38 | bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) { 39 | GenericStringStream is(s); 40 | const typename Encoding::Ch* end = s + length; 41 | SizeType count = 0; 42 | while (is.src_ < end) { 43 | unsigned codepoint; 44 | if (!Encoding::Decode(is, &codepoint)) 45 | return false; 46 | count++; 47 | } 48 | *outCount = count; 49 | return true; 50 | } 51 | 52 | } // namespace internal 53 | CEREAL_RAPIDJSON_NAMESPACE_END 54 | 55 | #endif // CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ 56 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/internal/swap.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_INTERNAL_SWAP_H_ 16 | #define CEREAL_RAPIDJSON_INTERNAL_SWAP_H_ 17 | 18 | #include "../rapidjson.h" 19 | 20 | #if defined(__clang__) 21 | CEREAL_RAPIDJSON_DIAG_PUSH 22 | CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) 23 | #endif 24 | 25 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 26 | namespace internal { 27 | 28 | //! Custom swap() to avoid dependency on C++ header 29 | /*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. 30 | \note This has the same semantics as std::swap(). 31 | */ 32 | template 33 | inline void Swap(T& a, T& b) CEREAL_RAPIDJSON_NOEXCEPT { 34 | T tmp = a; 35 | a = b; 36 | b = tmp; 37 | } 38 | 39 | } // namespace internal 40 | CEREAL_RAPIDJSON_NAMESPACE_END 41 | 42 | #if defined(__clang__) 43 | CEREAL_RAPIDJSON_DIAG_POP 44 | #endif 45 | 46 | #endif // CEREAL_RAPIDJSON_INTERNAL_SWAP_H_ 47 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/memorybuffer.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_MEMORYBUFFER_H_ 16 | #define CEREAL_RAPIDJSON_MEMORYBUFFER_H_ 17 | 18 | #include "stream.h" 19 | #include "internal/stack.h" 20 | 21 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 22 | 23 | //! Represents an in-memory output byte stream. 24 | /*! 25 | This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. 26 | 27 | It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. 28 | 29 | Differences between MemoryBuffer and StringBuffer: 30 | 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. 31 | 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. 32 | 33 | \tparam Allocator type for allocating memory buffer. 34 | \note implements Stream concept 35 | */ 36 | template 37 | struct GenericMemoryBuffer { 38 | typedef char Ch; // byte 39 | 40 | GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} 41 | 42 | void Put(Ch c) { *stack_.template Push() = c; } 43 | void Flush() {} 44 | 45 | void Clear() { stack_.Clear(); } 46 | void ShrinkToFit() { stack_.ShrinkToFit(); } 47 | Ch* Push(size_t count) { return stack_.template Push(count); } 48 | void Pop(size_t count) { stack_.template Pop(count); } 49 | 50 | const Ch* GetBuffer() const { 51 | return stack_.template Bottom(); 52 | } 53 | 54 | size_t GetSize() const { return stack_.GetSize(); } 55 | 56 | static const size_t kDefaultCapacity = 256; 57 | mutable internal::Stack stack_; 58 | }; 59 | 60 | typedef GenericMemoryBuffer<> MemoryBuffer; 61 | 62 | //! Implement specialized version of PutN() with memset() for better performance. 63 | template<> 64 | inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { 65 | std::memset(memoryBuffer.stack_.Push(n), c, n * sizeof(c)); 66 | } 67 | 68 | CEREAL_RAPIDJSON_NAMESPACE_END 69 | 70 | #endif // CEREAL_RAPIDJSON_MEMORYBUFFER_H_ 71 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/memorystream.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_MEMORYSTREAM_H_ 16 | #define CEREAL_RAPIDJSON_MEMORYSTREAM_H_ 17 | 18 | #include "stream.h" 19 | 20 | #ifdef __clang__ 21 | CEREAL_RAPIDJSON_DIAG_PUSH 22 | CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) 23 | CEREAL_RAPIDJSON_DIAG_OFF(missing-noreturn) 24 | #endif 25 | 26 | #ifdef _MSC_VER 27 | CEREAL_RAPIDJSON_DIAG_PUSH 28 | CEREAL_RAPIDJSON_DIAG_OFF( 4127 ) // ignore assert(false) for triggering exception 29 | #endif 30 | 31 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 32 | 33 | //! Represents an in-memory input byte stream. 34 | /*! 35 | This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream. 36 | 37 | It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file. 38 | 39 | Differences between MemoryStream and StringStream: 40 | 1. StringStream has encoding but MemoryStream is a byte stream. 41 | 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source. 42 | 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4(). 43 | \note implements Stream concept 44 | */ 45 | struct MemoryStream { 46 | typedef char Ch; // byte 47 | 48 | MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} 49 | 50 | Ch Peek() const { return CEREAL_RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; } 51 | Ch Take() { return CEREAL_RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; } 52 | size_t Tell() const { return static_cast(src_ - begin_); } 53 | 54 | Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 55 | void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } 56 | void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } 57 | size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 58 | 59 | // For encoding detection only. 60 | const Ch* Peek4() const { 61 | return Tell() + 4 <= size_ ? src_ : 0; 62 | } 63 | 64 | const Ch* src_; //!< Current read position. 65 | const Ch* begin_; //!< Original head of the string. 66 | const Ch* end_; //!< End of stream. 67 | size_t size_; //!< Size of the stream. 68 | }; 69 | 70 | CEREAL_RAPIDJSON_NAMESPACE_END 71 | 72 | #if defined(__clang__) || defined(_MSC_VER) 73 | CEREAL_RAPIDJSON_DIAG_POP 74 | #endif 75 | 76 | #endif // CEREAL_RAPIDJSON_MEMORYBUFFER_H_ 77 | -------------------------------------------------------------------------------- /cereal/external/rapidjson/ostreamwrapper.h: -------------------------------------------------------------------------------- 1 | // Tencent is pleased to support the open source community by making RapidJSON available. 2 | // 3 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. 4 | // 5 | // Licensed under the MIT License (the "License"); you may not use this file except 6 | // in compliance with the License. You may obtain a copy of the License at 7 | // 8 | // http://opensource.org/licenses/MIT 9 | // 10 | // Unless required by applicable law or agreed to in writing, software distributed 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the 13 | // specific language governing permissions and limitations under the License. 14 | 15 | #ifndef CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ 16 | #define CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ 17 | 18 | #include "stream.h" 19 | #include 20 | 21 | #ifdef __clang__ 22 | CEREAL_RAPIDJSON_DIAG_PUSH 23 | CEREAL_RAPIDJSON_DIAG_OFF(padded) 24 | #endif 25 | 26 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN 27 | 28 | //! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept. 29 | /*! 30 | The classes can be wrapped including but not limited to: 31 | 32 | - \c std::ostringstream 33 | - \c std::stringstream 34 | - \c std::wpstringstream 35 | - \c std::wstringstream 36 | - \c std::ifstream 37 | - \c std::fstream 38 | - \c std::wofstream 39 | - \c std::wfstream 40 | 41 | \tparam StreamType Class derived from \c std::basic_ostream. 42 | */ 43 | 44 | template 45 | class BasicOStreamWrapper { 46 | public: 47 | typedef typename StreamType::char_type Ch; 48 | BasicOStreamWrapper(StreamType& stream) : stream_(stream) {} 49 | 50 | void Put(Ch c) { 51 | stream_.put(c); 52 | } 53 | 54 | void Flush() { 55 | stream_.flush(); 56 | } 57 | 58 | // Not implemented 59 | char Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 60 | char Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 61 | size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 62 | char* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 63 | size_t PutEnd(char*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } 64 | 65 | private: 66 | BasicOStreamWrapper(const BasicOStreamWrapper&); 67 | BasicOStreamWrapper& operator=(const BasicOStreamWrapper&); 68 | 69 | StreamType& stream_; 70 | }; 71 | 72 | typedef BasicOStreamWrapper OStreamWrapper; 73 | typedef BasicOStreamWrapper WOStreamWrapper; 74 | 75 | #ifdef __clang__ 76 | CEREAL_RAPIDJSON_DIAG_POP 77 | #endif 78 | 79 | CEREAL_RAPIDJSON_NAMESPACE_END 80 | 81 | #endif // CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ 82 | -------------------------------------------------------------------------------- /cereal/external/rapidxml/license.txt: -------------------------------------------------------------------------------- 1 | Use of this software is granted under one of the following two licenses, 2 | to be chosen freely by the user. 3 | 4 | 1. Boost Software License - Version 1.0 - August 17th, 2003 5 | =============================================================================== 6 | 7 | Copyright (c) 2006, 2007 Marcin Kalicinski 8 | 9 | Permission is hereby granted, free of charge, to any person or organization 10 | obtaining a copy of the software and accompanying documentation covered by 11 | this license (the "Software") to use, reproduce, display, distribute, 12 | execute, and transmit the Software, and to prepare derivative works of the 13 | Software, and to permit third-parties to whom the Software is furnished to 14 | do so, all subject to the following: 15 | 16 | The copyright notices in the Software and this entire statement, including 17 | the above license grant, this restriction and the following disclaimer, 18 | must be included in all copies of the Software, in whole or in part, and 19 | all derivative works of the Software, unless such copies or derivative 20 | works are solely in the form of machine-executable object code generated by 21 | a source language processor. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT 26 | SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE 27 | FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, 28 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 29 | DEALINGS IN THE SOFTWARE. 30 | 31 | 2. The MIT License 32 | =============================================================================== 33 | 34 | Copyright (c) 2006, 2007 Marcin Kalicinski 35 | 36 | Permission is hereby granted, free of charge, to any person obtaining a copy 37 | of this software and associated documentation files (the "Software"), to deal 38 | in the Software without restriction, including without limitation the rights 39 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 40 | of the Software, and to permit persons to whom the Software is furnished to do so, 41 | subject to the following conditions: 42 | 43 | The above copyright notice and this permission notice shall be included in all 44 | copies or substantial portions of the Software. 45 | 46 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 47 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 48 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 49 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 50 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 51 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 52 | IN THE SOFTWARE. 53 | -------------------------------------------------------------------------------- /cereal/external/rapidxml/rapidxml_utils.hpp: -------------------------------------------------------------------------------- 1 | #ifndef CEREAL_RAPIDXML_UTILS_HPP_INCLUDED 2 | #define CEREAL_RAPIDXML_UTILS_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective. 8 | 9 | #include "rapidxml.hpp" 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | namespace cereal { 16 | namespace rapidxml 17 | { 18 | 19 | //! Represents data loaded from a file 20 | template 21 | class file 22 | { 23 | 24 | public: 25 | 26 | //! Loads file into the memory. Data will be automatically destroyed by the destructor. 27 | //! \param filename Filename to load. 28 | file(const char *filename) 29 | { 30 | using namespace std; 31 | 32 | // Open stream 33 | basic_ifstream stream(filename, ios::binary); 34 | if (!stream) 35 | throw runtime_error(string("cannot open file ") + filename); 36 | stream.unsetf(ios::skipws); 37 | 38 | // Determine stream size 39 | stream.seekg(0, ios::end); 40 | size_t size = stream.tellg(); 41 | stream.seekg(0); 42 | 43 | // Load data and add terminating 0 44 | m_data.resize(size + 1); 45 | stream.read(&m_data.front(), static_cast(size)); 46 | m_data[size] = 0; 47 | } 48 | 49 | //! Loads file into the memory. Data will be automatically destroyed by the destructor 50 | //! \param stream Stream to load from 51 | file(std::basic_istream &stream) 52 | { 53 | using namespace std; 54 | 55 | // Load data and add terminating 0 56 | stream.unsetf(ios::skipws); 57 | m_data.assign(istreambuf_iterator(stream), istreambuf_iterator()); 58 | if (stream.fail() || stream.bad()) 59 | throw runtime_error("error reading stream"); 60 | m_data.push_back(0); 61 | } 62 | 63 | //! Gets file data. 64 | //! \return Pointer to data of file. 65 | Ch *data() 66 | { 67 | return &m_data.front(); 68 | } 69 | 70 | //! Gets file data. 71 | //! \return Pointer to data of file. 72 | const Ch *data() const 73 | { 74 | return &m_data.front(); 75 | } 76 | 77 | //! Gets file data size. 78 | //! \return Size of file data, in characters. 79 | std::size_t size() const 80 | { 81 | return m_data.size(); 82 | } 83 | 84 | private: 85 | 86 | std::vector m_data; // File data 87 | 88 | }; 89 | 90 | //! Counts children of node. Time complexity is O(n). 91 | //! \return Number of children of node 92 | template 93 | inline std::size_t count_children(xml_node *node) 94 | { 95 | xml_node *child = node->first_node(); 96 | std::size_t count = 0; 97 | while (child) 98 | { 99 | ++count; 100 | child = child->next_sibling(); 101 | } 102 | return count; 103 | } 104 | 105 | //! Counts attributes of node. Time complexity is O(n). 106 | //! \return Number of attributes of node 107 | template 108 | inline std::size_t count_attributes(xml_node *node) 109 | { 110 | xml_attribute *attr = node->first_attribute(); 111 | std::size_t count = 0; 112 | while (attr) 113 | { 114 | ++count; 115 | attr = attr->next_attribute(); 116 | } 117 | return count; 118 | } 119 | 120 | } 121 | } // namespace cereal 122 | 123 | #endif 124 | -------------------------------------------------------------------------------- /cereal/types/array.hpp: -------------------------------------------------------------------------------- 1 | /*! \file array.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_ARRAY_HPP_ 31 | #define CEREAL_TYPES_ARRAY_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | //! Saving for std::array primitive types 39 | //! using binary serialization, if supported 40 | template inline 41 | typename std::enable_if, Archive>::value 42 | && std::is_arithmetic::value, void>::type 43 | CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::array const & array ) 44 | { 45 | ar( binary_data( array.data(), sizeof(array) ) ); 46 | } 47 | 48 | //! Loading for std::array primitive types 49 | //! using binary serialization, if supported 50 | template inline 51 | typename std::enable_if, Archive>::value 52 | && std::is_arithmetic::value, void>::type 53 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::array & array ) 54 | { 55 | ar( binary_data( array.data(), sizeof(array) ) ); 56 | } 57 | 58 | //! Saving for std::array all other types 59 | template inline 60 | typename std::enable_if, Archive>::value 61 | || !std::is_arithmetic::value, void>::type 62 | CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::array const & array ) 63 | { 64 | for( auto const & i : array ) 65 | ar( i ); 66 | } 67 | 68 | //! Loading for std::array all other types 69 | template inline 70 | typename std::enable_if, Archive>::value 71 | || !std::is_arithmetic::value, void>::type 72 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::array & array ) 73 | { 74 | for( auto & i : array ) 75 | ar( i ); 76 | } 77 | } // namespace cereal 78 | 79 | #endif // CEREAL_TYPES_ARRAY_HPP_ 80 | -------------------------------------------------------------------------------- /cereal/types/chrono.hpp: -------------------------------------------------------------------------------- 1 | /*! \file chrono.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_CHRONO_HPP_ 31 | #define CEREAL_TYPES_CHRONO_HPP_ 32 | 33 | #include 34 | 35 | namespace cereal 36 | { 37 | //! Saving std::chrono::duration 38 | template inline 39 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::chrono::duration const & dur ) 40 | { 41 | ar( CEREAL_NVP_("count", dur.count()) ); 42 | } 43 | 44 | //! Loading std::chrono::duration 45 | template inline 46 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::chrono::duration & dur ) 47 | { 48 | R count; 49 | ar( CEREAL_NVP_("count", count) ); 50 | 51 | dur = std::chrono::duration{count}; 52 | } 53 | 54 | //! Saving std::chrono::time_point 55 | template inline 56 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::chrono::time_point const & dur ) 57 | { 58 | ar( CEREAL_NVP_("time_since_epoch", dur.time_since_epoch()) ); 59 | } 60 | 61 | //! Loading std::chrono::time_point 62 | template inline 63 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::chrono::time_point & dur ) 64 | { 65 | D elapsed; 66 | ar( CEREAL_NVP_("time_since_epoch", elapsed) ); 67 | 68 | dur = std::chrono::time_point{elapsed}; 69 | } 70 | } // namespace cereal 71 | 72 | #endif // CEREAL_TYPES_CHRONO_HPP_ 73 | -------------------------------------------------------------------------------- /cereal/types/complex.hpp: -------------------------------------------------------------------------------- 1 | /*! \file complex.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_COMPLEX_HPP_ 31 | #define CEREAL_TYPES_COMPLEX_HPP_ 32 | 33 | #include 34 | 35 | namespace cereal 36 | { 37 | //! Serializing (save) for std::complex 38 | template inline 39 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::complex const & comp ) 40 | { 41 | ar( CEREAL_NVP_("real", comp.real()), 42 | CEREAL_NVP_("imag", comp.imag()) ); 43 | } 44 | 45 | //! Serializing (load) for std::complex 46 | template inline 47 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::complex & bits ) 48 | { 49 | T real, imag; 50 | ar( CEREAL_NVP_("real", real), 51 | CEREAL_NVP_("imag", imag) ); 52 | bits = {real, imag}; 53 | } 54 | } // namespace cereal 55 | 56 | #endif // CEREAL_TYPES_COMPLEX_HPP_ 57 | -------------------------------------------------------------------------------- /cereal/types/concepts/pair_associative_container.hpp: -------------------------------------------------------------------------------- 1 | /*! \file pair_associative_container.hpp 2 | \brief Support for the PairAssociativeContainer refinement of the 3 | AssociativeContainer concept. 4 | \ingroup TypeConcepts */ 5 | /* 6 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 7 | All rights reserved. 8 | 9 | Redistribution and use in source and binary forms, with or without 10 | modification, are permitted provided that the following conditions are met: 11 | * Redistributions of source code must retain the above copyright 12 | notice, this list of conditions and the following disclaimer. 13 | * Redistributions in binary form must reproduce the above copyright 14 | notice, this list of conditions and the following disclaimer in the 15 | documentation and/or other materials provided with the distribution. 16 | * Neither the name of cereal nor the 17 | names of its contributors may be used to endorse or promote products 18 | derived from this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 21 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 22 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 24 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 25 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 26 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 27 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 29 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | #ifndef CEREAL_CONCEPTS_PAIR_ASSOCIATIVE_CONTAINER_HPP_ 32 | #define CEREAL_CONCEPTS_PAIR_ASSOCIATIVE_CONTAINER_HPP_ 33 | 34 | #include "cereal/cereal.hpp" 35 | 36 | namespace cereal 37 | { 38 | //! Saving for std-like pair associative containers 39 | template class Map, typename... Args, typename = typename Map::mapped_type> inline 40 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, Map const & map ) 41 | { 42 | ar( make_size_tag( static_cast(map.size()) ) ); 43 | 44 | for( const auto & i : map ) 45 | ar( make_map_item(i.first, i.second) ); 46 | } 47 | 48 | //! Loading for std-like pair associative containers 49 | template class Map, typename... Args, typename = typename Map::mapped_type> inline 50 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, Map & map ) 51 | { 52 | size_type size; 53 | ar( make_size_tag( size ) ); 54 | 55 | map.clear(); 56 | 57 | auto hint = map.begin(); 58 | for( size_t i = 0; i < size; ++i ) 59 | { 60 | typename Map::key_type key; 61 | typename Map::mapped_type value; 62 | 63 | ar( make_map_item(key, value) ); 64 | #ifdef CEREAL_OLDER_GCC 65 | hint = map.insert( hint, std::make_pair(std::move(key), std::move(value)) ); 66 | #else // NOT CEREAL_OLDER_GCC 67 | hint = map.emplace_hint( hint, std::move( key ), std::move( value ) ); 68 | #endif // NOT CEREAL_OLDER_GCC 69 | } 70 | } 71 | } // namespace cereal 72 | 73 | #endif // CEREAL_CONCEPTS_PAIR_ASSOCIATIVE_CONTAINER_HPP_ 74 | -------------------------------------------------------------------------------- /cereal/types/deque.hpp: -------------------------------------------------------------------------------- 1 | /*! \file deque.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_DEQUE_HPP_ 31 | #define CEREAL_TYPES_DEQUE_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | //! Saving for std::deque 39 | template inline 40 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::deque const & deque ) 41 | { 42 | ar( make_size_tag( static_cast(deque.size()) ) ); 43 | 44 | for( auto const & i : deque ) 45 | ar( i ); 46 | } 47 | 48 | //! Loading for std::deque 49 | template inline 50 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::deque & deque ) 51 | { 52 | size_type size; 53 | ar( make_size_tag( size ) ); 54 | 55 | deque.resize( static_cast( size ) ); 56 | 57 | for( auto & i : deque ) 58 | ar( i ); 59 | } 60 | } // namespace cereal 61 | 62 | #endif // CEREAL_TYPES_DEQUE_HPP_ 63 | -------------------------------------------------------------------------------- /cereal/types/forward_list.hpp: -------------------------------------------------------------------------------- 1 | /*! \file forward_list.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_FORWARD_LIST_HPP_ 31 | #define CEREAL_TYPES_FORWARD_LIST_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | //! Saving for std::forward_list all other types 39 | template inline 40 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::forward_list const & forward_list ) 41 | { 42 | // write the size - note that this is slow because we need to traverse 43 | // the entire list. there are ways we could avoid this but this was chosen 44 | // since it works in the most general fashion with any archive type 45 | size_type const size = std::distance( forward_list.begin(), forward_list.end() ); 46 | 47 | ar( make_size_tag( size ) ); 48 | 49 | // write the list 50 | for( const auto & i : forward_list ) 51 | ar( i ); 52 | } 53 | 54 | //! Loading for std::forward_list all other types from 55 | template 56 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::forward_list & forward_list ) 57 | { 58 | size_type size; 59 | ar( make_size_tag( size ) ); 60 | 61 | forward_list.resize( static_cast( size ) ); 62 | 63 | for( auto & i : forward_list ) 64 | ar( i ); 65 | } 66 | } // namespace cereal 67 | 68 | #endif // CEREAL_TYPES_FORWARD_LIST_HPP_ 69 | -------------------------------------------------------------------------------- /cereal/types/functional.hpp: -------------------------------------------------------------------------------- 1 | /*! \file functional.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2016, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_FUNCTIONAL_HPP_ 31 | #define CEREAL_TYPES_FUNCTIONAL_HPP_ 32 | 33 | #include 34 | 35 | namespace cereal 36 | { 37 | //! Saving for std::less 38 | template inline 39 | void serialize( Archive &, std::less & ) 40 | { } 41 | } // namespace cereal 42 | 43 | #endif // CEREAL_TYPES_FUNCTIONAL_HPP_ 44 | -------------------------------------------------------------------------------- /cereal/types/list.hpp: -------------------------------------------------------------------------------- 1 | /*! \file list.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_LIST_HPP_ 31 | #define CEREAL_TYPES_LIST_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | //! Saving for std::list 39 | template inline 40 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::list const & list ) 41 | { 42 | ar( make_size_tag( static_cast(list.size()) ) ); 43 | 44 | for( auto const & i : list ) 45 | ar( i ); 46 | } 47 | 48 | //! Loading for std::list 49 | template inline 50 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::list & list ) 51 | { 52 | size_type size; 53 | ar( make_size_tag( size ) ); 54 | 55 | list.resize( static_cast( size ) ); 56 | 57 | for( auto & i : list ) 58 | ar( i ); 59 | } 60 | } // namespace cereal 61 | 62 | #endif // CEREAL_TYPES_LIST_HPP_ 63 | -------------------------------------------------------------------------------- /cereal/types/map.hpp: -------------------------------------------------------------------------------- 1 | /*! \file map.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_MAP_HPP_ 31 | #define CEREAL_TYPES_MAP_HPP_ 32 | 33 | #include "cereal/types/concepts/pair_associative_container.hpp" 34 | #include 35 | 36 | #endif // CEREAL_TYPES_MAP_HPP_ 37 | -------------------------------------------------------------------------------- /cereal/types/set.hpp: -------------------------------------------------------------------------------- 1 | /*! \file set.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_SET_HPP_ 31 | #define CEREAL_TYPES_SET_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | namespace set_detail 39 | { 40 | //! @internal 41 | template inline 42 | void save( Archive & ar, SetT const & set ) 43 | { 44 | ar( make_size_tag( static_cast(set.size()) ) ); 45 | 46 | for( const auto & i : set ) 47 | ar( i ); 48 | } 49 | 50 | //! @internal 51 | template inline 52 | void load( Archive & ar, SetT & set ) 53 | { 54 | size_type size; 55 | ar( make_size_tag( size ) ); 56 | 57 | set.clear(); 58 | 59 | auto hint = set.begin(); 60 | for( size_type i = 0; i < size; ++i ) 61 | { 62 | typename SetT::key_type key; 63 | 64 | ar( key ); 65 | #ifdef CEREAL_OLDER_GCC 66 | hint = set.insert( hint, std::move( key ) ); 67 | #else // NOT CEREAL_OLDER_GCC 68 | hint = set.emplace_hint( hint, std::move( key ) ); 69 | #endif // NOT CEREAL_OLDER_GCC 70 | } 71 | } 72 | } 73 | 74 | //! Saving for std::set 75 | template inline 76 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::set const & set ) 77 | { 78 | set_detail::save( ar, set ); 79 | } 80 | 81 | //! Loading for std::set 82 | template inline 83 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::set & set ) 84 | { 85 | set_detail::load( ar, set ); 86 | } 87 | 88 | //! Saving for std::multiset 89 | template inline 90 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::multiset const & multiset ) 91 | { 92 | set_detail::save( ar, multiset ); 93 | } 94 | 95 | //! Loading for std::multiset 96 | template inline 97 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::multiset & multiset ) 98 | { 99 | set_detail::load( ar, multiset ); 100 | } 101 | } // namespace cereal 102 | 103 | #endif // CEREAL_TYPES_SET_HPP_ 104 | -------------------------------------------------------------------------------- /cereal/types/stack.hpp: -------------------------------------------------------------------------------- 1 | /*! \file stack.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_STACK_HPP_ 31 | #define CEREAL_TYPES_STACK_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | // The default container for stack is deque, so let's include that too 37 | #include "cereal/types/deque.hpp" 38 | 39 | namespace cereal 40 | { 41 | namespace stack_detail 42 | { 43 | //! Allows access to the protected container in stack 44 | template inline 45 | C const & container( std::stack const & stack ) 46 | { 47 | struct H : public std::stack 48 | { 49 | static C const & get( std::stack const & s ) 50 | { 51 | return s.*(&H::c); 52 | } 53 | }; 54 | 55 | return H::get( stack ); 56 | } 57 | } 58 | 59 | //! Saving for std::stack 60 | template inline 61 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::stack const & stack ) 62 | { 63 | ar( CEREAL_NVP_("container", stack_detail::container( stack )) ); 64 | } 65 | 66 | //! Loading for std::stack 67 | template inline 68 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::stack & stack ) 69 | { 70 | C container; 71 | ar( CEREAL_NVP_("container", container) ); 72 | stack = std::stack( std::move( container ) ); 73 | } 74 | } // namespace cereal 75 | 76 | #endif // CEREAL_TYPES_STACK_HPP_ 77 | -------------------------------------------------------------------------------- /cereal/types/string.hpp: -------------------------------------------------------------------------------- 1 | /*! \file string.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_STRING_HPP_ 31 | #define CEREAL_TYPES_STRING_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | //! Serialization for basic_string types, if binary data is supported 39 | template inline 40 | typename std::enable_if, Archive>::value, void>::type 41 | CEREAL_SAVE_FUNCTION_NAME(Archive & ar, std::basic_string const & str) 42 | { 43 | // Save number of chars + the data 44 | ar( make_size_tag( static_cast(str.size()) ) ); 45 | ar( binary_data( str.data(), str.size() * sizeof(CharT) ) ); 46 | } 47 | 48 | //! Serialization for basic_string types, if binary data is supported 49 | template inline 50 | typename std::enable_if, Archive>::value, void>::type 51 | CEREAL_LOAD_FUNCTION_NAME(Archive & ar, std::basic_string & str) 52 | { 53 | size_type size; 54 | ar( make_size_tag( size ) ); 55 | str.resize(static_cast(size)); 56 | ar( binary_data( const_cast( str.data() ), static_cast(size) * sizeof(CharT) ) ); 57 | } 58 | } // namespace cereal 59 | 60 | #endif // CEREAL_TYPES_STRING_HPP_ 61 | 62 | -------------------------------------------------------------------------------- /cereal/types/unordered_map.hpp: -------------------------------------------------------------------------------- 1 | /*! \file unordered_map.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_UNORDERED_MAP_HPP_ 31 | #define CEREAL_TYPES_UNORDERED_MAP_HPP_ 32 | 33 | #include "cereal/types/concepts/pair_associative_container.hpp" 34 | #include 35 | 36 | #endif // CEREAL_TYPES_UNORDERED_MAP_HPP_ 37 | -------------------------------------------------------------------------------- /cereal/types/unordered_set.hpp: -------------------------------------------------------------------------------- 1 | /*! \file unordered_set.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_UNORDERED_SET_HPP_ 31 | #define CEREAL_TYPES_UNORDERED_SET_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | namespace unordered_set_detail 39 | { 40 | //! @internal 41 | template inline 42 | void save( Archive & ar, SetT const & set ) 43 | { 44 | ar( make_size_tag( static_cast(set.size()) ) ); 45 | 46 | for( const auto & i : set ) 47 | ar( i ); 48 | } 49 | 50 | //! @internal 51 | template inline 52 | void load( Archive & ar, SetT & set ) 53 | { 54 | size_type size; 55 | ar( make_size_tag( size ) ); 56 | 57 | set.clear(); 58 | set.reserve( static_cast( size ) ); 59 | 60 | for( size_type i = 0; i < size; ++i ) 61 | { 62 | typename SetT::key_type key; 63 | 64 | ar( key ); 65 | set.emplace( std::move( key ) ); 66 | } 67 | } 68 | } 69 | 70 | //! Saving for std::unordered_set 71 | template inline 72 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unordered_set const & unordered_set ) 73 | { 74 | unordered_set_detail::save( ar, unordered_set ); 75 | } 76 | 77 | //! Loading for std::unordered_set 78 | template inline 79 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::unordered_set & unordered_set ) 80 | { 81 | unordered_set_detail::load( ar, unordered_set ); 82 | } 83 | 84 | //! Saving for std::unordered_multiset 85 | template inline 86 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unordered_multiset const & unordered_multiset ) 87 | { 88 | unordered_set_detail::save( ar, unordered_multiset ); 89 | } 90 | 91 | //! Loading for std::unordered_multiset 92 | template inline 93 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::unordered_multiset & unordered_multiset ) 94 | { 95 | unordered_set_detail::load( ar, unordered_multiset ); 96 | } 97 | } // namespace cereal 98 | 99 | #endif // CEREAL_TYPES_UNORDERED_SET_HPP_ 100 | -------------------------------------------------------------------------------- /cereal/types/utility.hpp: -------------------------------------------------------------------------------- 1 | /*! \file utility.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | /* 5 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | * Neither the name of cereal nor the 16 | names of its contributors may be used to endorse or promote products 17 | derived from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 23 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 24 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 26 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 28 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | #ifndef CEREAL_TYPES_UTILITY_HPP_ 31 | #define CEREAL_TYPES_UTILITY_HPP_ 32 | 33 | #include "cereal/cereal.hpp" 34 | #include 35 | 36 | namespace cereal 37 | { 38 | //! Serializing for std::pair 39 | template inline 40 | void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, std::pair & pair ) 41 | { 42 | ar( CEREAL_NVP_("first", pair.first), 43 | CEREAL_NVP_("second", pair.second) ); 44 | } 45 | } // namespace cereal 46 | 47 | #endif // CEREAL_TYPES_UTILITY_HPP_ 48 | -------------------------------------------------------------------------------- /cereal/types/valarray.hpp: -------------------------------------------------------------------------------- 1 | /*! \file valarray.hpp 2 | \brief Support for types found in \ 3 | \ingroup STLSupport */ 4 | 5 | /* 6 | Copyright (c) 2014, Randolph Voorhies, Shane Grant 7 | All rights reserved. 8 | 9 | Redistribution and use in source and binary forms, with or without 10 | modification, are permitted provided that the following conditions are met: 11 | * Redistributions of source code must retain the above copyright 12 | notice, this list of conditions and the following disclaimer. 13 | * Redistributions in binary form must reproduce the above copyright 14 | notice, this list of conditions and the following disclaimer in the 15 | documentation and/or other materials provided with the distribution. 16 | * Neither the name of cereal nor the 17 | names of its contributors may be used to endorse or promote products 18 | derived from this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 21 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 22 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY 24 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 25 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 26 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 27 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 29 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | #ifndef CEREAL_TYPES_VALARRAY_HPP_ 33 | #define CEREAL_TYPES_VALARRAY_HPP_ 34 | 35 | #include "cereal/cereal.hpp" 36 | #include 37 | 38 | namespace cereal 39 | { 40 | //! Saving for std::valarray arithmetic types, using binary serialization, if supported 41 | template inline 42 | typename std::enable_if, Archive>::value 43 | && std::is_arithmetic::value, void>::type 44 | CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::valarray const & valarray ) 45 | { 46 | ar( make_size_tag( static_cast(valarray.size()) ) ); // number of elements 47 | ar( binary_data( &valarray[0], valarray.size() * sizeof(T) ) ); // &valarray[0] ok since guaranteed contiguous 48 | } 49 | 50 | //! Loading for std::valarray arithmetic types, using binary serialization, if supported 51 | template inline 52 | typename std::enable_if, Archive>::value 53 | && std::is_arithmetic::value, void>::type 54 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::valarray & valarray ) 55 | { 56 | size_type valarraySize; 57 | ar( make_size_tag( valarraySize ) ); 58 | 59 | valarray.resize( static_cast( valarraySize ) ); 60 | ar( binary_data( &valarray[0], static_cast( valarraySize ) * sizeof(T) ) ); 61 | } 62 | 63 | //! Saving for std::valarray all other types 64 | template inline 65 | typename std::enable_if, Archive>::value 66 | || !std::is_arithmetic::value, void>::type 67 | CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::valarray const & valarray ) 68 | { 69 | ar( make_size_tag( static_cast(valarray.size()) ) ); // number of elements 70 | for(auto && v : valarray) 71 | ar(v); 72 | } 73 | 74 | //! Loading for std::valarray all other types 75 | template inline 76 | typename std::enable_if, Archive>::value 77 | || !std::is_arithmetic::value, void>::type 78 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::valarray & valarray ) 79 | { 80 | size_type valarraySize; 81 | ar( make_size_tag( valarraySize ) ); 82 | 83 | valarray.resize( static_cast( valarraySize ) ); 84 | for(auto && v : valarray) 85 | ar(v); 86 | } 87 | } // namespace cereal 88 | 89 | #endif // CEREAL_TYPES_VALARRAY_HPP_ 90 | -------------------------------------------------------------------------------- /cmake/FindSC2Api.cmake: -------------------------------------------------------------------------------- 1 | # - Try to find SC2Api 2 | # Once done, this will define: 3 | # 4 | # SC2Api_FOUND - system has SC2Api. 5 | # SC2Api_INCLUDE_DIRS - the SC2Api include directories. 6 | # SC2Api_LIBRARIES - link these to use SC2Api. 7 | # 8 | # The following libraries variables are provided: 9 | # SC2Api_CIVETWEB_LIB, SC2Api_PROTOBUF_LIB, 10 | # SC2Api_SC2API_LIB, SC2Api_SC2LIB_LIB, SC2Api_SC2PROTOCOL_LIB, 11 | # SC2Api_SC2UTILS_LIB 12 | 13 | # Find main Api headers. 14 | find_path(SC2Api_INCLUDE_DIR 15 | NAMES 16 | "sc2api/sc2_api.h" 17 | "sc2utils/sc2_manage_process.h" 18 | PATHS 19 | "/opt/local/include" 20 | "/usr/local/include" 21 | "/usr/include" 22 | "/var/lib/jenkins/workspace/MicroMachine/api/include" 23 | ) 24 | 25 | # Find autogenerated Protobuf Api headers. 26 | find_path(SC2Api_Proto_INCLUDE_DIR 27 | NAMES 28 | "s2clientprotocol/sc2api.pb.h" 29 | PATHS 30 | "/opt/local/include" 31 | "/usr/local/include" 32 | "/usr/include" 33 | "/var/lib/jenkins/workspace/MicroMachine/api/include" 34 | ) 35 | 36 | # Find Protobuf headers. 37 | find_path(SC2Api_Protobuf_INCLUDE_DIR 38 | NAMES 39 | "google/protobuf/stubs/common.h" 40 | PATHS 41 | "${SC2Api_INCLUDE_DIR}/sc2api" 42 | NO_DEFAULT_PATH 43 | ) 44 | 45 | # Put all the headers together. 46 | set(SC2Api_INCLUDE_DIRS 47 | "${SC2Api_INCLUDE_DIR}" 48 | "${SC2Api_Proto_INCLUDE_DIR}" 49 | "${SC2Api_Protobuf_INCLUDE_DIR}" 50 | ) 51 | 52 | set(SC2Api_LIBRARIES "") 53 | 54 | # Search for SC2Api libraries. 55 | foreach(COMPONENT sc2api sc2lib sc2utils sc2protocol civetweb protobuf) 56 | string(TOUPPER ${COMPONENT} UPPERCOMPONENT) 57 | 58 | find_library(SC2Api_${UPPERCOMPONENT}_LIB 59 | NAMES 60 | "${COMPONENT}" 61 | PATHS 62 | "/opt/local/lib" 63 | "/usr/local/lib" 64 | "/var/lib/jenkins/workspace/MicroMachine/api/lib" 65 | PATH_SUFFIXES 66 | "sc2api" 67 | NO_DEFAULT_PATH 68 | ) 69 | 70 | if(SC2Api_${UPPERCOMPONENT}_LIB) 71 | mark_as_advanced(SC2Api_${UPPERCOMPONENT}_LIB) 72 | list(APPEND SC2Api_LIBRARIES "${SC2Api_${UPPERCOMPONENT}_LIB}") 73 | else() 74 | message(STATUS ${COMPONENT} " not found!") 75 | set(SC2Api_FOUND FALSE) 76 | endif() 77 | endforeach() 78 | 79 | mark_as_advanced(SC2Api_INCLUDE_DIRS SC2Api_LIBRARIES) 80 | 81 | include(FindPackageHandleStandardArgs) 82 | find_package_handle_standard_args(SC2Api DEFAULT_MSG SC2Api_INCLUDE_DIRS SC2Api_LIBRARIES) 83 | -------------------------------------------------------------------------------- /copy_bot_to_ladder.bat: -------------------------------------------------------------------------------- 1 | cp build/bin/MicroMachine ../Sc2LadderServer/build/bin/Bots/MicroMachine/ -------------------------------------------------------------------------------- /custom_maps/DefeatBunker.SC2Map: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/custom_maps/DefeatBunker.SC2Map -------------------------------------------------------------------------------- /custom_maps/DefeatMarines.SC2Map: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/custom_maps/DefeatMarines.SC2Map -------------------------------------------------------------------------------- /custom_maps/DefeatPlanetaryFortress.SC2Map: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/custom_maps/DefeatPlanetaryFortress.SC2Map -------------------------------------------------------------------------------- /custom_maps/DefeatSpineCrawlers.SC2Map: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/custom_maps/DefeatSpineCrawlers.SC2Map -------------------------------------------------------------------------------- /custom_maps/DefeatWingedZerglings.SC2Map: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/custom_maps/DefeatWingedZerglings.SC2Map -------------------------------------------------------------------------------- /linux_build.bat: -------------------------------------------------------------------------------- 1 | # Clear the workspace 2 | rm -Rf build/ 3 | rm -Rf api/ 4 | rm -Rf sc2-libvoxelbot/ 5 | rm -Rf /usr/local/include 6 | rm -Rf /usr/local/lib 7 | 8 | # We need theses folders to be present 9 | mkdir -p build 10 | mkdir -p /usr/local/include 11 | mkdir -p /usr/local/include/sc2-libvoxelbot 12 | mkdir -p /usr/local/lib 13 | mkdir -p /usr/local/lib/sc2api 14 | 15 | # Clone and build libvoxelbot (for combat simulator) 16 | if [ ! -d "sc2-libvoxelbot" ] ; then 17 | git clone --recursive https://github.com/RaphaelRoyerRivard/sc2-libvoxelbot 18 | fi 19 | cd sc2-libvoxelbot 20 | mkdir build 21 | cd build 22 | cmake ../ 23 | make -j8 24 | 25 | cd ../ 26 | 27 | # Install libvoxelbot lib 28 | cp -R libvoxelbot /usr/local/include/sc2-libvoxelbot 29 | cp -R build /usr/local/include/sc2-libvoxelbot 30 | 31 | ls -la /usr/local/include/sc2-libvoxelbot 32 | 33 | # Install SC2 API headers 34 | cp -R s2client-api/include/sc2api /usr/local/include 35 | cp -R s2client-api/include/sc2utils /usr/local/include 36 | cp -R build/s2client-api/generated/s2clientprotocol /usr/local/include 37 | 38 | # Install protobuf headers 39 | cp -R s2client-api/contrib/protobuf/src/google /usr/local/include/sc2api 40 | 41 | # Install SC2 API libraries 42 | cp build/s2client-api/bin/libcivetweb.a /usr/local/lib/sc2api/libcivetweb.a 43 | cp build/s2client-api/bin/libprotobuf.a /usr/local/lib/sc2api/libprotobuf.a 44 | cp build/s2client-api/bin/libsc2api.a /usr/local/lib/sc2api/libsc2api.a 45 | cp build/s2client-api/bin/libsc2lib.a /usr/local/lib/sc2api/libsc2lib.a 46 | cp build/s2client-api/bin/libsc2protocol.a /usr/local/lib/sc2api/libsc2protocol.a 47 | cp build/s2client-api/bin/libsc2utils.a /usr/local/lib/sc2api/libsc2utils.a 48 | 49 | # Build the bot 50 | cd ../ 51 | ls -la /usr/local/include/sc2api 52 | ls -la /usr/local/lib/sc2api 53 | cd build 54 | 55 | # Generate a Makefile. 56 | # Use 'cmake -DCMAKE_BUILD_TYPE=Debug ../' if debuginfo is needed 57 | cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3" ../ 58 | 59 | # Build. 60 | make -------------------------------------------------------------------------------- /linux_partial_build_debug.bat: -------------------------------------------------------------------------------- 1 | # Clear the workspace 2 | rm -Rf build/ 3 | 4 | # We need theses folders to be present 5 | mkdir -p build 6 | 7 | # Build the bot 8 | cd build 9 | 10 | # Generate a Makefile. 11 | # Use 'cmake -DCMAKE_BUILD_TYPE=Debug ../' if debuginfo is needed 12 | cmake -DCMAKE_BUILD_TYPE=Debug ../ 13 | 14 | # Build. 15 | make -------------------------------------------------------------------------------- /linux_partial_build_release.bat: -------------------------------------------------------------------------------- 1 | # Clear the workspace 2 | rm -Rf build/ 3 | 4 | # We need theses folders to be present 5 | mkdir -p build 6 | 7 | # Build the bot 8 | cd build 9 | 10 | # Generate a Makefile. 11 | # Use 'cmake -DCMAKE_BUILD_TYPE=Debug ../' if debuginfo is needed 12 | cmake ../ 13 | 14 | # Build. 15 | make -------------------------------------------------------------------------------- /release/CommandCenter.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/release/CommandCenter.zip -------------------------------------------------------------------------------- /run_ladder_manager.bat: -------------------------------------------------------------------------------- 1 | cd ~/Projects/Sc2LadderServer/build/bin/ 2 | echo "MicroMachine"vs"MicroMachine" AutomatonLE.SC2Map > matchupList 3 | sudo ./Sc2LadderServer -e /home/raphael/StarCraftII/Versions/Base70154/SC2_x64 -------------------------------------------------------------------------------- /src/BaseLocationManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "BaseLocation.h" 4 | 5 | class CCBot; 6 | 7 | class BaseLocationManager 8 | { 9 | CCBot & m_bot; 10 | 11 | bool m_areBaseLocationPtrsSorted; 12 | std::vector m_baseLocationData; 13 | std::vector m_baseLocationPtrs; 14 | std::vector m_startingBaseLocations; 15 | std::map m_playerStartingBaseLocations; 16 | std::map> m_occupiedBaseLocations; 17 | std::vector> m_tileBaseLocations; 18 | std::vector> m_resourceProximity; 19 | BaseLocation * m_nat = nullptr; 20 | BaseLocation * m_enemyNat = nullptr; 21 | 22 | const int NearBaseLocationTileDistance = 38; 23 | const float TerrainHeightCostMultiplier = 5.f; 24 | 25 | void sortBaseLocationPtrs(); 26 | 27 | public: 28 | 29 | BaseLocationManager(CCBot & bot); 30 | 31 | void onStart(); 32 | bool affectToCluster(std::vector> & resourceClusters, Unit & resource, float maxDistanceWithCluster) const; 33 | void onFrame(); 34 | void drawBaseLocations(); 35 | void drawTileBaseLocationAssociations() const; 36 | void drawResourceProxity(); 37 | 38 | BaseLocation * getBaseLocation(const CCPosition & pos) const; 39 | const std::vector & getBaseLocations() const; 40 | const std::vector & getStartingBaseLocations() const; 41 | const std::set & getOccupiedBaseLocations(int player) const; 42 | int getFreeBaseLocationCount() const; 43 | BaseLocation * getClosestOccupiedBaseLocationForUnit(const Unit unit) const; 44 | BaseLocation * getFarthestOccupiedBaseLocation() const; 45 | const BaseLocation * getPlayerStartingBaseLocation(int player) const; 46 | void FixNullPlayerStartingBaseLocation(); 47 | int getBaseCount(int player, bool isCompleted = false) const; 48 | 49 | BaseLocation* getNextExpansion(int player, bool checkBlocked, bool checkBuildable, bool ignoreReservedTiles, std::vector basesToIgnore = {}) const; 50 | CCTilePosition getNextExpansionPosition(int player, bool checkBlocked, bool checkBuildable, bool ignoreReservedTiles) const; 51 | BaseLocation* getPlayerNat(int player); 52 | CCTilePosition getBasePosition(int player, int index) const; 53 | BaseLocation* getClosestBase(const CCPosition position, bool checkContains) const; 54 | CCTilePosition getClosestBasePosition(const sc2::Unit* unit, int player = Players::Self, bool shiftTowardsResourceDepot = false, bool checkContainsMinerals = false, bool checkUnderAttack = false) const; 55 | const BaseLocation* getBaseForDepotPosition(const CCTilePosition position) const; 56 | const BaseLocation* getBaseForDepot(const Unit depot) const; 57 | void SetLocationAsBlocked(const CCPosition position, UnitType type); 58 | void ClearBlockedLocations(); 59 | std::vector getEnemyUnitsNear(CCTilePosition center) const; 60 | const BaseLocation* getBaseContainingPosition(const CCPosition position, int player = -1) const; 61 | bool isInProximityOfResources(int x, int y) const; 62 | int getAccessibleMineralFieldCount() const; 63 | }; 64 | -------------------------------------------------------------------------------- /src/BehaviorTreeBuilder.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "Behavior.h" 7 | 8 | class BehaviorTree 9 | { 10 | protected: 11 | Behavior* m_pRoot; 12 | public: 13 | BehaviorTree(Behavior* b) 14 | { 15 | m_pRoot = b; 16 | } 17 | void tick() { 18 | m_pRoot->tick(); 19 | } 20 | }; 21 | 22 | // from https://michaelyagidotcom.wordpress.com/behavior-tree-builder/ 23 | template 24 | class NodeBuilder; 25 | 26 | template 27 | class LeafBuilder { 28 | public: 29 | LeafBuilder(parent_type* parent, Behavior* leaf) : 30 | m_parent(parent), 31 | m_leaf(leaf) {} 32 | 33 | parent_type& end() 34 | { 35 | return *m_parent; 36 | } 37 | private: 38 | parent_type* m_parent; 39 | Behavior* m_leaf; 40 | }; 41 | 42 | template 43 | class NodeBuilder { 44 | public: 45 | NodeBuilder(parent_type* parent, Composite* node): 46 | m_parent(parent), 47 | m_node(node) {} 48 | 49 | LeafBuilder> action(Behavior * action) { 50 | m_node->addChild(action); 51 | return LeafBuilder>(this, action); 52 | } 53 | 54 | LeafBuilder> condition(Behavior * condition) { 55 | m_node->addChild(condition); 56 | return LeafBuilder>(this, condition); 57 | } 58 | 59 | NodeBuilder> selector() { 60 | Selector* selector = new Selector(); 61 | m_node->addChild(selector); 62 | return NodeBuilder>(this, selector); 63 | } 64 | 65 | NodeBuilder> sequence() { 66 | Sequence* sequence = new Sequence(); 67 | m_node->addChild(sequence); 68 | return NodeBuilder>(this, sequence); 69 | } 70 | 71 | parent_type& end() 72 | { 73 | return *m_parent; 74 | } 75 | 76 | private: 77 | parent_type* m_parent; 78 | Composite* m_node; 79 | }; 80 | 81 | class BehaviorTreeBuilder { 82 | 83 | protected: 84 | Behavior* m_parentNode; 85 | 86 | public: 87 | virtual ~BehaviorTreeBuilder() {} 88 | BehaviorTreeBuilder() {} 89 | 90 | LeafBuilder action(Behavior * action) { 91 | m_parentNode = action; 92 | return LeafBuilder(this, action); 93 | } 94 | 95 | LeafBuilder condition(Behavior * condition) { 96 | m_parentNode = condition; 97 | return LeafBuilder(this, condition); 98 | } 99 | 100 | NodeBuilder sequence() { 101 | Sequence* sequence = new Sequence(); 102 | m_parentNode = sequence; 103 | return NodeBuilder(this, sequence); 104 | } 105 | NodeBuilder selector() { 106 | Selector* selector = new Selector(); 107 | m_parentNode = selector; 108 | return NodeBuilder(this, selector); 109 | } 110 | 111 | BehaviorTree* end() 112 | { 113 | return new BehaviorTree(m_parentNode); 114 | } 115 | }; 116 | 117 | -------------------------------------------------------------------------------- /src/BotAssert.cpp: -------------------------------------------------------------------------------- 1 | #include "BotAssert.h" 2 | #include 3 | #ifdef _WINDOWS 4 | #include "StackWalker.h" 5 | #endif 6 | 7 | namespace Assert 8 | { 9 | std::string lastErrorMessage; 10 | 11 | const std::string CurrentDateTime() 12 | { 13 | auto t = std::time(nullptr); 14 | auto tm = *std::localtime(&t); 15 | std::stringstream ss; 16 | ss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S"); 17 | return ss.str(); 18 | } 19 | 20 | void ReportFailure(const char * condition, const char * file, int line, const char * msg, ...) 21 | { 22 | char messageBuffer[1024] = ""; 23 | if (msg != nullptr) 24 | { 25 | va_list args; 26 | va_start(args, msg); 27 | vsnprintf(messageBuffer, 1024, msg, args); 28 | va_end(args); 29 | } 30 | 31 | std::stringstream ss; 32 | ss << std::endl; 33 | ss << "!Assert: " << condition << std::endl; 34 | ss << "File: " << file << std::endl; 35 | ss << "Message: " << messageBuffer << std::endl; 36 | ss << "Line: " << line << std::endl; 37 | ss << "Time: " << CurrentDateTime() << std::endl; 38 | 39 | lastErrorMessage = messageBuffer; 40 | 41 | std::cerr << ss.str(); 42 | 43 | #ifdef _WINDOWS 44 | StackWalker sw; 45 | sw.ShowCallstack(); 46 | #endif 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /src/BotAssert.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #ifdef WIN32 12 | #define BOT_BREAK __debugbreak(); 13 | #else 14 | #define BOT_BREAK ; 15 | #endif 16 | 17 | #if true 18 | #define BOT_ASSERT(cond, msg, ...) \ 19 | do \ 20 | { \ 21 | if (!(cond)) \ 22 | { \ 23 | Assert::ReportFailure(#cond, __FILE__, __LINE__, (msg), ##__VA_ARGS__); \ 24 | BOT_BREAK \ 25 | } \ 26 | } while(0) 27 | #else 28 | #define BOT_ASSERT(cond, msg, ...) 29 | #endif 30 | 31 | namespace Assert 32 | { 33 | extern std::string lastErrorMessage; 34 | 35 | const std::string CurrentDateTime(); 36 | 37 | void ReportFailure(const char * condition, const char * file, int line, const char * msg, ...); 38 | } 39 | -------------------------------------------------------------------------------- /src/BotConfig.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | 5 | class BotConfig 6 | { 7 | 8 | public: 9 | 10 | bool ConfigFileFound; 11 | bool ConfigFileParsed; 12 | std::string ConfigFileLocation; 13 | 14 | bool UsingAutoObserver; 15 | 16 | std::string BotName; 17 | std::string Authors; 18 | bool PrintInfoOnStart; 19 | std::string BotMode; 20 | 21 | int SetLocalSpeed; 22 | int SetFrameSkip; 23 | bool UserInput; 24 | bool CompleteMapInformation; 25 | 26 | bool BatchReplayMode; 27 | int NbBatchReplay; 28 | 29 | std::string StrategyName; 30 | std::string ReadDir; 31 | std::string WriteDir; 32 | bool UseEnemySpecificStrategy; 33 | bool FoundEnemySpecificStrategy; 34 | 35 | bool AllowDebug; 36 | bool AllowKeyControl; 37 | bool IsRealTime; 38 | bool DebugMenu; 39 | bool DrawTileInfo; 40 | bool DrawBaseLocationInfo; 41 | bool DrawBaseTiles; 42 | bool DrawWalkableSectors; 43 | bool DrawBuildableSectors; 44 | bool DrawBuildable; 45 | bool DrawResourceInfo; 46 | bool DrawProductionInfo; 47 | bool DrawScoutInfo; 48 | bool DrawWorkerInfo; 49 | bool DrawModuleTimers; 50 | bool DrawReservedBuildingTiles; 51 | bool DrawBuildingInfo; 52 | bool DrawStartingRamp; 53 | bool DrawWall; 54 | bool DrawEnemyUnitInfo; 55 | bool DrawUnitTargetInfo; 56 | bool DrawSquadInfo; 57 | bool DrawUnitPowerInfo; 58 | bool DrawHarassInfo; 59 | bool DrawMemoryInfo; 60 | bool DrawUnitID; 61 | bool DrawProfilingInfo; 62 | bool DrawInfluenceMaps; 63 | bool DrawBlockedTiles; 64 | bool DrawRepairStation; 65 | bool DrawDamageHealthRatio; 66 | bool DrawUnitActions; 67 | bool DrawResourcesProximity; 68 | bool DrawCombatInformation; 69 | bool DrawPathfindingTiles; 70 | bool DrawBuildingBase; 71 | bool DrawCurrentStartingStrategy; 72 | bool DrawMainBaseSiegePositions; 73 | bool LogArmyActions; 74 | bool TimeControl; 75 | bool PrintGreetingMessage; 76 | bool RandomProxyLocation; 77 | int ProductionPrintFrequency; 78 | int LogFrameDurationThreshold; 79 | 80 | CCColor ColorLineTarget; 81 | CCColor ColorLineMineral; 82 | CCColor ColorUnitNearEnemy; 83 | CCColor ColorUnitNotNearEnemy; 84 | 85 | bool KiteWithRangedUnits; 86 | float MaxTargetDistance; 87 | float MaxWorkerRepairDistance; 88 | bool ScoutHarassEnemy; 89 | bool AutoCompleteBuildOrder; 90 | bool NoScoutOn2PlayersMap; 91 | 92 | bool AlphaBetaPruning; 93 | int AlphaBetaDepth; 94 | int AlphaBetaMaxMilli; 95 | 96 | bool UCTCD; 97 | int UCTCDMaxMilli; 98 | float UCTCDK; 99 | int UCTCDMaxTraversals; 100 | bool UCTCDConsiderDistance; 101 | 102 | bool UnitOwnAgent; 103 | bool SkipOneFrame; 104 | bool ClosestEnemy; 105 | bool WeakestEnemy; 106 | bool HighestPriority; 107 | bool EnableMultiThreading; 108 | bool TournamentMode; 109 | std::string StarCraft2Version; 110 | bool ArchonMode; 111 | 112 | int WorkersPerRefinery; 113 | int PylonSpacing; 114 | bool SelectStartingBuildBasedOnHistory; 115 | 116 | BotConfig(); 117 | 118 | void readConfigFile(); 119 | }; -------------------------------------------------------------------------------- /src/BuildOrder.cpp: -------------------------------------------------------------------------------- 1 | #include "BuildOrder.h" 2 | 3 | MM::BuildOrder::BuildOrder() 4 | { 5 | 6 | } 7 | 8 | 9 | MM::BuildOrder::BuildOrder(const std::vector & vec) 10 | : m_buildOrder(vec) 11 | { 12 | 13 | } 14 | 15 | void MM::BuildOrder::add(const MetaType & type) 16 | { 17 | m_buildOrder.push_back(type); 18 | } 19 | 20 | size_t MM::BuildOrder::size() const 21 | { 22 | return m_buildOrder.size(); 23 | } 24 | 25 | const MetaType & MM::BuildOrder::operator [] (const size_t & index) const 26 | { 27 | return m_buildOrder[index]; 28 | } 29 | 30 | MetaType & MM::BuildOrder::operator [] (const size_t & index) 31 | { 32 | return m_buildOrder[index]; 33 | } -------------------------------------------------------------------------------- /src/BuildOrder.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "MetaType.h" 5 | 6 | namespace MM 7 | { 8 | class BuildOrder 9 | { 10 | std::vector m_buildOrder; 11 | 12 | public: 13 | 14 | BuildOrder(); 15 | BuildOrder(const std::vector & buildVector); 16 | 17 | void add(const MetaType & type); 18 | size_t size() const; 19 | const MetaType & operator [] (const size_t & index) const; 20 | MetaType & operator [] (const size_t & index); 21 | }; 22 | } 23 | -------------------------------------------------------------------------------- /src/BuildOrderQueue.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "MetaType.h" 5 | 6 | class CCBot; 7 | 8 | // This namespace is to prevent build error when compiling because the libvoxelbot library also contains a BuildOrderItem 9 | namespace MM { 10 | struct BuildOrderItem 11 | { 12 | MetaType type; // the thing we want to 'build' 13 | int priority; // the priority at which to place it in the queue 14 | bool blocking; // whether or not we block further items 15 | 16 | BuildOrderItem(const MetaType & t, int p, bool b); 17 | bool operator<(const BuildOrderItem & x) const; 18 | bool operator==(const BuildOrderItem & x) const; 19 | }; 20 | } 21 | 22 | class BuildOrderQueue 23 | { 24 | CCBot & m_bot; 25 | std::deque m_queue; 26 | 27 | int m_lowestPriority; 28 | int m_highestPriority; 29 | int m_defaultPrioritySpacing; 30 | int m_numSkippedItems; 31 | 32 | public: 33 | 34 | BuildOrderQueue(CCBot & bot); 35 | 36 | void clearAll(); // clears the entire build order queue 37 | void skipItem(); // increments skippedItems 38 | MM::BuildOrderItem queueAsHighestPriority(const MetaType & type, bool blocking); // queues something at the highest priority 39 | MM::BuildOrderItem queueAsLowestPriority(const MetaType & type, bool blocking); // queues something at the lowest priority 40 | MM::BuildOrderItem queueItem(const MM::BuildOrderItem & b); // queues something with a given priority 41 | void removeHighestPriorityItem(); // removes the highest priority item 42 | void removeCurrentHighestPriorityItem(); 43 | void removeAllOfType(const MetaType & type); 44 | 45 | size_t size(); // returns the size of the queue 46 | 47 | bool isEmpty(); 48 | MM::BuildOrderItem getHighestPriorityItem(); // returns the highest priority item 49 | MM::BuildOrderItem getNextHighestPriorityItem(); // returns the highest priority item 50 | int getCountOfType(const MetaType & type); // returns the number of items of a type in the queue 51 | 52 | bool canSkipItem(); 53 | std::string getQueueInformation() const; 54 | bool contains(const MetaType & type) const; 55 | 56 | // overload the bracket operator for ease of use 57 | MM::BuildOrderItem operator [] (int i); 58 | }; 59 | -------------------------------------------------------------------------------- /src/Building.cpp: -------------------------------------------------------------------------------- 1 | #include "Building.h" 2 | 3 | Building::Building() 4 | : desiredPosition (0,0) 5 | , finalPosition (0,0) 6 | , position (0,0) 7 | , type () 8 | , buildingUnit () 9 | , builderUnit () 10 | , lastOrderFrame (0) 11 | , status (BuildingStatus::Unassigned) 12 | , buildCommandGiven (false) 13 | , underConstruction (false) 14 | {} 15 | 16 | // constructor we use most often 17 | Building::Building(UnitType t, CCTilePosition desired) 18 | : desiredPosition (desired) 19 | , finalPosition (0,0) 20 | , position (0,0) 21 | , type (t) 22 | , buildingUnit () 23 | , builderUnit () 24 | , lastOrderFrame (0) 25 | , status (BuildingStatus::Unassigned) 26 | , buildCommandGiven (false) 27 | , underConstruction (false) 28 | {} 29 | 30 | // equals operator 31 | bool Building::operator == (const Building & b) 32 | { 33 | // buildings are equal if their worker unit and building unit are equal 34 | return (b.buildingUnit == buildingUnit) 35 | && (b.builderUnit == builderUnit) 36 | && (b.finalPosition.x == finalPosition.x) 37 | && (b.finalPosition.y == finalPosition.y); 38 | } 39 | 40 | bool Building::operator != (const Building & b) 41 | { 42 | return !(*this == b); 43 | } 44 | 45 | void Building::unassign() 46 | { 47 | builderUnit = Unit(); 48 | buildCommandGiven = false; 49 | status = BuildingStatus::Unassigned; 50 | } -------------------------------------------------------------------------------- /src/Building.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "Unit.h" 5 | #include "UnitType.h" 6 | 7 | namespace BuildingStatus 8 | { 9 | enum { Unassigned = 0, Assigned = 1, UnderConstruction = 2, Size = 3 }; 10 | } 11 | 12 | class Building 13 | { 14 | public: 15 | 16 | CCTilePosition desiredPosition; 17 | CCTilePosition finalPosition; 18 | CCTilePosition position; 19 | UnitType type; 20 | Unit buildingUnit;//Building 21 | Unit builderUnit;//Worker 22 | size_t status; 23 | int lastOrderFrame; 24 | bool buildCommandGiven; 25 | bool underConstruction; 26 | bool reserveResources = true; 27 | bool canBeBuiltElseWhere = true; 28 | 29 | Building(); 30 | 31 | // constructor we use most often 32 | Building(UnitType t, CCTilePosition desired); 33 | 34 | // equals operator 35 | bool operator == (const Building & b); 36 | bool operator != (const Building & b); 37 | 38 | void unassign(); 39 | }; 40 | -------------------------------------------------------------------------------- /src/BuildingData.cpp: -------------------------------------------------------------------------------- 1 | #include "BuildingData.h" 2 | 3 | BuildingData::BuildingData() 4 | { 5 | 6 | } 7 | 8 | void BuildingData::removeBuilding(const Building & b) 9 | { 10 | const auto & building = std::find(_buildings.begin(), _buildings.end(), b); 11 | 12 | if (building != _buildings.end()) 13 | { 14 | _buildings.erase(building); 15 | } 16 | } 17 | 18 | std::vector & BuildingData::getBuildings() 19 | { 20 | return _buildings; 21 | } 22 | 23 | void BuildingData::addBuilding(const Building & b) 24 | { 25 | _buildings.push_back(b); 26 | } 27 | 28 | bool BuildingData::isBeingBuilt(UnitType type) 29 | { 30 | for (auto & b : _buildings) 31 | { 32 | if (b.type == type) 33 | { 34 | return true; 35 | } 36 | } 37 | 38 | return false; 39 | } 40 | 41 | void BuildingData::removeBuildings(const std::vector & buildings) 42 | { 43 | for (const auto & b : buildings) 44 | { 45 | removeBuilding(b); 46 | } 47 | } -------------------------------------------------------------------------------- /src/BuildingData.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "Building.h" 5 | 6 | class BuildingData 7 | { 8 | std::vector _buildings; 9 | 10 | public: 11 | 12 | BuildingData(); 13 | 14 | std::vector & getBuildings(); 15 | 16 | void addBuilding(const Building & b); 17 | void removeBuilding(const Building & b); 18 | void removeBuildings(const std::vector & buildings); 19 | bool isBeingBuilt(UnitType type); 20 | }; -------------------------------------------------------------------------------- /src/BuildingManager.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/src/BuildingManager.cpp -------------------------------------------------------------------------------- /src/BuildingPlacer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "BuildingData.h" 5 | 6 | class CCBot; 7 | class BaseLocation; 8 | 9 | class BuildingPlacer 10 | { 11 | CCBot & m_bot; 12 | 13 | const int buildingPadding = 2; 14 | 15 | std::vector< std::vector > m_resourceBlockedTiles;//Used to place command centers when building an expand in the main 16 | std::vector< std::vector > m_reserveBuildingMap; 17 | #ifdef COMPUTE_WALKABLE_TILES 18 | std::vector< std::vector > m_reserveWalkableMap;//Only used with #define COMPUTE_WALKABLE_TILES 19 | #endif 20 | 21 | // queries for various BuildingPlacer data 22 | bool isGeyserAssigned(CCTilePosition geyserTilePos) const; 23 | bool tileOverlapsBaseLocation(int x, int y, UnitType type) const; 24 | 25 | public: 26 | 27 | BuildingPlacer(CCBot & bot); 28 | 29 | void onStart(); 30 | 31 | // determines whether we can build at a given location 32 | bool buildable(const UnitType type, int x, int y, bool ignoreReservedTiles = false) const; 33 | bool canBuildDepotHere(int bx, int by, std::vector minerals, std::vector geysers) const; 34 | bool canBuildBunkerHere(int bx, int by, int depotX, int depotY, std::vector geysersPos) const; 35 | bool canBuildHere(int bx, int by, const UnitType & type, bool ignoreReserved, bool checkInfluenceMap, bool includeExtraTiles, bool ignoreExtraBorder = false) const; 36 | bool isBuildingBlockedByCreep(CCTilePosition pos, UnitType type) const; 37 | std::vector getTilesForBuildLocation(Unit building) const; 38 | std::vector getTilesForBuildLocation(int bx, int by, const UnitType & type, int width, int height, bool includeExtraTiles, int extraBorder) const; 39 | CCTilePosition getBottomLeftForBuildLocation(int bx, int by, const UnitType & type) const; 40 | int getBuildingCenterOffset(int x, int y, int width, int height) const; 41 | 42 | // returns a build location near a building's desired location 43 | CCTilePosition getBuildLocationNear(const Building & b, bool ignoreReserved, bool checkInfluenceMap, bool includeExtraTiles, bool ignoreExtraBorder = false, bool forceSameHeight = false) const; 44 | CCTilePosition getBunkerBuildLocationNear(const Building & b, int depotX, int depotY, std::vector geysersPos) const; 45 | 46 | void drawReservedTiles(); 47 | 48 | void reserveTiles(UnitType type, CCTilePosition pos);//(int x, int y, int width, int height); 49 | void reserveTiles(CCTilePosition start, CCTilePosition end); 50 | void freeTiles(int x, int y, int width, int height, bool setBlocked); 51 | void freeTilesForTurrets(CCTilePosition position); 52 | void freeTilesForBunker(CCTilePosition position); 53 | bool isReserved(int x, int y) const; 54 | CCTilePosition getRefineryPosition(); 55 | }; 56 | -------------------------------------------------------------------------------- /src/CCBot.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/src/CCBot.cpp -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++14") 2 | set(CMAKE_CXX_STANDARD 14) 3 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 4 | set(CMAKE_CXX_EXTENSIONS OFF) 5 | SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "-rdynamic") 6 | 7 | # All the source files for the bot. 8 | file(GLOB BOT_SOURCES "*.cpp" "*.h" "*.hpp") 9 | 10 | # Enable compilation of the SC2 version of the bot. 11 | add_definitions(-DSC2API) 12 | 13 | # Find libvoxelbot lib 14 | # find_path(LIBVOXELBOT_PATH 15 | # NAMES 16 | # "build/liblibvoxelbot.a" 17 | # PATHS 18 | # "/opt/local/include/sc2-libvoxelbot" 19 | # "/usr/local/include/sc2-libvoxelbot" 20 | # "/usr/include/sc2-libvoxelbot" 21 | # "/var/lib/jenkins/workspace/MicroMachine/sc2-libvoxelbot" 22 | # ) 23 | 24 | # include_directories(SYSTEM "${SC2Api_INCLUDE_DIRS}" "${LIBVOXELBOT_PATH}") 25 | include_directories(SYSTEM "${SC2Api_INCLUDE_DIRS}" "${PROJECT_SOURCE_DIR}") 26 | 27 | # Show more warnings at compiletime. 28 | if (MSVC) 29 | # FIXME: put Windows specific options here. 30 | else () 31 | set(CMAKE_CXX_FLAGS "-Wall -Wextra") 32 | endif () 33 | 34 | # Create the executable. 35 | add_executable(MicroMachine ${BOT_SOURCES}) 36 | # target_link_libraries(MicroMachine ${SC2Api_LIBRARIES} "${LIBVOXELBOT_PATH}/build/liblibvoxelbot.a") 37 | 38 | if (APPLE) 39 | target_link_libraries(MicroMachine "-framework Carbon") 40 | endif () 41 | 42 | # Linux specific. 43 | if (UNIX AND NOT APPLE) 44 | target_link_libraries(MicroMachine pthread dl) 45 | endif () 46 | -------------------------------------------------------------------------------- /src/Common.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "BotAssert.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "json/json.hpp" 13 | #include "MetaTypeEnum.h" 14 | #include "sc2api/sc2_score.h" 15 | 16 | using json = nlohmann::json; 17 | 18 | #ifdef SC2API 19 | #include "sc2api/sc2_api.h" 20 | typedef sc2::Point2D CCPosition; 21 | typedef sc2::Point2DI CCTilePosition; 22 | typedef sc2::Color CCColor; 23 | typedef sc2::UpgradeID CCUpgrade; 24 | typedef sc2::Tag CCUnitID; 25 | typedef sc2::Race CCRace; 26 | typedef float CCHealth; 27 | typedef float CCPositionType; 28 | 29 | inline bool operator<(const CCTilePosition& lhs, const CCTilePosition& rhs) 30 | { 31 | return lhs.x < rhs.x || lhs.x == rhs.y && lhs.y < rhs.y; 32 | } 33 | 34 | #else 35 | #include "BWAPI.h" 36 | typedef BWAPI::Position CCPosition; 37 | typedef BWAPI::TilePosition CCTilePosition; 38 | typedef BWAPI::Color CCColor; 39 | typedef BWAPI::Race CCRace; 40 | typedef BWAPI::UpgradeType CCUpgrade; 41 | typedef int CCUnitID; 42 | typedef int CCHealth; 43 | typedef int CCPositionType; 44 | #endif 45 | 46 | typedef size_t CCPlayer; 47 | namespace Players 48 | { 49 | enum {Self = 0u, Enemy = 1u, Neutral = 2u, Size = 3u, None = 4u}; 50 | } -------------------------------------------------------------------------------- /src/Condition.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | 5 | class CCBot; 6 | 7 | namespace ConditionTypes 8 | { 9 | enum { UnaryString, UnaryInt, UnaryUnitType, BinaryComp, BinaryBool, BinaryInt, Invalid }; 10 | } 11 | 12 | namespace ConditionOperators 13 | { 14 | enum { LT, GT, EQ, NEQ, LTE, GTE, OR, AND, PLUS, MINUS, MULT, DIV, Invalid }; 15 | } 16 | 17 | class Condition 18 | { 19 | CCBot * m_bot; 20 | int m_type; 21 | int m_player; 22 | Condition * m_lhs; 23 | Condition * m_rhs; 24 | int m_op; 25 | std::string m_strValue; 26 | int m_intValue; 27 | json m_json; 28 | 29 | static int GetOperator(const std::string & op); 30 | static int GetPlayer(const std::string & op); 31 | static int GetType(const std::string & op); 32 | 33 | public: 34 | 35 | Condition(); 36 | Condition(const json & j, CCBot & bot); 37 | 38 | bool eval() const; 39 | int intEval() const; 40 | }; 41 | -------------------------------------------------------------------------------- /src/DistanceMap.cpp: -------------------------------------------------------------------------------- 1 | #include "DistanceMap.h" 2 | #include "CCBot.h" 3 | #include "Util.h" 4 | 5 | const size_t LegalActions = 4; 6 | const int actionX[LegalActions] = {1, -1, 0, 0}; 7 | const int actionY[LegalActions] = {0, 0, 1, -1}; 8 | 9 | DistanceMap::DistanceMap() 10 | { 11 | 12 | } 13 | 14 | int DistanceMap::getDistance(int tileX, int tileY) const 15 | { 16 | BOT_ASSERT(tileX < m_width && tileY < m_height, "Index out of range: X = %d, Y = %d", tileX, tileY); 17 | return m_dist[tileX][tileY]; 18 | } 19 | 20 | int DistanceMap::getDistance(const CCTilePosition & pos) const 21 | { 22 | return getDistance(pos.x, pos.y); 23 | } 24 | 25 | int DistanceMap::getDistance(const CCPosition & pos) const 26 | { 27 | return getDistance(CCTilePosition((int)pos.x, (int)pos.y)); 28 | } 29 | 30 | const std::vector & DistanceMap::getSortedTiles() const 31 | { 32 | return m_sortedTiles; 33 | } 34 | 35 | // Computes m_dist[x][y] = ground distance from (startX, startY) to (x,y) 36 | // Uses BFS, since the map is quite large and DFS may cause a stack overflow 37 | void DistanceMap::computeDistanceMap(CCBot & m_bot, const CCTilePosition & startTile) 38 | { 39 | m_startTile = startTile; 40 | m_width = m_bot.Map().totalWidth(); 41 | m_height = m_bot.Map().totalHeight(); 42 | m_dist = std::vector>(m_width, std::vector(m_height, -1)); 43 | m_sortedTiles.reserve(m_width * m_height); 44 | 45 | // the fringe for the BFS we will perform to calculate distances 46 | std::vector fringe; 47 | fringe.reserve(m_width * m_height); 48 | fringe.push_back(startTile); 49 | m_sortedTiles.push_back(startTile); 50 | 51 | m_dist[(int)startTile.x][(int)startTile.y] = 0; 52 | 53 | for (size_t fringeIndex=0; fringeIndex 5 | 6 | class CCBot; 7 | 8 | 9 | class DistanceMap 10 | { 11 | int m_width; 12 | int m_height; 13 | CCTilePosition m_startTile; 14 | 15 | // 2D matrix storing distances from the start tile 16 | std::vector> m_dist; 17 | 18 | std::vector m_sortedTiles; 19 | 20 | public: 21 | 22 | DistanceMap(); 23 | void computeDistanceMap(CCBot & m_bot, const CCTilePosition & startTile); 24 | 25 | int getDistance(int tileX, int tileY) const; 26 | int getDistance(const CCTilePosition & pos) const; 27 | int getDistance(const CCPosition & pos) const; 28 | 29 | // given a position, get the position we should move to to minimize distance 30 | const std::vector & getSortedTiles() const; 31 | const CCTilePosition & getStartTile() const; 32 | 33 | void draw(CCBot & bot) const; 34 | }; -------------------------------------------------------------------------------- /src/GameCommander.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "Timer.hpp" 5 | #include "ProductionManager.h" 6 | #include "ScoutManager.h" 7 | #include "CombatCommander.h" 8 | 9 | class CCBot; 10 | 11 | class GameCommander 12 | { 13 | CCBot & m_bot; 14 | 15 | ProductionManager m_productionManager; 16 | ScoutManager m_scoutManager; 17 | CombatCommander m_combatCommander; 18 | 19 | std::vector m_validUnits; 20 | std::vector m_combatUnits; 21 | std::vector m_scoutUnits; 22 | 23 | std::vector m_unitInside; 24 | std::map m_unitCarrier; 25 | 26 | std::vector>> m_delayedSmartAbility; 27 | 28 | bool m_initialScoutSet; 29 | 30 | void assignUnit(const Unit & unit, std::vector & units); 31 | bool isAssigned(const Unit & unit) const; 32 | 33 | public: 34 | 35 | GameCommander(CCBot & bot); 36 | 37 | void onStart(); 38 | void onFrame(bool executeMacro); 39 | 40 | ProductionManager& Production(); 41 | CombatCommander& Combat(); 42 | 43 | void handleUnitAssignments(); 44 | void setValidUnits(); 45 | std::vector getValidUnits() const; 46 | void setScoutUnits(); 47 | void setCombatUnits(); 48 | void setCarryingAndCarried(); 49 | 50 | bool shouldSendInitialScout(); 51 | 52 | void onUnitCreate(const Unit & unit); 53 | void onUnitDestroy(const Unit & unit); 54 | 55 | //Carrier and Carried 56 | bool isInside(sc2::Tag unit); 57 | void setInside(sc2::Tag unit); 58 | Unit* getCarrierForUnit(sc2::Tag unitTag); 59 | Unit* setCarrierForUnit(sc2::Tag unitTag, Unit* carrier); 60 | void AddDelayedSmartAbility(Unit unit, sc2::AbilityID ability, CCPosition position); 61 | void GiveDelayedSmarAbilityOrders(); 62 | }; 63 | -------------------------------------------------------------------------------- /src/JSONTools.cpp: -------------------------------------------------------------------------------- 1 | #include "JSONTools.h" 2 | #include "BotAssert.h" 3 | 4 | namespace JSONTools 5 | { 6 | void ReadBool(const char * key, const json & j, bool & dest) 7 | { 8 | if (j.count(key)) 9 | { 10 | BOT_ASSERT(j[key].is_boolean(), "%s should be a bool", key); 11 | dest = j[key]; 12 | } 13 | } 14 | 15 | void ReadString(const char * key, const json & j, std::string & dest) 16 | { 17 | if (j.count(key)) 18 | { 19 | BOT_ASSERT(j[key].is_string(), "%s should be a string", key); 20 | dest = j[key].get(); 21 | } 22 | } 23 | 24 | 25 | std::string ReadFile(const std::string & filename) 26 | { 27 | std::ifstream t(filename); 28 | std::stringstream buffer; 29 | buffer << t.rdbuf(); 30 | return buffer.str(); 31 | } 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/JSONTools.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | 5 | namespace JSONTools 6 | { 7 | template 8 | void ReadInt(const char * key, const json & j, T & dest) 9 | { 10 | if (j.count(key)) 11 | { 12 | BOT_ASSERT(j[key].is_number_integer(), "%s should be an int", key); 13 | dest = (T)j[key]; 14 | } 15 | } 16 | 17 | template 18 | void ReadFloat(const char * key, const json & j, T & dest) 19 | { 20 | if (j.count(key)) 21 | { 22 | BOT_ASSERT(j[key].is_number_float(), "%s should be an float", key); 23 | dest = (T)j[key]; 24 | } 25 | } 26 | 27 | void ReadBool(const char * key, const json & json, bool & dest); 28 | void ReadString(const char * key, const json & json, std::string & dest); 29 | 30 | std::string ReadFile(const std::string & filename); 31 | } 32 | -------------------------------------------------------------------------------- /src/MeleeManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "MicroManager.h" 5 | 6 | class CCBot; 7 | 8 | class MeleeManager: public MicroManager 9 | { 10 | protected: 11 | CCPosition m_stackPosition = CCPosition(); 12 | Unit m_stackingMineral; 13 | bool m_mineralPocket = false; 14 | Unit m_enemyMineral; 15 | std::set m_stackedUnits; 16 | 17 | public: 18 | 19 | MeleeManager(CCBot & bot); 20 | void setTargets(const std::vector & targets); 21 | void executeMicro(); 22 | void microUnit(const Unit & meleeUnit); 23 | bool shouldStackWorkers() const; 24 | bool areUnitsStackedUp(); 25 | void stackUnits(); 26 | void identifyStackingMinerals(); 27 | void microStack(); 28 | void updateBackstabbers(); 29 | Unit getTarget(Unit meleeUnit, const std::vector & targets) const; 30 | }; 31 | -------------------------------------------------------------------------------- /src/MetaType.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "UnitType.h" 5 | 6 | namespace MetaTypes 7 | { 8 | enum { Unit, Upgrade, Buff, Tech, Ability, None }; 9 | } 10 | 11 | class CCBot; 12 | class MetaType 13 | { 14 | CCBot * m_bot; 15 | size_t m_type; 16 | std::string m_name; 17 | CCRace m_race; 18 | UnitType m_unitType; 19 | CCUpgrade m_upgrade; 20 | 21 | #ifndef SC2API 22 | BWAPI::TechType m_tech; 23 | #endif 24 | 25 | public: 26 | 27 | MetaType(); 28 | MetaType(const std::string & name, CCBot & bot); 29 | MetaType(const UnitType & unitType, CCBot & bot); 30 | MetaType(const CCUpgrade & upgradeType, CCBot & bot); 31 | 32 | bool isUnit() const; 33 | bool isUpgrade() const; 34 | bool isTech() const; 35 | bool isBuilding() const; 36 | bool isAddon() const; 37 | 38 | const size_t & getMetaType() const; 39 | const std::string & getName() const; 40 | const CCRace & getRace() const; 41 | const UnitType & getUnitType() const; 42 | const CCUpgrade & getUpgrade() const; 43 | 44 | std::vector whatBuilds; 45 | 46 | bool operator < (const MetaType & mt) const; 47 | bool operator == (const MetaType & mt) const; 48 | bool operator != (const MetaType & mt) const; 49 | 50 | #ifndef SC2API 51 | MetaType(const BWAPI::TechType & tech, CCBot & bot); 52 | const BWAPI::TechType & getTechType() const; 53 | #endif 54 | }; 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/Micro.cpp: -------------------------------------------------------------------------------- 1 | #include "Micro.h" 2 | #include "Util.h" 3 | #include "CCBot.h" 4 | #include "sc2api/sc2_api.h" 5 | 6 | const float dotRadius = 0.1f; 7 | 8 | MicroActionType Micro::SmartStop(const sc2::Unit * attacker, CCBot & bot) 9 | { 10 | BOT_ASSERT(attacker != nullptr, "Attacker is null"); 11 | bot.Actions()->UnitCommand(attacker, sc2::ABILITY_ID::STOP); 12 | bot.Map().drawCircle(CCPosition(attacker->pos), 2, CCColor(255, 0, 255)); 13 | return MicroActionType::Stop; 14 | } 15 | 16 | MicroActionType Micro::SmartAttackUnit(const sc2::Unit * attacker, const sc2::Unit * target, CCBot & bot) 17 | { 18 | BOT_ASSERT(attacker != nullptr, "Attacker is null"); 19 | BOT_ASSERT(target != nullptr, "Target is null"); 20 | bot.Actions()->UnitCommand(attacker, sc2::ABILITY_ID::ATTACK, target); 21 | return MicroActionType::AttackUnit; 22 | } 23 | 24 | MicroActionType Micro::SmartAttackMove(const sc2::Unit * attacker, const sc2::Point2D & targetPosition, CCBot & bot) 25 | { 26 | BOT_ASSERT(attacker != nullptr, "Attacker is null"); 27 | bot.Actions()->UnitCommand(attacker, sc2::ABILITY_ID::ATTACK, targetPosition); 28 | return MicroActionType::AttackMove; 29 | } 30 | 31 | MicroActionType Micro::SmartMove(const sc2::Unit * unit, const sc2::Point2D & targetPosition, CCBot & bot) 32 | { 33 | BOT_ASSERT(unit != nullptr, "Unit is null"); 34 | bot.Actions()->UnitCommand(unit, sc2::ABILITY_ID::MOVE, targetPosition); 35 | return MicroActionType::Move; 36 | } 37 | 38 | MicroActionType Micro::SmartHold(const sc2::Unit * unit, bool queued, CCBot & bot) 39 | { 40 | BOT_ASSERT(unit != nullptr, "Unit is null"); 41 | bot.Actions()->UnitCommand(unit, sc2::ABILITY_ID::HOLDPOSITION, queued); 42 | return MicroActionType::Move; 43 | } 44 | 45 | MicroActionType Micro::SmartRightClick(const sc2::Unit * unit, const sc2::Unit * target, CCBot & bot) 46 | { 47 | BOT_ASSERT(unit != nullptr, "Unit is null"); 48 | bot.Actions()->UnitCommand(unit, sc2::ABILITY_ID::SMART, target); 49 | return MicroActionType::RightClick; 50 | } 51 | 52 | MicroActionType Micro::SmartRightClick(const sc2::Units & units, const sc2::Unit * target, CCBot & bot) 53 | { 54 | bot.Actions()->UnitCommand(units, sc2::ABILITY_ID::SMART, target); 55 | return MicroActionType::RightClick; 56 | } 57 | 58 | MicroActionType Micro::SmartRepair(const sc2::Unit * unit, const sc2::Unit * target, CCBot & bot) 59 | { 60 | BOT_ASSERT(unit != nullptr, "Unit is null"); 61 | bot.Actions()->UnitCommand(unit, sc2::ABILITY_ID::SMART, target); 62 | return MicroActionType::RightClick; 63 | } 64 | 65 | MicroActionType Micro::SmartAbility(const sc2::Unit * unit, const sc2::AbilityID & abilityID, CCBot & bot) 66 | { 67 | BOT_ASSERT(unit != nullptr, "Unit using smart ability is null"); 68 | bot.Actions()->UnitCommand(unit, abilityID); 69 | return MicroActionType::Ability; 70 | } 71 | 72 | MicroActionType Micro::SmartAbility(const sc2::Unit * unit, const sc2::AbilityID & abilityID, CCPosition position, CCBot & bot) 73 | { 74 | BOT_ASSERT(unit != nullptr, "Unit using smart ability is null"); 75 | bot.Actions()->UnitCommand(unit, abilityID, position); 76 | return MicroActionType::AbilityPosition; 77 | } 78 | 79 | MicroActionType Micro::SmartAbility(const sc2::Unit * unit, const sc2::AbilityID & abilityID, const sc2::Unit * target, CCBot & bot) 80 | { 81 | BOT_ASSERT(unit != nullptr, "Unit using smart ability is null"); 82 | BOT_ASSERT(target != nullptr, "Target of smart ability is null"); 83 | bot.Actions()->UnitCommand(unit, abilityID, target); 84 | return MicroActionType::AbilityTarget; 85 | } 86 | 87 | MicroActionType Micro::SmartToggleAutoCast(const sc2::Unit * unit, const sc2::AbilityID & abilityID, CCBot & bot) 88 | { 89 | BOT_ASSERT(unit != nullptr, "Unit using smart toggle auto cast is null"); 90 | bot.Actions()->ToggleAutocast(unit->tag, abilityID); 91 | return MicroActionType::ToggleAbility; 92 | } -------------------------------------------------------------------------------- /src/Micro.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "sc2api/sc2_api.h" 5 | 6 | class CCBot; 7 | 8 | enum MicroActionType 9 | { 10 | Stop, 11 | AttackUnit, 12 | AttackMove, 13 | Move, 14 | RightClick, 15 | Ability, 16 | AbilityPosition, 17 | AbilityTarget, 18 | ToggleAbility, 19 | FSMKite, 20 | FSMFocusFire, 21 | }; 22 | 23 | const std::string MicroActionTypeAccronyms[] = {"S", "AU", "AM", "M", "RC", "A", "AP", "AT", "K", "FF"}; 24 | 25 | namespace Micro 26 | { 27 | MicroActionType SmartStop (const sc2::Unit * attacker, CCBot & bot); 28 | MicroActionType SmartAttackUnit (const sc2::Unit * attacker, const sc2::Unit * target, CCBot & bot); 29 | MicroActionType SmartAttackMove (const sc2::Unit * attacker, const sc2::Point2D & targetPosition, CCBot & bot); 30 | MicroActionType SmartMove (const sc2::Unit * unit, const sc2::Point2D & targetPosition, CCBot & bot); 31 | MicroActionType SmartHold (const sc2::Unit * unit, bool queued, CCBot & bot); 32 | MicroActionType SmartRightClick (const sc2::Unit * unit, const sc2::Unit * target, CCBot & bot); 33 | MicroActionType SmartRightClick (const sc2::Units & units, const sc2::Unit * target, CCBot & bot); 34 | MicroActionType SmartRepair (const sc2::Unit * unit, const sc2::Unit * target, CCBot & bot); 35 | MicroActionType SmartAbility (const sc2::Unit * unit, const sc2::AbilityID & abilityID, CCBot & bot); 36 | MicroActionType SmartAbility (const sc2::Unit * unit, const sc2::AbilityID & abilityID, CCPosition position, CCBot & bot); 37 | MicroActionType SmartAbility (const sc2::Unit * unit, const sc2::AbilityID & abilityID, const sc2::Unit * target, CCBot & bot); 38 | MicroActionType SmartToggleAutoCast(const sc2::Unit * unit, const sc2::AbilityID & abilityID, CCBot & bot); 39 | }; -------------------------------------------------------------------------------- /src/MicroManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "SquadOrder.h" 5 | #include "Unit.h" 6 | #include "Micro.h" 7 | 8 | class CCBot; 9 | class Squad; 10 | 11 | class MicroManager 12 | { 13 | protected: 14 | 15 | CCBot & m_bot; 16 | Squad * m_squad = nullptr; 17 | SquadOrder m_order; 18 | std::vector m_units; 19 | std::vector m_targets; 20 | std::set m_healingProbes; 21 | bool m_waitForProbesHealed; 22 | 23 | virtual void executeMicro() = 0; 24 | 25 | float calculateSplashDamageScore(const sc2::Unit * attacker, const sc2::Unit * splashTarget, float zoneDamagePercent) const; 26 | 27 | public: 28 | 29 | MicroManager(CCBot & bot); 30 | 31 | void setSquad(Squad * squadPtr) { m_squad = squadPtr; } 32 | const Squad * getSquad() const { return m_squad; } 33 | const std::vector & getUnits() const; 34 | void setUnits(const std::vector & u); 35 | std::vector getTargets() const { return m_targets; } 36 | virtual void setTargets(const std::vector & targets) = 0; 37 | void setOrder(SquadOrder order) { m_order = order; } 38 | void regroup(const CCPosition & regroupPosition) const; 39 | float getAverageSquadSpeed() const; 40 | float getAverageTargetsSpeed() const; 41 | float getSquadPower() const; 42 | float getTargetsPower(const std::vector& units) const; 43 | float getAttackPriority(const sc2::Unit * attacker, const sc2::Unit * target, const sc2::Units & allTargets, bool filterHighRangeUnits, bool considerOnlyUnitsInRange, bool reducePriorityOfUnpowered) const; 44 | float getPriorityOfTargetConsideringSplash(const sc2::Unit * attacker, const sc2::Unit * target, const sc2::Units & allTargets) const; 45 | }; -------------------------------------------------------------------------------- /src/RepairStationManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "BaseLocation.h" 3 | #include 4 | 5 | class CCBot; 6 | 7 | class RepairStationManager 8 | { 9 | public: 10 | RepairStationManager(CCBot& bot); 11 | 12 | void onStart(); 13 | void onFrame(); 14 | 15 | CCPosition getBestRepairStationForUnit(const sc2::Unit* unit); 16 | 17 | private: 18 | CCBot & m_bot; 19 | std::unordered_map> m_repairStations; 20 | std::unordered_map m_destinations; 21 | 22 | bool isRepairStationValidForBaseLocation(const BaseLocation * baseLocation, bool ignoreUnderAttack = true) const; 23 | void reservePlaceForUnit(const sc2::Unit* unit); 24 | void drawRepairStations(); 25 | }; 26 | 27 | -------------------------------------------------------------------------------- /src/ScoutManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "Unit.h" 5 | 6 | class CCBot; 7 | 8 | class ScoutManager 9 | { 10 | CCBot & m_bot; 11 | 12 | Unit m_scoutUnit; 13 | std::string m_scoutStatus; 14 | int m_numScouts; 15 | bool m_scoutUnderAttack; 16 | CCHealth m_previousScoutHP; 17 | 18 | bool enemyWorkerInRadiusOf(const CCPosition & pos) const; 19 | CCPosition getFleePosition() const; 20 | Unit closestEnemyWorkerTo(const CCPosition & pos) const; 21 | void moveScouts(); 22 | void drawScoutInformation(); 23 | 24 | 25 | public: 26 | 27 | ScoutManager(CCBot & bot); 28 | 29 | void onStart(); 30 | void onFrame(); 31 | void setWorkerScout(const Unit & unit); 32 | }; -------------------------------------------------------------------------------- /src/Squad.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "MeleeManager.h" 5 | #include "RangedManager.h" 6 | #include "SquadOrder.h" 7 | #include 8 | 9 | class CCBot; 10 | 11 | class Squad 12 | { 13 | CCBot & m_bot; 14 | 15 | std::string m_name; 16 | std::vector m_units; 17 | std::vector m_targets; 18 | 19 | int m_lastRegroupFrame; 20 | int m_regroupStartFrame; 21 | int m_maxRegroupDuration; 22 | int m_regroupCooldown; 23 | 24 | int m_retreatStartFrame; 25 | int m_minRetreatDuration; 26 | 27 | float m_maxDistanceFromCenter; 28 | 29 | bool m_isSuiciding; //used by the main attack squad when not retreating from a bad fight 30 | 31 | size_t m_priority; 32 | 33 | SquadOrder m_order; 34 | MeleeManager m_meleeManager; 35 | RangedManager m_rangedManager; 36 | 37 | std::map m_nearEnemy; 38 | 39 | Unit unitClosestToEnemy() const; 40 | 41 | void updateUnits(); 42 | void addUnitsToMicroManagers(); 43 | void setNearEnemyUnits(); 44 | void setAllUnits(); 45 | 46 | bool isUnitNearEnemy(const Unit & unit) const; 47 | int squadUnitsNear(const CCPosition & pos) const; 48 | 49 | public: 50 | 51 | Squad(const std::string & name, const SquadOrder & order, size_t priority, CCBot & bot); 52 | Squad(const std::string & name, const SquadOrder & order, int maxRegroupDuration, int regroupCooldown, int minRetreatDuration, float maxDistanceFromCenter, size_t priority, CCBot & bot); 53 | Squad(CCBot & bot); 54 | 55 | const std::vector & getTargets() const { return m_targets; } 56 | RangedManager & getRangedManager() { return m_rangedManager; } 57 | MeleeManager & getMeleeManager() { return m_meleeManager; } 58 | 59 | void onFrame(); 60 | void setSquadOrder(const SquadOrder & so); 61 | void addUnit(const Unit & unit); 62 | void removeUnit(const Unit & unit); 63 | void giveBackWorkers(); 64 | bool needsToRetreat(); 65 | bool isSuiciding() const; 66 | bool needsToRegroup(); 67 | void clear(); 68 | 69 | bool containsUnit(const Unit & unit) const; 70 | bool containsUnit(sc2::Tag tag) const; 71 | bool isEmpty() const; 72 | float getMaxDistanceFromCenter() const; 73 | void setMaxDistanceFromCenter(const float & maxDistanceFromCenter); 74 | size_t getPriority() const; 75 | void setPriority(const size_t & priority); 76 | const std::string & getName() const; 77 | 78 | CCPosition calcCenter() const; 79 | float calcAverageHeight() const; 80 | CCPosition calcRetreatPosition() const; 81 | std::vector calcVisibleTargets(); 82 | std::vector calcTargets(bool visibilityFilter = false); 83 | 84 | const std::vector & getUnits() const; 85 | size_t getUnitCountOfType(sc2::UNIT_TYPEID unitType) const; 86 | std::vector getUnitsOfType(sc2::UNIT_TYPEID unitType) const; 87 | SquadOrder & getSquadOrder(); 88 | }; 89 | -------------------------------------------------------------------------------- /src/SquadData.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "Squad.h" 5 | 6 | class CCBot; 7 | 8 | class SquadData 9 | { 10 | CCBot & m_bot; 11 | std::map m_squads; 12 | 13 | void updateAllSquads(); 14 | void verifySquadUniqueMembership(); 15 | 16 | public: 17 | 18 | SquadData(CCBot & bot); 19 | 20 | void onFrame(); 21 | void clearSquadData(); 22 | 23 | bool canAssignUnitToSquad(const Unit & unit, const Squad & squad, bool considerMaxSquadDistance = true) const; 24 | void assignUnitToSquad(const sc2::Unit* unitptr, Squad & squad); 25 | void assignUnitToSquad(const Unit & unit, Squad & squad); 26 | void addSquad(const std::string & squadName, const Squad & squad); 27 | void removeSquad(const std::string & squadName); 28 | void drawSquadInformation(); 29 | 30 | 31 | bool squadExists(const std::string & squadName); 32 | bool unitIsInSquad(const Unit & unit) const; 33 | const Squad * getUnitSquad(const Unit & unit) const; 34 | Squad * getUnitSquad(const Unit & unit); 35 | 36 | Squad & getSquad(const std::string & squadName); 37 | std::map & getSquads(); 38 | }; 39 | -------------------------------------------------------------------------------- /src/SquadOrder.cpp: -------------------------------------------------------------------------------- 1 | #include "SquadOrder.h" 2 | 3 | SquadOrder::SquadOrder() 4 | : m_type (SquadOrderTypes::None) 5 | , m_radius (0) 6 | { 7 | } 8 | 9 | SquadOrder::SquadOrder(int type, const CCPosition & position, float radius, std::string status) 10 | : m_type (type) 11 | , m_position(position) 12 | , m_radius (radius) 13 | , m_status (status) 14 | { 15 | } 16 | 17 | const std::string & SquadOrder::getStatus() const 18 | { 19 | return m_status; 20 | } 21 | 22 | const CCPosition & SquadOrder::getPosition() const 23 | { 24 | return m_position; 25 | } 26 | 27 | const float & SquadOrder::getRadius() const 28 | { 29 | return m_radius; 30 | } 31 | 32 | const size_t & SquadOrder::getType() const 33 | { 34 | return m_type; 35 | } -------------------------------------------------------------------------------- /src/SquadOrder.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | 5 | 6 | namespace SquadOrderTypes 7 | { 8 | enum { None, Idle, Attack, Defend, Clear, Retreat, Regroup, Harass, Scout, SquadOrderTypes }; 9 | } 10 | 11 | class SquadOrder 12 | { 13 | size_t m_type; 14 | float m_radius; 15 | CCPosition m_position; 16 | std::string m_status; 17 | 18 | public: 19 | 20 | SquadOrder(); 21 | SquadOrder(int type, const CCPosition & position, float radius, std::string status = "Default"); 22 | 23 | const std::string & getStatus() const; 24 | const CCPosition & getPosition() const; 25 | const float & getRadius() const; 26 | const size_t & getType() const; 27 | void setType(int type) { m_type = type; } 28 | void setRadius(float radius) { m_radius = radius; } 29 | void setStatus(std::string status) { m_status = status; } 30 | }; -------------------------------------------------------------------------------- /src/Strategy.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | struct ProtossStrategy { 5 | }; 6 | 7 | struct ZergStrategy { 8 | }; -------------------------------------------------------------------------------- /src/TechTree.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "UnitType.h" 5 | 6 | class CCBot; 7 | class MetaType; 8 | 9 | struct TypeData 10 | { 11 | CCRace race; 12 | int mineralCost = 0; // mineral cost of the item 13 | int gasCost = 0; // gas cost of the item 14 | int supplyCost = 0; // supply cost of the item 15 | int buildTime = 0; // build time of the item 16 | bool isUnit = false; 17 | bool isBuilding = false; 18 | bool isWorker = false; 19 | bool isRefinery = false; 20 | bool isSupplyProvider= false; 21 | bool isResourceDepot = false; 22 | bool isAddon = false; 23 | #ifdef SC2API 24 | sc2::AbilityID buildAbility = 0; // the ability that creates this item 25 | sc2::AbilityID warpAbility = 0; // the ability that creates this item via warp-in 26 | #endif 27 | std::vector whatBuilds; // any of these units can build the item 28 | std::vector requiredUnits; // owning ONE of these is required to make 29 | std::vector requiredUpgrades; // having ALL of these is required to make 30 | }; 31 | 32 | class TechTree 33 | { 34 | CCBot & m_bot; 35 | std::map m_unitTypeData; 36 | std::map m_upgradeData; 37 | std::map> m_buildingAbilitiesProductionTypes; // > 38 | 39 | void initUnitTypeData(); 40 | void initUpgradeData(); 41 | void initBuildingAbilitiesProductionTypes(); 42 | 43 | void outputJSON(const std::string & filename) const; 44 | 45 | public: 46 | 47 | TechTree(CCBot & bot); 48 | void onStart(); 49 | 50 | const TypeData & getData(const UnitType & type); 51 | const TypeData & getData(const CCUpgrade & type) const; 52 | const TypeData & getData(const MetaType & type); 53 | 54 | const UnitType & getUnitTypeFromBuildingAbility(sc2::UNIT_TYPEID buildingType, sc2::ABILITY_ID ability); 55 | }; -------------------------------------------------------------------------------- /src/Timer.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #ifdef WIN32 // Windows system specific 8 | #include 9 | #else // Unix based system specific 10 | #include 11 | #endif 12 | 13 | class Timer 14 | { 15 | double startTimeInMicroSec; // starting time in micro-second 16 | double endTimeInMicroSec; // ending time in micro-second 17 | int stopped; // stop flag 18 | #ifdef WIN32 19 | LARGE_INTEGER frequency; // ticks per second 20 | LARGE_INTEGER startCount; // 21 | LARGE_INTEGER endCount; // 22 | #else 23 | timeval startCount; // 24 | timeval endCount; // 25 | #endif 26 | 27 | public: 28 | 29 | Timer() 30 | { 31 | #ifdef WIN32 32 | QueryPerformanceFrequency(&frequency); 33 | startCount.QuadPart = 0; 34 | endCount.QuadPart = 0; 35 | #else 36 | startCount.tv_sec = startCount.tv_usec = 0; 37 | endCount.tv_sec = endCount.tv_usec = 0; 38 | #endif 39 | 40 | stopped = 0; 41 | startTimeInMicroSec = 0; 42 | endTimeInMicroSec = 0; 43 | 44 | start(); 45 | } 46 | 47 | ~Timer() {} // default destructor 48 | 49 | void start() 50 | { 51 | stopped = 0; // reset stop flag 52 | 53 | #ifdef WIN32 54 | QueryPerformanceCounter(&startCount); 55 | #else 56 | gettimeofday(&startCount, NULL); 57 | #endif 58 | } 59 | 60 | void stop() 61 | { 62 | stopped = 1; // set timer stopped flag 63 | 64 | #ifdef WIN32 65 | QueryPerformanceCounter(&endCount); 66 | #else 67 | gettimeofday(&endCount, NULL); 68 | #endif 69 | } 70 | 71 | double getElapsedTimeInMicroSec() 72 | { 73 | #ifdef WIN32 74 | if(!stopped) 75 | QueryPerformanceCounter(&endCount); 76 | 77 | startTimeInMicroSec = startCount.QuadPart * (1000000.0 / frequency.QuadPart); 78 | endTimeInMicroSec = endCount.QuadPart * (1000000.0 / frequency.QuadPart); 79 | #else 80 | if(!stopped) 81 | gettimeofday(&endCount, NULL); 82 | 83 | startTimeInMicroSec = (startCount.tv_sec * 1000000.0) + startCount.tv_usec; 84 | endTimeInMicroSec = (endCount.tv_sec * 1000000.0) + endCount.tv_usec; 85 | #endif 86 | 87 | return endTimeInMicroSec - startTimeInMicroSec; 88 | } 89 | 90 | double getElapsedTimeInMilliSec() 91 | { 92 | return this->getElapsedTimeInMicroSec() * 0.001; 93 | } 94 | 95 | 96 | double getElapsedTimeInSec() 97 | { 98 | return this->getElapsedTimeInMicroSec() * 0.000001; 99 | } 100 | 101 | double getElapsedTime() 102 | { 103 | return this->getElapsedTimeInSec(); 104 | } 105 | 106 | template 107 | static void TimeFunction(std::function function, ...) 108 | { 109 | Timer t; 110 | t.start(); 111 | va_list args; 112 | va_start(args, function); 113 | va_end(args); 114 | 115 | double ms = t.getElapsedTimeInMilliSec(); 116 | std::cout << "Function ran in " << ms << "ms\n"; 117 | } 118 | }; 119 | 120 | -------------------------------------------------------------------------------- /src/Unit.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "UnitType.h" 5 | 6 | class CCBot; 7 | 8 | class Unit 9 | { 10 | mutable CCBot * m_bot; 11 | CCUnitID m_unitID; 12 | UnitType m_unitType; 13 | 14 | #ifdef SC2API 15 | const sc2::Unit * m_unit; 16 | #else 17 | BWAPI::Unit m_unit; 18 | #endif 19 | 20 | public: 21 | 22 | Unit(); 23 | 24 | #ifdef SC2API 25 | Unit(const sc2::Unit * unit, CCBot & bot); 26 | const sc2::Unit * getUnitPtr() const; 27 | const sc2::UnitTypeID & getAPIUnitType() const; 28 | #else 29 | Unit(const BWAPI::Unit unit, CCBot & bot); 30 | const BWAPI::Unit getUnitPtr() const; 31 | const BWAPI::UnitType & getAPIUnitType() const; 32 | #endif 33 | 34 | bool operator < (const Unit & rhs) const; 35 | bool operator == (const Unit & rhs) const; 36 | bool operator != (const Unit & rhs) const; 37 | 38 | const UnitType & getType() const; 39 | bool hasAttribute(sc2::Attribute attribute) const; 40 | CCPosition getPosition() const; 41 | CCTilePosition getTilePosition() const; 42 | float getHitPointsPercentage() const; 43 | CCHealth getHitPoints() const; 44 | CCHealth getShields() const; 45 | CCHealth getEnergy() const; 46 | CCPlayer getPlayer() const; 47 | sc2::Tag getTag() const; 48 | int getTagAsInt() const; 49 | float getBuildProgress() const; 50 | int getWeaponCooldown() const; 51 | bool canAttackAir() const; 52 | bool canAttackGround() const; 53 | bool isCompleted() const; 54 | bool isBeingConstructed() const; 55 | bool isCloaked() const; 56 | bool isFlying() const; 57 | bool isLight() const; 58 | bool isArmored() const; 59 | bool isBiological() const; 60 | bool isMechanical() const; 61 | bool isPsionic() const; 62 | bool isMassive() const; 63 | bool isAlive() const; 64 | bool isPowered() const; 65 | bool isIdle() const; 66 | bool isBurrowed() const; 67 | bool isValid() const; 68 | bool isVisible() const; 69 | bool isTraining() const; 70 | bool isAddonTraining() const; 71 | bool isConstructing(const UnitType & type) const; 72 | bool isConstructingAnything() const; 73 | bool isCounterToUnit(const Unit& unit) const; 74 | bool isReturningCargo() const; 75 | sc2::Tag getAddonTag() const; 76 | bool isProducingAddon() const; 77 | bool isProductionBuildingIdle(bool underConstructionConsideredIdle, bool constructingAddonConsideredIdle) const; 78 | bool isMoving() const; 79 | 80 | void stop () const; 81 | void cancel () const; 82 | void attackUnit (const Unit & target) const; 83 | void attackMove (const CCPosition & targetPosition) const; 84 | void move (const CCPosition & targetPosition) const; 85 | void move (const CCTilePosition & targetTilePosition) const; 86 | void patrol (const CCPosition & targetPosition) const; 87 | void patrol (const CCTilePosition & targetPosition) const; 88 | void rightClick (const Unit & target) const; 89 | void shiftRightClick(const Unit & target) const; 90 | void rightClick (const sc2::Unit * target) const; 91 | void shiftRightClick(const sc2::Unit * target) const; 92 | void rightClick (const CCPosition position) const; 93 | void shiftRightClick(const CCPosition position) const; 94 | void repair (const Unit & target) const; 95 | void build (const UnitType & buildingType, CCTilePosition pos) const; 96 | void buildTarget (const UnitType & buildingType, const Unit & target) const; 97 | void harvestTarget (const Unit & target) const; 98 | void train (const UnitType & buildingType) const; 99 | void morph (const UnitType & type) const; 100 | bool unloadUnit (const sc2::Tag passengerTag) const; 101 | bool useAbility (const sc2::ABILITY_ID abilityId) const; 102 | sc2::AvailableAbilities getAbilities() const; 103 | void getBuildingLimits(CCTilePosition & bottomLeft, CCTilePosition & topRight) const; 104 | }; 105 | -------------------------------------------------------------------------------- /src/UnitData.cpp: -------------------------------------------------------------------------------- 1 | #include "UnitData.h" 2 | #include "Util.h" 3 | 4 | UnitData::UnitData() 5 | : m_mineralsLost(0) 6 | , m_gasLost(0) 7 | { 8 | 9 | } 10 | 11 | void UnitData::updateUnit(const Unit & unit) 12 | { 13 | bool firstSeen = false; 14 | const auto & it = m_unitMap.find(unit); 15 | if (it == m_unitMap.end()) 16 | { 17 | firstSeen = true; 18 | m_unitMap[unit] = UnitInfo(); 19 | } 20 | 21 | UnitInfo & ui = m_unitMap[unit]; 22 | ui.unit = unit; 23 | ui.player = unit.getPlayer(); 24 | ui.lastPosition = unit.getPosition(); 25 | ui.lastHealth = unit.getHitPoints(); 26 | ui.lastShields = unit.getShields(); 27 | ui.type = unit.getType(); 28 | ui.progress = unit.getBuildProgress(); 29 | ui.id = unit.getTag(); 30 | 31 | if (firstSeen) 32 | { 33 | if (m_numUnits.find(ui.type) == m_numUnits.end()) 34 | { 35 | m_numUnits[ui.type] = 0; 36 | } 37 | 38 | m_numUnits[ui.type]++; 39 | } 40 | } 41 | 42 | void UnitData::killUnit(const Unit & unit) 43 | { 44 | //_mineralsLost += unit->getType().mineralPrice(); 45 | //_gasLost += unit->getType().gasPrice(); 46 | m_numUnits[unit.getType()]--; 47 | m_numDeadUnits[unit.getType()]++; 48 | 49 | m_unitMap.erase(unit); 50 | } 51 | 52 | void UnitData::removeBadUnits() 53 | { 54 | for (auto iter = m_unitMap.begin(); iter != m_unitMap.end();) 55 | { 56 | if (badUnitInfo(iter->second)) 57 | { 58 | m_numUnits[iter->second.type]--; 59 | iter = m_unitMap.erase(iter); 60 | } 61 | else 62 | { 63 | iter++; 64 | } 65 | } 66 | } 67 | 68 | bool UnitData::badUnitInfo(const UnitInfo & ui) const 69 | { 70 | return false; 71 | } 72 | 73 | int UnitData::getGasLost() const 74 | { 75 | return m_gasLost; 76 | } 77 | 78 | int UnitData::getMineralsLost() const 79 | { 80 | return m_mineralsLost; 81 | } 82 | 83 | int UnitData::getNumUnits(const UnitType & t) const 84 | { 85 | if (m_numUnits.find(t) == m_numUnits.end()) 86 | { 87 | return 0; 88 | } 89 | 90 | return m_numUnits.at(t); 91 | } 92 | 93 | int UnitData::getNumDeadUnits(const UnitType & t) const 94 | { 95 | if (m_numDeadUnits.find(t) == m_numDeadUnits.end()) 96 | { 97 | return 0; 98 | } 99 | 100 | return m_numDeadUnits.at(t); 101 | } 102 | 103 | const std::map & UnitData::getUnitInfoMap() const 104 | { 105 | return m_unitMap; 106 | } -------------------------------------------------------------------------------- /src/UnitData.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "Util.h" 5 | #include "Unit.h" 6 | #include "UnitType.h" 7 | 8 | struct UnitInfo 9 | { 10 | // we need to store all of this data because if the unit is not visible, we 11 | // can't reference it from the unit pointer 12 | 13 | CCUnitID id; 14 | CCHealth lastHealth; 15 | CCHealth lastShields; 16 | CCPlayer player; 17 | Unit unit; 18 | CCPosition lastPosition; 19 | UnitType type; 20 | float progress; 21 | 22 | UnitInfo() 23 | : id(0) 24 | , lastHealth(0) 25 | , player(-1) 26 | , lastPosition(0, 0) 27 | , progress(1.0) 28 | { 29 | 30 | } 31 | 32 | bool operator == (const Unit & unit) const 33 | { 34 | return id == unit.getTag(); 35 | } 36 | 37 | bool operator == (const UnitInfo & rhs) const 38 | { 39 | return (id == rhs.id); 40 | } 41 | 42 | bool operator < (const UnitInfo & rhs) const 43 | { 44 | return (id < rhs.id); 45 | } 46 | }; 47 | 48 | typedef std::vector UnitInfoVector; 49 | 50 | class UnitData 51 | { 52 | std::map m_unitMap; 53 | std::map m_numDeadUnits; 54 | std::map m_numUnits; 55 | int m_mineralsLost; 56 | int m_gasLost; 57 | 58 | bool badUnitInfo(const UnitInfo & ui) const; 59 | 60 | public: 61 | 62 | UnitData(); 63 | 64 | void updateUnit(const Unit & unit); 65 | void killUnit(const Unit & unit); 66 | void removeBadUnits(); 67 | 68 | int getGasLost() const; 69 | int getMineralsLost() const; 70 | int getNumUnits(const UnitType & t) const; 71 | int getNumDeadUnits(const UnitType & t) const; 72 | const std::map & getUnitInfoMap() const; 73 | }; 74 | -------------------------------------------------------------------------------- /src/UnitInfoManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | #include "UnitData.h" 5 | #include "BaseLocation.h" 6 | #include "Unit.h" 7 | 8 | class CCBot; 9 | class UnitInfoManager 10 | { 11 | CCBot & m_bot; 12 | 13 | std::map m_unitData; 14 | std::map> m_units; 15 | 16 | void updateUnit(const Unit & unit); 17 | void updateUnitInfo(); 18 | bool isValidUnit(const Unit & unit); 19 | 20 | const UnitData & getUnitData(CCPlayer player) const; 21 | 22 | void drawSelectedUnitDebugInfo(); 23 | void drawUnitID(); 24 | 25 | public: 26 | 27 | UnitInfoManager(CCBot & bot); 28 | 29 | void onFrame(); 30 | void onStart(); 31 | 32 | const std::vector & getUnits(CCPlayer player) const; 33 | 34 | size_t getUnitTypeCount(CCPlayer player, UnitType type, bool completed = true, bool ignoreState = false, bool underConstruction = false) const; 35 | 36 | void getNearbyForce(std::vector & unitInfo, CCPosition p, int player, float radius) const; 37 | 38 | const std::map & getUnitInfoMap(CCPlayer player) const; 39 | 40 | //bool enemyHasCloakedUnits() const; 41 | void drawUnitInformation(float x, float y) const; 42 | 43 | }; -------------------------------------------------------------------------------- /src/UnitState.cpp: -------------------------------------------------------------------------------- 1 | #include "UnitState.h" 2 | 3 | UnitState::UnitState() 4 | { 5 | 6 | } 7 | 8 | UnitState::UnitState(const sc2::Unit* unitPtr) 9 | { 10 | m_previousHitPoints = unitPtr->health; 11 | m_previousShields = unitPtr->shield; 12 | m_previousEnergy = unitPtr->energy; 13 | 14 | m_hitPoints = unitPtr->health; 15 | m_shields = unitPtr->shield; 16 | m_energy = unitPtr->energy; 17 | 18 | unit = unitPtr; 19 | 20 | m_recentDamage = std::vector(REMEMBER_X_LAST_DOMMAGE_TAKEN, 0); 21 | } 22 | 23 | void UnitState::Reset() 24 | { 25 | wasUpdated = false; 26 | } 27 | 28 | void UnitState::Update() 29 | { 30 | wasUpdated = true; 31 | } 32 | 33 | void UnitState::Update(CCHealth hitPoints, CCHealth shields, CCHealth energy) 34 | { 35 | wasUpdated = true; 36 | 37 | m_previousHitPoints = m_hitPoints; 38 | m_previousShields = m_shields; 39 | m_previousEnergy = m_energy; 40 | 41 | m_hitPoints = hitPoints; 42 | m_shields = shields; 43 | m_energy = energy; 44 | 45 | int damage = m_previousShields - m_shields + m_previousHitPoints - m_hitPoints; 46 | m_damageTaken = damage > 0 ? damage : 0; 47 | 48 | m_totalRecentDamage -= m_recentDamage.at(REMEMBER_X_LAST_DOMMAGE_TAKEN - 1); 49 | std::rotate(m_recentDamage.begin(), 50 | m_recentDamage.end() - 1, // this will be the new first element 51 | m_recentDamage.end()); 52 | m_recentDamage.at(0) = m_damageTaken; 53 | m_totalRecentDamage += m_damageTaken; 54 | } 55 | 56 | bool UnitState::WasUpdated() const 57 | { 58 | return wasUpdated; 59 | } 60 | 61 | void UnitState::UpdateThreat(bool hasThreat) 62 | { 63 | for (int i = 0; i < CONSIDER_X_LAST_THREAT_CHECK - 1; i++) 64 | { 65 | m_recentThreat[i] = m_recentThreat[i + 1]; 66 | } 67 | m_recentThreat[CONSIDER_X_LAST_THREAT_CHECK - 1] = hasThreat; 68 | } 69 | 70 | bool UnitState::WasAttacked() const 71 | { 72 | return GetDamageTaken() > 0; 73 | } 74 | 75 | int UnitState::GetDamageTaken() const 76 | { 77 | return m_damageTaken; 78 | } 79 | 80 | int UnitState::GetRecentDamageTaken() const 81 | { 82 | return m_totalRecentDamage; 83 | } 84 | 85 | int UnitState::GetHealed() const 86 | { 87 | int heal = m_shields - m_previousShields + m_hitPoints - m_previousHitPoints; 88 | return heal > 0 ? heal : 0; 89 | } 90 | 91 | bool UnitState::HadRecentTreats() const 92 | { 93 | for (int i = 0; i < CONSIDER_X_LAST_THREAT_CHECK; i++) 94 | { 95 | if (m_recentThreat[i]) 96 | { 97 | return true; 98 | } 99 | } 100 | return false; 101 | } 102 | 103 | sc2::UNIT_TYPEID UnitState::GetType() const 104 | { 105 | return unit->unit_type; 106 | } -------------------------------------------------------------------------------- /src/UnitState.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Common.h" 3 | 4 | class UnitState 5 | { 6 | bool wasUpdated; 7 | int m_hitPoints; 8 | int m_previousHitPoints; 9 | int m_shields; 10 | int m_previousShields; 11 | int m_energy; 12 | int m_previousEnergy; 13 | int m_damageTaken; 14 | int m_totalRecentDamage = 0; 15 | 16 | const sc2::Unit* unit; 17 | 18 | static const int THREAT_CHECK_EVERY_X_FRAME = 5; 19 | static const int CONSIDER_X_LAST_THREAT_CHECK = 3; 20 | static const int REMEMBER_X_LAST_DOMMAGE_TAKEN = 24;//1 sec 21 | bool m_recentThreat[CONSIDER_X_LAST_THREAT_CHECK]; 22 | std::vector m_recentDamage; 23 | public: 24 | 25 | UnitState(); 26 | UnitState(const sc2::Unit* unitPtr); 27 | void Reset(); 28 | void Update(); 29 | void Update(CCHealth hitPoints, CCHealth shields, CCHealth energy); 30 | bool WasUpdated() const; 31 | void UpdateThreat(bool hasThreat); 32 | 33 | bool WasAttacked() const; 34 | int GetDamageTaken() const; 35 | int GetRecentDamageTaken() const; 36 | int GetHealed() const; 37 | bool HadRecentTreats() const; 38 | sc2::UNIT_TYPEID GetType() const; 39 | }; -------------------------------------------------------------------------------- /src/UnitType.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Common.h" 4 | 5 | class CCBot; 6 | 7 | class UnitType 8 | { 9 | mutable CCBot * m_bot; 10 | 11 | #ifdef SC2API 12 | sc2::UnitTypeID m_type; 13 | #else 14 | BWAPI::UnitType m_type; 15 | #endif 16 | 17 | public: 18 | 19 | UnitType(); 20 | 21 | static sc2::UNIT_TYPEID getEnemyRefineryType(sc2::Race enemyRace); 22 | static bool isTargetable(sc2::UnitTypeID unitTypeId); 23 | static bool isDetector(sc2::UnitTypeID unitTypeId); 24 | static bool isSpawnedUnit(sc2::UnitTypeID unitTypeId); 25 | static bool isRefinery(sc2::UnitTypeID unitTypeId); 26 | static bool hasSplashingAttack(sc2::UnitTypeID unitTypeId, bool air); 27 | 28 | #ifdef SC2API 29 | UnitType(const sc2::UnitTypeID & type, CCBot & bot); 30 | sc2::UnitTypeID getAPIUnitType() const; 31 | bool is(const sc2::UnitTypeID & type) const; 32 | #else 33 | UnitType(const BWAPI::UnitType & type, CCBot & bot); 34 | BWAPI::UnitType getAPIUnitType() const; 35 | bool is(const BWAPI::UnitType & type) const; 36 | #endif 37 | 38 | bool operator < (const UnitType & rhs) const; 39 | bool operator == (const UnitType & rhs) const; 40 | bool operator != (const UnitType & rhs) const; 41 | 42 | std::string getName() const; 43 | CCRace getRace() const; 44 | 45 | bool isValid() const; 46 | bool isBuilding() const; 47 | bool isCombatUnit() const; 48 | bool isSpawnedUnit() const; 49 | bool isSupplyProvider() const; 50 | bool isResourceDepot() const; 51 | bool isRefinery() const; 52 | bool hasSplashingAttack(bool air) const; 53 | bool isDetector() const; 54 | bool isGeyser() const; 55 | bool isMineral() const; 56 | bool isStandardMineral() const; 57 | bool isRichMineral() const; 58 | bool isMineralWallPatch() const; 59 | bool isWorker() const; 60 | bool isMule() const; 61 | bool isCreepTumor() const; 62 | bool isMorphedBuilding() const; 63 | sc2::UNIT_TYPEID getBaseUnitTypeOfMorphedBuilding() const; 64 | bool isMorphableBuilding() const; 65 | std::vector getMorphedUnitTypesOfBuilding() const; 66 | bool isAttackingBuilding() const; 67 | bool isAddon() const; 68 | CCPositionType getAttackRange() const; 69 | float radius() const; 70 | int tileWidth() const; 71 | int tileHeight() const; 72 | int supplyProvided() const; 73 | int supplyRequired() const; 74 | int mineralPrice() const; 75 | int gasPrice() const; 76 | 77 | static UnitType GetUnitTypeFromName(const std::string & name, CCBot & bot); 78 | 79 | // lazy functions to let me know if this type is a special type 80 | bool isOverlord() const; 81 | bool isCocoon() const; 82 | bool isLarva() const; 83 | bool isEgg() const; 84 | bool isQueen() const; 85 | bool isTank() const; 86 | bool isRepairable() const; 87 | }; 88 | -------------------------------------------------------------------------------- /src/WorkerData.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Common.h" 3 | #include "Unit.h" 4 | #include "BaseLocation.h" 5 | #include 6 | 7 | class CCBot; 8 | 9 | namespace WorkerJobs 10 | { 11 | enum { Minerals, Gas, Build, Combat, Idle, Repair, Move, Scout, GeyserProtect, None, Num }; 12 | } 13 | 14 | class WorkerData 15 | { 16 | CCBot & m_bot; 17 | 18 | std::set m_workers; 19 | std::set m_proxyWorkers; 20 | std::set m_depots; 21 | std::set m_idleWorkers; 22 | std::set m_mineralWorkers; 23 | std::map m_workerJobCount; 24 | std::map m_workerJobMap; 25 | std::map m_refineryWorkerCount; 26 | std::map m_depotWorkerCount; 27 | std::map m_workerRefineryMap; 28 | std::map> m_refineryWorkerMap; 29 | std::map> m_workerRepairing; 30 | std::map> m_repairStationWorkers; 31 | std::map m_workerRepairTarget; 32 | Unit m_idleMineralTarget; 33 | 34 | void clearPreviousJob(const Unit & unit); 35 | std::set getWorkerRepairingThatTarget(const Unit & unit); 36 | const Unit GetBestMineralWithLessWorkersInLists(const std::vector & closeMinerals, const std::vector & farMinerals, const CCPosition location) const; 37 | 38 | public: 39 | //Public variables for simplicity 40 | std::map m_workerMineralMap; 41 | std::map> m_mineralWorkersMap; 42 | std::map m_workerGeyserMap; 43 | std::map m_workerDepotMap; // 44 | 45 | WorkerData(CCBot & bot); 46 | 47 | void workerDestroyed(const Unit & unit); 48 | void updateAllWorkerData(); 49 | void updateIdleMineralTarget(); 50 | void updateWorker(const Unit & unit); 51 | void setWorkerJob(const Unit & unit, int job, Unit jobUnit = Unit()); 52 | void drawDepotDebugInfo(); 53 | size_t getNumWorkers() const; 54 | int getWorkerJobCount(int job) const; 55 | int getNumAssignedWorkers(const Unit & unit); 56 | std::vector getAssignedWorkersRefinery(const Unit & unit); 57 | int getWorkerJob(const Unit & unit) const; 58 | bool isReturningCargo(const Unit & unit) const; 59 | bool isActivelyReturningCargo(const Unit & unit) const; 60 | int getCountWorkerAtDepot(const Unit & depot) const; 61 | Unit getMineralToMine(const Unit & unit, const CCPosition location) const; 62 | Unit getWorkerDepot(const Unit & unit) const; 63 | const char * getJobCode(const Unit & unit); 64 | const std::set & getWorkers() const; 65 | const std::set & getProxyWorkers() const; 66 | const std::set getIdleWorkers() const; 67 | const std::set getMineralWorkers() const; 68 | void sendIdleWorkerToIdleSpot(const Unit & worker, bool force); 69 | void sendIdleWorkerToMiningSpot(const Unit & worker, bool force); 70 | bool isProxyWorker(const Unit & unit) const; 71 | void setProxyWorker(const Unit & unit); 72 | bool isAnyMineralAvailable(CCPosition workerCurrentPosition) const; 73 | void removeProxyWorker(const Unit & unit); 74 | void clearProxyWorkers(); 75 | std::map>& getRepairStationWorkers(); 76 | void validateRepairStationWorkers(); 77 | Unit GetBestMineralInList(const std::vector & unitsToTest, CCPosition depotPosition, bool checkVisibility) const; 78 | Unit GetBestMineralInList(const std::vector & unitsToTest, const Unit & worker, bool checkVisibility) const; 79 | Unit getWorkerRepairTarget(const Unit & unit) const; 80 | int getWorkerRepairingTargetCount(const Unit & unit); 81 | const std::set getWorkerRepairingThatTargetC(const Unit & unit) const; 82 | void WorkerStoppedRepairing(const Unit & unit); 83 | Unit updateWorkerDepot(const Unit & worker, const Unit & mineral); 84 | }; -------------------------------------------------------------------------------- /src/libvoxelbot/buildorder/build_order.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "sc2api/sc2_interfaces.h" 4 | 5 | using namespace std; 6 | 7 | namespace libvoxelbot { 8 | struct BuildState; 9 | 10 | static const int UPGRADE_ID_OFFSET = 1000000; 11 | struct BuildOrderItem { 12 | public: 13 | // union ish. It is assumed that unit type ids are pretty small (which they are) 14 | sc2::UNIT_TYPEID internalType = sc2::UNIT_TYPEID::INVALID; 15 | bool chronoBoosted = false; 16 | 17 | bool isUnitType() const { 18 | return (int)internalType < UPGRADE_ID_OFFSET; 19 | } 20 | 21 | sc2::UNIT_TYPEID rawType() const { 22 | return internalType; 23 | } 24 | 25 | sc2::UNIT_TYPEID typeID() const { 26 | assert((int)internalType < UPGRADE_ID_OFFSET); 27 | return internalType; 28 | } 29 | 30 | sc2::UPGRADE_ID upgradeID() const { 31 | return (sc2::UPGRADE_ID)((int)internalType - UPGRADE_ID_OFFSET); 32 | } 33 | 34 | BuildOrderItem() {} 35 | explicit BuildOrderItem(sc2::UPGRADE_ID upgrade, bool chronoBoosted = false) : internalType((sc2::UNIT_TYPEID)((int)upgrade + UPGRADE_ID_OFFSET)), chronoBoosted(chronoBoosted) {} 36 | explicit BuildOrderItem(sc2::UNIT_TYPEID type) : internalType(type), chronoBoosted(false) {} 37 | explicit BuildOrderItem(sc2::UNIT_TYPEID type, bool chronoBoosted) : internalType(type), chronoBoosted(chronoBoosted) {} 38 | 39 | bool operator==(const BuildOrderItem& other) const { 40 | return internalType == other.internalType && chronoBoosted == other.chronoBoosted; 41 | } 42 | 43 | bool operator!=(const BuildOrderItem& other) const { 44 | return internalType != other.internalType || chronoBoosted != other.chronoBoosted; 45 | } 46 | 47 | std::string name() const { 48 | if (isUnitType()) return sc2::UnitTypeToName(typeID()); 49 | else return sc2::UpgradeIDToName(upgradeID()); 50 | } 51 | }; 52 | 53 | enum class BuildOrderPrintMode { 54 | Brief, 55 | Detailed 56 | }; 57 | 58 | struct BuildOrder { 59 | std::vector items; 60 | 61 | BuildOrder() {} 62 | 63 | BuildOrder(std::initializer_list order) { 64 | for (auto tp : order) { 65 | items.push_back(tp); 66 | } 67 | } 68 | 69 | BuildOrder(std::initializer_list order) { 70 | for (auto tp : order) { 71 | items.push_back(BuildOrderItem(tp)); 72 | } 73 | } 74 | 75 | explicit BuildOrder(const std::vector& order) : items(order.size()) { 76 | for (size_t i = 0; i < order.size(); i++) { 77 | items[i] = BuildOrderItem(order[i]); 78 | } 79 | } 80 | 81 | inline size_t size() const noexcept { 82 | return items.size(); 83 | } 84 | 85 | inline BuildOrderItem& operator[] (int index) { 86 | return items[index]; 87 | } 88 | 89 | inline const BuildOrderItem& operator[] (int index) const { 90 | return items[index]; 91 | } 92 | 93 | std::vector::const_iterator begin() const { return items.begin(); } 94 | std::vector::const_iterator end() const { return items.end(); } 95 | std::vector::iterator begin() { return items.begin(); } 96 | std::vector::iterator end() { return items.end(); } 97 | 98 | std::string toString(); 99 | std::string toString(BuildState initialState, BuildOrderPrintMode mode = BuildOrderPrintMode::Brief); 100 | }; 101 | 102 | 103 | struct BuildOrderState { 104 | std::shared_ptr buildOrder; 105 | int buildIndex = 0; 106 | sc2::UNIT_TYPEID lastChronoUnit = sc2::UNIT_TYPEID::INVALID; 107 | 108 | BuildOrderState(std::shared_ptr buildOrder) : buildOrder(buildOrder) {} 109 | }; 110 | 111 | void printBuildOrder(const std::vector& buildOrder); 112 | void printBuildOrder(const BuildOrder& buildOrder); 113 | } -------------------------------------------------------------------------------- /src/libvoxelbot/buildorder/build_time_estimator.cpp: -------------------------------------------------------------------------------- 1 | #include "build_time_estimator.h" 2 | #include "../utilities/python_utils.h" 3 | #include "../combat/simulator.h" 4 | 5 | using namespace std; 6 | using namespace sc2; 7 | 8 | void BuildOptimizerNN::init() { 9 | } 10 | 11 | vector> BuildOptimizerNN::predictTimeToBuild(const vector>& startingState, const BuildResources& startingResources, const vector < vector>>& targets) const { 12 | return vector>(targets.size(), vector(3)); 13 | } 14 | -------------------------------------------------------------------------------- /src/libvoxelbot/buildorder/build_time_estimator.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "../utilities/mappings.h" 4 | 5 | struct BuildResources; 6 | 7 | struct BuildOptimizerNN { 8 | 9 | void init(); 10 | 11 | std::vector> predictTimeToBuild(const std::vector>& startingState, const BuildResources& startingResources, const std::vector < std::vector>>& targets) const; 12 | }; 13 | -------------------------------------------------------------------------------- /src/libvoxelbot/buildorder/optimizer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "../combat/simulator.h" 4 | #include "build_order.h" 5 | #include "build_state.h" 6 | 7 | struct GeneUnitType { 8 | int type = -1; 9 | bool chronoBoosted = false; 10 | 11 | GeneUnitType() {} 12 | GeneUnitType(int type) : type(type), chronoBoosted(false) {} 13 | GeneUnitType(int type, bool chronoBoosted) : type(type), chronoBoosted(chronoBoosted) {} 14 | 15 | bool operator==(const GeneUnitType& other) const { 16 | return type == other.type && chronoBoosted == other.chronoBoosted; 17 | } 18 | 19 | bool operator!=(const GeneUnitType& other) const { 20 | return type != other.type || chronoBoosted != other.chronoBoosted; 21 | } 22 | }; 23 | 24 | struct BuildOrderFitness { 25 | static const BuildOrderFitness ReallyBad; 26 | 27 | float time; 28 | BuildResources resources; 29 | MiningSpeed miningSpeed; 30 | MiningSpeed miningSpeedPerSecond; 31 | 32 | BuildOrderFitness () : time(0), resources(0,0), miningSpeed({0,0}), miningSpeedPerSecond({0, 0}) {} 33 | BuildOrderFitness (float time, BuildResources resources, MiningSpeed miningSpeed, MiningSpeed miningSpeedPerSecond) : time(time), resources(resources), miningSpeed(miningSpeed), miningSpeedPerSecond(miningSpeedPerSecond) {} 34 | 35 | float score() const; 36 | 37 | bool operator<(const BuildOrderFitness& other) const; 38 | }; 39 | 40 | struct BuildOptimizerParams { 41 | int genePoolSize = 25; 42 | int iterations = 512; 43 | float mutationRateAddRemove = 0.05f; 44 | float mutationRateMove = 0.025f; 45 | float varianceBias = 0; 46 | bool allowChronoBoost = true; 47 | }; 48 | 49 | std::pair> expandBuildOrderWithImplicitSteps (const libvoxelbot::BuildState& startState, libvoxelbot::BuildOrder buildOrder); 50 | 51 | libvoxelbot::BuildOrder findBestBuildOrderGenetic(const std::vector>& startingUnits, const std::vector>& target); 52 | libvoxelbot::BuildOrder findBestBuildOrderGenetic(const libvoxelbot::BuildState& startState, const std::vector>& target, const libvoxelbot::BuildOrder* seed = nullptr, BuildOptimizerParams params = BuildOptimizerParams()); 53 | std::pair findBestBuildOrderGeneticWithFitness(const libvoxelbot::BuildState& startState, const std::vector>& target, const libvoxelbot::BuildOrder* seed = nullptr, BuildOptimizerParams params = BuildOptimizerParams()); 54 | libvoxelbot::BuildOrder findBestBuildOrderGenetic(const libvoxelbot::BuildState& startState, const std::vector>& target, const libvoxelbot::BuildOrder* seed = nullptr, BuildOptimizerParams params = BuildOptimizerParams()); 55 | void unitTestBuildOptimizer(); 56 | void printBuildOrderDetailed(const libvoxelbot::BuildState& startState, const libvoxelbot::BuildOrder& buildOrder, const std::vector* highlight = nullptr); 57 | void optimizeExistingBuildOrder(const sc2::ObservationInterface* observation, const std::vector& ourUnits, const libvoxelbot::BuildState& buildOrderStartingState, BuildOrderTracker& buildOrder, bool serialize); 58 | BuildOrderFitness calculateFitness(const libvoxelbot::BuildState& startState, const libvoxelbot::BuildOrder& buildOrder); -------------------------------------------------------------------------------- /src/libvoxelbot/buildorder/tracker.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "optimizer.h" 3 | #include 4 | #include "../../BuildOrder.h" 5 | 6 | struct BuildOrderTracker { 7 | private: 8 | std::map ignoreUnits; 9 | std::vector buildOrderUnits; 10 | int tick; 11 | public: 12 | std::set knownUnits; 13 | libvoxelbot::BuildOrder buildOrder; 14 | 15 | BuildOrderTracker () {} 16 | BuildOrderTracker (libvoxelbot::BuildOrder buildOrder); 17 | 18 | void setBuildOrder (libvoxelbot::BuildOrder buildOrder); 19 | void tweakBuildOrder (std::vector keepMask, libvoxelbot::BuildOrder buildOrder); 20 | void addExistingUnit(const sc2::Unit* unit); 21 | 22 | void ignoreUnit (sc2::UNIT_TYPEID type, int count); 23 | std::vector update(const sc2::ObservationInterface* observation, const std::vector& ourUnits); 24 | }; 25 | -------------------------------------------------------------------------------- /src/libvoxelbot/caching/dependency_analyzer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "sc2api/sc2_api.h" 3 | #include 4 | 5 | struct DependencyAnalyzer { 6 | std::vector> allUnitDependencies; 7 | void analyze(); 8 | }; 9 | -------------------------------------------------------------------------------- /src/libvoxelbot/combat/combat_environment.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "sc2api/sc2_interfaces.h" 3 | #include 4 | #include 5 | #include 6 | #include "combat_upgrades.h" 7 | 8 | struct CombatUnit; 9 | 10 | struct WeaponInfo { 11 | private: 12 | mutable std::map dpsCache; 13 | float baseDPS; 14 | 15 | public: 16 | bool available; 17 | float splash; 18 | const sc2::Weapon* weapon; 19 | 20 | float getDPS() const { 21 | return baseDPS; 22 | } 23 | 24 | float getDPS(sc2::UNIT_TYPEID target, float modifier = 0) const; 25 | 26 | float range() const; 27 | 28 | WeaponInfo() 29 | : baseDPS(0), available(false), splash(0), weapon(nullptr) { 30 | } 31 | 32 | WeaponInfo(const sc2::Weapon* weapon, sc2::UNIT_TYPEID type, const CombatUpgrades& upgrades, const CombatUpgrades& targetUpgrades); 33 | }; 34 | 35 | struct UnitCombatInfo { 36 | WeaponInfo groundWeapon; 37 | WeaponInfo airWeapon; 38 | 39 | // In case the unit has multiple weapons this is the fastest of the two weapons 40 | float attackInterval() const; 41 | 42 | UnitCombatInfo(sc2::UNIT_TYPEID type, const CombatUpgrades& upgrades, const CombatUpgrades& targetUpgrades); 43 | }; 44 | 45 | struct CombatEnvironment { 46 | std::array, 2> combatInfo; 47 | std::array upgrades; 48 | 49 | CombatEnvironment(const CombatUpgrades& upgrades, const CombatUpgrades& targetUpgrades); 50 | 51 | float attackRange(int owner, sc2::UNIT_TYPEID type) const; 52 | float attackRange(const CombatUnit& unit) const; 53 | const UnitCombatInfo& getCombatInfo(const CombatUnit& unit) const; 54 | float calculateDPS(int owner, sc2::UNIT_TYPEID type, bool air) const; 55 | float calculateDPS(const std::vector& units, bool air) const; 56 | float calculateDPS(const CombatUnit& unit, bool air) const; 57 | float calculateDPS(const CombatUnit& unit1, const CombatUnit& unit2) const; 58 | }; 59 | -------------------------------------------------------------------------------- /src/libvoxelbot/combat/combat_upgrades.cpp: -------------------------------------------------------------------------------- 1 | #include "combat_upgrades.h" 2 | #include "../common/unit_lists.h" 3 | 4 | CombatUpgrades::CombatUpgrades() { 5 | // It's a bit tricky to set the template argument to the upgrades array based on the availableUpgrades list 6 | // so instead we just validate it at runtime here. 7 | // If new upgrades are introduced the upgrades bitset needs to be expanded. 8 | assert(upgrades.size() >= availableUpgrades.size()); 9 | } 10 | 11 | sc2::UPGRADE_ID CombatUpgrades::iterator::operator*() const { return availableUpgrades.getBuildOrderItem(index).upgradeID(); } 12 | 13 | bool CombatUpgrades::hasUpgrade(sc2::UPGRADE_ID upgrade) const { 14 | const auto index = availableUpgrades.getIndex(upgrade); 15 | if (index < 0 || index >= upgrades.size()) 16 | return false; 17 | return upgrades[index]; 18 | } 19 | 20 | void CombatUpgrades::add(sc2::UPGRADE_ID upgrade) { 21 | const auto index = availableUpgrades.getIndex(upgrade); 22 | if (index >= 0 && index < upgrades.size()) 23 | upgrades[index] = true; 24 | } -------------------------------------------------------------------------------- /src/libvoxelbot/combat/combat_upgrades.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "sc2api/sc2_interfaces.h" 4 | 5 | struct CombatUpgrades { 6 | std::bitset<90> upgrades; 7 | 8 | struct iterator { 9 | const CombatUpgrades& parent; 10 | size_t index = 0; 11 | iterator(const CombatUpgrades& parent, size_t index): parent(parent), index(index) { 12 | while(this->index < parent.upgrades.size() && !parent.upgrades[this->index]) this->index++; 13 | } 14 | iterator operator++() { 15 | index++; 16 | while(index < parent.upgrades.size() && !parent.upgrades[index]) index++; 17 | return *this; 18 | } 19 | bool operator!=(const iterator & other) const { 20 | return index != other.index; 21 | } 22 | sc2::UPGRADE_ID operator*() const; 23 | }; 24 | 25 | CombatUpgrades(); 26 | 27 | CombatUpgrades(std::initializer_list upgrades) { 28 | for (auto u : upgrades) add(u); 29 | } 30 | 31 | bool hasUpgrade(sc2::UPGRADE_ID upgrade) const; 32 | 33 | uint64_t hash() const { 34 | return std::hash>()(upgrades); 35 | } 36 | 37 | void add(sc2::UPGRADE_ID upgrade); 38 | 39 | void combine(const CombatUpgrades& other) { 40 | upgrades |= other.upgrades; 41 | } 42 | 43 | void remove(const CombatUpgrades& other) { 44 | upgrades &= ~other.upgrades; 45 | } 46 | 47 | iterator begin() const { return iterator(*this, 0 ); } 48 | iterator end() const { return iterator(*this, upgrades.size() ); } 49 | }; 50 | -------------------------------------------------------------------------------- /src/libvoxelbot/generated/abilities.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | extern std::vector> unit_type_has_ability; 4 | extern std::vector> unit_type_initial_health; 5 | extern std::vector unit_type_is_flying; 6 | extern std::vector unit_type_radius; 7 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/build_state_serialization.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "../combat/simulator.h" 4 | #include "src/libvoxelbot/buildorder/build_state.h" 5 | #include "src/libvoxelbot/buildorder/optimizer.h" 6 | 7 | 8 | template 9 | void serialize(Archive& archive, MiningSpeed& data) { 10 | archive( 11 | cereal::make_nvp("mineralsPerSecond", data.mineralsPerSecond), 12 | cereal::make_nvp("vespenePerSecond", data.vespenePerSecond) 13 | ); 14 | } 15 | 16 | template 17 | void serialize(Archive& archive, BuildOrderFitness& data) { 18 | archive( 19 | cereal::make_nvp("time", data.time), 20 | cereal::make_nvp("resources", data.resources), 21 | cereal::make_nvp("miningSpeed", data.miningSpeed), 22 | cereal::make_nvp("miningSpeedPerSecond", data.miningSpeedPerSecond) 23 | ); 24 | } 25 | 26 | template 27 | void serialize(Archive& archive, BuildOrderItem& data) { 28 | archive( 29 | cereal::make_nvp("type", data.internalType), 30 | cereal::make_nvp("chronoBoosted", data.chronoBoosted) 31 | ); 32 | } 33 | 34 | template 35 | void serialize(Archive& archive, BuildOrder& data) { 36 | archive( 37 | cereal::make_nvp("items", data.items) 38 | ); 39 | } 40 | 41 | template 42 | void serialize(Archive& archive, CombatUpgrades& data) { 43 | archive( 44 | cereal::make_nvp("upgrades", data.upgrades) 45 | ); 46 | } 47 | 48 | template 49 | void serialize(Archive& archive, ChronoBoostInfo& data) { 50 | archive( 51 | cereal::make_nvp("energyOffsets", data.energyOffsets), 52 | cereal::make_nvp("chronoEndTimes", data.chronoEndTimes) 53 | ); 54 | } 55 | 56 | template 57 | void serialize(Archive& archive, BaseInfo& data) { 58 | archive( 59 | cereal::make_nvp("remainingMinerals", data.remainingMinerals), 60 | cereal::make_nvp("remainingVespene1", data.remainingVespene1), 61 | cereal::make_nvp("remainingVespene2", data.remainingVespene2) 62 | ); 63 | } 64 | 65 | template 66 | void serialize(Archive& archive, BuildEvent& data) { 67 | archive( 68 | cereal::make_nvp("type", data.type), 69 | cereal::make_nvp("ability", data.ability), 70 | cereal::make_nvp("caster", data.caster), 71 | cereal::make_nvp("casterAddon", data.casterAddon), 72 | cereal::make_nvp("time", data.time), 73 | cereal::make_nvp("chronoEndTime", data.chronoEndTime) 74 | ); 75 | } 76 | 77 | template 78 | void serialize(Archive& archive, BuildResources& data) { 79 | archive( 80 | cereal::make_nvp("minerals", data.minerals), 81 | cereal::make_nvp("vespene", data.vespene) 82 | ); 83 | } 84 | 85 | template 86 | void serialize(Archive& archive, BuildUnitInfo& data) { 87 | archive( 88 | cereal::make_nvp("type", data.type), 89 | cereal::make_nvp("addon", data.addon), 90 | cereal::make_nvp("units", data.units), 91 | cereal::make_nvp("busyUnits", data.busyUnits) 92 | ); 93 | } 94 | 95 | template 96 | void serialize(Archive& archive, libvoxelbot::BuildState& state) { 97 | archive( 98 | cereal::make_nvp("time", state.time), 99 | cereal::make_nvp("race", state.race), 100 | cereal::make_nvp("units", state.units), 101 | cereal::make_nvp("events", state.events), 102 | cereal::make_nvp("resources", state.resources), 103 | cereal::make_nvp("baseInfos", state.baseInfos), 104 | cereal::make_nvp("chronoInfo", state.chronoInfo), 105 | cereal::make_nvp("upgrades", state.upgrades) 106 | ); 107 | } 108 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/bump_allocator.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | // A simple bump allocator 5 | // Much faster than new or shared pointers 6 | 7 | template 8 | struct BumpAllocator { 9 | private: 10 | // const size_t BlockSize = 128; 11 | std::vector blocks; 12 | std::vector freeBlocks; 13 | size_t currentBlockCount = 0; 14 | T* currentBlock = nullptr; 15 | 16 | void grow() { 17 | if (currentBlock != nullptr) blocks.push_back(currentBlock); 18 | 19 | currentBlockCount = 0; 20 | if (!freeBlocks.empty()) { 21 | currentBlock = *freeBlocks.rbegin(); 22 | freeBlocks.pop_back(); 23 | } else { 24 | currentBlock = (T*)malloc(sizeof(T) * BlockSize); 25 | assert(currentBlock != nullptr); 26 | } 27 | } 28 | 29 | public: 30 | BumpAllocator() { 31 | grow(); 32 | } 33 | 34 | // Do not allow delete 35 | BumpAllocator(const BumpAllocator& x) = delete; 36 | 37 | // Allow move 38 | BumpAllocator(BumpAllocator&& x) = default; 39 | 40 | ~BumpAllocator() { 41 | for (auto block : blocks) { 42 | for (size_t i = 0; i < BlockSize; i++) (block + i)->~T(); 43 | free(block); 44 | } 45 | for (auto block : freeBlocks) { 46 | free(block); 47 | } 48 | for (size_t i = 0; i < currentBlockCount; i++) (currentBlock + i)->~T(); 49 | free(currentBlock); 50 | currentBlock = nullptr; 51 | } 52 | 53 | template 54 | T* allocate(Args&&... args) { 55 | if (currentBlockCount >= BlockSize) grow(); 56 | T* ret = currentBlock + currentBlockCount; 57 | // *ret = T(std::forward(args)...); 58 | // Placement new. Constructs the new object at the ret pointer's location 59 | new(ret) T(std::forward(args)...); 60 | currentBlockCount++; 61 | return ret; 62 | } 63 | 64 | void clear() { 65 | for (auto block : blocks) { 66 | for (size_t i = 0; i < BlockSize; i++) (block + i)->~T(); 67 | } 68 | 69 | for (auto block : blocks) freeBlocks.push_back(block); 70 | blocks.clear(); 71 | 72 | for (size_t i = 0; i < currentBlockCount; i++) (currentBlock + i)->~T(); 73 | currentBlockCount = 0; 74 | } 75 | 76 | size_t size() { 77 | return blocks.size() * BlockSize + currentBlockCount; 78 | } 79 | }; 80 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/cereal_json.h: -------------------------------------------------------------------------------- 1 | // Identical to including some cereal files, but without the annoying warnings 2 | 3 | #pragma once 4 | #pragma GCC diagnostic ignored "-Wunused-private-field" 5 | // Fix annoying noexcept warnings 6 | #include 7 | #define CEREAL_RAPIDJSON_ASSERT(x) assert(x) 8 | #include 9 | #include 10 | #pragma GCC diagnostic warning "-Wunused-private-field" -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/influence.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "sc2api/sc2_api.h" 3 | #include 4 | 5 | struct InfluenceMap { 6 | std::vector weights; 7 | int w, h; 8 | 9 | InfluenceMap() { 10 | } 11 | 12 | InfluenceMap(int width, int height) { 13 | w = width; 14 | h = height; 15 | weights = std::vector(width*height, 0.0); 16 | } 17 | 18 | InfluenceMap(const sc2::ImageData map); 19 | InfluenceMap(const SC2APIProtocol::ImageData map); 20 | 21 | inline double& operator()(int x, int y) { 22 | return weights[y*w + x]; 23 | } 24 | 25 | inline double operator()(int x, int y) const { 26 | return weights[y*w + x]; 27 | } 28 | 29 | inline double& operator()(sc2::Point2DI p) { 30 | return weights[p.y*w + p.x]; 31 | } 32 | 33 | inline double operator()(sc2::Point2DI p) const { 34 | return weights[p.y*w + p.x]; 35 | } 36 | 37 | inline double& operator()(sc2::Point2D p) { 38 | return weights[std::min(h-1, std::max(0, (int)round(p.y)))*w + std::min(w-1, std::max(0, (int)round(p.x)))]; 39 | } 40 | 41 | inline double operator()(sc2::Point2D p) const { 42 | return weights[std::min(h-1, std::max(0, (int)round(p.y)))*w + std::min(w-1, std::max(0, (int)round(p.x)))]; 43 | } 44 | 45 | inline double& operator[](int index) { 46 | return weights[index]; 47 | } 48 | 49 | inline double operator[](int index) const { 50 | return weights[index]; 51 | } 52 | 53 | InfluenceMap& operator+= (const InfluenceMap& other); 54 | 55 | InfluenceMap& operator+= (double other); 56 | 57 | InfluenceMap operator+ (const InfluenceMap& other) const; 58 | 59 | InfluenceMap& operator-= (const InfluenceMap& other); 60 | 61 | InfluenceMap operator- (const InfluenceMap& other) const; 62 | 63 | InfluenceMap& operator*= (const InfluenceMap& other); 64 | 65 | InfluenceMap operator* (const InfluenceMap& other) const; 66 | 67 | InfluenceMap& operator/= (const InfluenceMap& other); 68 | 69 | InfluenceMap operator/ (const InfluenceMap& other) const; 70 | 71 | InfluenceMap operator+ (double factor) const; 72 | 73 | InfluenceMap operator- (double factor) const; 74 | 75 | InfluenceMap operator* (double factor) const; 76 | 77 | void operator*= (double factor); 78 | 79 | void threshold(double value); 80 | 81 | double sum() const; 82 | 83 | double max() const; 84 | void max(const InfluenceMap& other); 85 | double maxFinite() const; 86 | 87 | sc2::Point2DI argmax() const; 88 | 89 | InfluenceMap replace_nonzero(double with) const; 90 | InfluenceMap replace_nan(double with) const; 91 | InfluenceMap replace(double value, double with) const; 92 | 93 | void addInfluence(double influence, sc2::Point2DI pos); 94 | void addInfluence(double influence, sc2::Point2D pos); 95 | void setInfluence(double influence, sc2::Point2D pos); 96 | void addInfluenceInDecayingCircle(double influence, double radius, sc2::Point2D pos); 97 | void setInfluenceInCircle(double influence, double radius, sc2::Point2D pos); 98 | 99 | void addInfluence(const std::vector >& influence, sc2::Point2D); 100 | 101 | void addInfluenceMultiple(const std::vector >& influence, sc2::Point2D, double factor); 102 | 103 | void maxInfluence(const std::vector >& influence, sc2::Point2D); 104 | 105 | void maxInfluenceMultiple(const std::vector >& influence, sc2::Point2D, double factor); 106 | 107 | void propagateMax(double decay, double speed, const InfluenceMap& traversable); 108 | void propagateSum(double decay, double speed, const InfluenceMap& traversable); 109 | sc2::Point2DI samplePointFromProbabilityDistribution() const; 110 | 111 | void print() const; 112 | }; 113 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/pathfinding.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "influence.h" 3 | #include "sc2api/sc2_api.h" 4 | #include 5 | 6 | std::vector getPath (const sc2::Point2DI from, const sc2::Point2DI to, const InfluenceMap& costs); 7 | InfluenceMap getDistances (const InfluenceMap& startingPoints, const InfluenceMap& costs); -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/predicates.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "sc2api/sc2_interfaces.h" 3 | 4 | struct IsAttackable { 5 | bool operator()(const sc2::Unit& unit); 6 | }; 7 | struct IsFlying { 8 | bool operator()(const sc2::Unit& unit); 9 | }; 10 | struct IsArmy { 11 | const sc2::ObservationInterface* observation_; 12 | // Ignores Overlords, workers, and structures 13 | IsArmy(const sc2::ObservationInterface* obs) : observation_(obs) {} 14 | bool operator()(const sc2::Unit& unit); 15 | }; 16 | struct IsTownHall { 17 | bool operator()(const sc2::Unit& unit); 18 | }; 19 | struct IsVespeneGeyser { 20 | bool operator()(const sc2::Unit& unit); 21 | }; 22 | struct IsStructure { 23 | const sc2::ObservationInterface* observation_; 24 | IsStructure(const sc2::ObservationInterface* obs) : observation_(obs){}; 25 | bool operator()(const sc2::Unit& unit); 26 | }; 27 | 28 | bool isArmy(sc2::UNIT_TYPEID type); 29 | bool isStructure(const sc2::UnitTypeData& unitType); 30 | 31 | bool carriesResources(const sc2::Unit* unit); 32 | 33 | bool isMelee(sc2::UNIT_TYPEID type); 34 | bool isInfantry(sc2::UNIT_TYPEID type); 35 | bool isChangeling(sc2::UNIT_TYPEID type); 36 | bool hasBuff (const sc2::Unit* unit, sc2::BUFF_ID buff); 37 | bool isUpgradeWithLevels(sc2::UPGRADE_ID upgrade); 38 | bool isTownHall(sc2::UNIT_TYPEID type); 39 | bool isUpgradeDoneOrInProgress(const sc2::ObservationInterface* observation, sc2::UPGRADE_ID upgrade); -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/profiler.cpp: -------------------------------------------------------------------------------- 1 | #include "profiler.h" 2 | using Clock = std::chrono::high_resolution_clock; 3 | 4 | void Stopwatch::start() { 5 | startTime = Clock::now(); 6 | } 7 | 8 | void Stopwatch::stop() { 9 | endTime = Clock::now(); 10 | } 11 | 12 | double Stopwatch::millis() { 13 | std::chrono::duration duration = endTime - startTime; 14 | return duration.count(); 15 | } 16 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/profiler.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | struct Stopwatch { 5 | private: 6 | std::chrono::time_point startTime; 7 | std::chrono::time_point endTime; 8 | public: 9 | Stopwatch() : startTime(), endTime() { 10 | start(); 11 | } 12 | Stopwatch(bool started) : startTime(), endTime() { 13 | if (started) start(); 14 | } 15 | double millis(); 16 | void stop(); 17 | void start(); 18 | }; 19 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/python_utils.cpp: -------------------------------------------------------------------------------- 1 | #include "python_utils.h" 2 | using namespace std; 3 | 4 | mutex python_thread_mutex; -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/python_utils.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern std::mutex python_thread_mutex; -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/stdutils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // ------------------------------------------------------------------- 8 | // --- Reversed iterable 9 | 10 | template 11 | struct reversion_wrapper { T& iterable; }; 12 | 13 | template 14 | auto begin (reversion_wrapper w) { return std::rbegin(w.iterable); } 15 | 16 | template 17 | auto end (reversion_wrapper w) { return std::rend(w.iterable); } 18 | 19 | template 20 | reversion_wrapper reverse (T&& iterable) { return { iterable }; } 21 | 22 | template 23 | bool contains(const std::vector& arr, const T& item) { 24 | return find(arr.begin(), arr.end(), item) != arr.end(); 25 | } 26 | 27 | template 28 | int indexOf(const std::vector& arr, const T& item) { 29 | auto c = find(arr.begin(), arr.end(), item); 30 | assert(c != arr.end()); 31 | return (int)(c - arr.begin()); 32 | } 33 | 34 | template 35 | int indexOfMaybe(const std::vector& arr, const T& item) { 36 | auto c = find(arr.begin(), arr.end(), item); 37 | if (c == arr.end()) return -1; 38 | return (int)(c - arr.begin()); 39 | } 40 | 41 | template 42 | void sortByValueAscending (std::vector& arr, std::function value) { 43 | std::sort(arr.begin(), arr.end(), [&](const T& a, const T& b) -> bool { 44 | return value(a) < value(b); 45 | }); 46 | } 47 | 48 | template 49 | void sortByValueDescending (std::vector& arr, std::function value) { 50 | std::sort(arr.begin(), arr.end(), [&](const T& a, const T& b) -> bool { 51 | return value(b) < value(a); 52 | }); 53 | } 54 | 55 | 56 | template 57 | void sortByValueDescendingBubble (std::vector& arr, std::function value) { 58 | bool changed = true; 59 | while(changed) { 60 | changed = false; 61 | for (size_t i = 0; i + 1 < arr.size(); i++) { 62 | if (value(arr[i]) < value(arr[i+1])) { 63 | std::swap(arr[i], arr[i+1]); 64 | changed = true; 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/libvoxelbot/utilities/unit_data_caching.h: -------------------------------------------------------------------------------- 1 | #include "sc2api/sc2_api.h" 2 | #include 3 | #include 4 | #include 5 | 6 | const std::string UNIT_DATA_CACHE_PATH = "sc2-libvoxelbot/libvoxelbot/generated/units.data"; 7 | const std::string UPGRADE_DATA_CACHE_PATH = "sc2-libvoxelbot/libvoxelbot/generated/upgrades.bin"; 8 | const std::string ABILITY_DATA_CACHE_PATH = "sc2-libvoxelbot/libvoxelbot/generated/abilities.bin"; 9 | 10 | void save_unit_data(const std::vector& unit_types, std::string path=UNIT_DATA_CACHE_PATH); 11 | std::vector load_unit_data(); 12 | void save_ability_data(std::vector abilities); 13 | void save_upgrade_data(std::vector upgrades); 14 | std::vector load_ability_data(); 15 | std::vector load_upgrade_data(); -------------------------------------------------------------------------------- /vs/CommandCenter.aps: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/vs/CommandCenter.aps -------------------------------------------------------------------------------- /vs/CommandCenter.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/vs/CommandCenter.rc -------------------------------------------------------------------------------- /vs/CommandCenter.sdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RaphaelRoyerRivard/MicroMachine/eb893161371dab975a0a7e600f9e250ac03ec1ef/vs/CommandCenter.sdf -------------------------------------------------------------------------------- /vs/CommandCenter.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2005 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CommandCenter", "CommandCenter.vcxproj", "{D4AC5062-8BEA-46D8-9231-57241C214F1C}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Debug|x64 = Debug|x64 12 | Debug|x86 = Debug|x86 13 | Release|Win32 = Release|Win32 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Debug|Win32.ActiveCfg = Debug|Win32 19 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Debug|Win32.Build.0 = Debug|Win32 20 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Debug|x64.ActiveCfg = Debug|x64 21 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Debug|x64.Build.0 = Debug|x64 22 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Debug|x86.ActiveCfg = Debug|Win32 23 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Debug|x86.Build.0 = Debug|Win32 24 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Release|Win32.ActiveCfg = Release|Win32 25 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Release|Win32.Build.0 = Release|Win32 26 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Release|x64.ActiveCfg = Release|x64 27 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Release|x64.Build.0 = Release|x64 28 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Release|x86.ActiveCfg = Release|Win32 29 | {D4AC5062-8BEA-46D8-9231-57241C214F1C}.Release|x86.Build.0 = Release|Win32 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {8B9A040A-DE18-49B1-ABAA-D3A6F4CDA066} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /vs/CommandCenter.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | $(ProjectDir)/../bin/ 5 | WindowsLocalDebugger 6 | 7 | 8 | $(ProjectDir)/../bin/ 9 | WindowsLocalDebugger 10 | 11 | 12 | $(ProjectDir)/../bin/ 13 | WindowsLocalDebugger 14 | 15 | 16 | $(ProjectDir)/../bin/ 17 | WindowsLocalDebugger 18 | 19 | 20 | $(ProjectDir)/../bin/ 21 | WindowsLocalDebugger 22 | 23 | 24 | $(ProjectDir)/../bin/ 25 | WindowsLocalDebugger 26 | 27 | 28 | $(ProjectDir)/../bin/ 29 | WindowsLocalDebugger 30 | 31 | 32 | $(ProjectDir)/../bin/ 33 | WindowsLocalDebugger 34 | 35 | 36 | $(ProjectDir)/../bin/ 37 | WindowsLocalDebugger 38 | 39 | -------------------------------------------------------------------------------- /vs/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by CommandCenter.rc 4 | 5 | // Next default values for new objects 6 | // 7 | #ifdef APSTUDIO_INVOKED 8 | #ifndef APSTUDIO_READONLY_SYMBOLS 9 | #define _APS_NEXT_RESOURCE_VALUE 101 10 | #define _APS_NEXT_COMMAND_VALUE 40001 11 | #define _APS_NEXT_CONTROL_VALUE 1001 12 | #define _APS_NEXT_SYMED_VALUE 101 13 | #endif 14 | #endif 15 | --------------------------------------------------------------------------------