StarCraft: Brood War. This game means so much to me! And to many of you, I guess. So much, that I wonder if I should even give a link to its page on Wikipedia or not. Once Halt sent me PM and offered to learn Rust. Like any ordinary people, we decided to start with hello world writing a dynamic library for Windows that could be loaded into StarCraft's address space and manage units. The following article will describe the process of finding solutions and using technologies and techniques that will allow you to learn new things about Rust and its ecosystem. You may also be inspired to implement a bot using your favorite language, whether it be C, C++, Ruby, Python, etc. It is definitely worth listening to the hymn of South Korea while reading this article: This game is almost 20 years old. And it is still popular; championships attracted crowds of people in the USA even in 2017 where the battle of grand masters Jaedong vs Bisu took place. In addition to human players, soulless machines also take part in SC battles! And this is possible because of BWAPI. More useful links. For over a decade now, there has been a community of bot developers around this game. Enthusiasts create bots and participate in various championships. Many of them study AI and machine learning. BWAPI is used by universities to train their students. There is even a twitch channel broadcasting such matches. So, a fan team reversed the Starcraft back-end several years ago and developed an API in C++, which allows you to create bots, make injections in the game process and dominate miserable humans. As it often happens, before building a house, it is necessary to mine ore, forge tools creating a bot, you need to implement an API. What does Rust have to offer? It is quite simple to work with other languages from Rust. There is an FFI for this. Let me give you a short excerpt from the documentation. Imagine we have a snappy library, that has a header file snappy-c.h, which contains function declarations. Let's create a project using cargo. Cargo has created a standard file structure for the project. In Cargo.toml we specify dependency to libc: The src/main.rs file will look like this: Let's build and run the project: You can call cargo run only, which calls cargo build before the run. Other option is to build the project and call the binary directly: If the snappy library is installed the code will be compiled (for Ubuntu you should install libsnappy-dev package). As you can see, our binary is linked to the libsnappy shared library. And a call to snappy_max_compressed_length in our code is a function call from this library. It would be nice if we could automatically generate our FFI. Fortunately, there is a utility called rust-bindgen in a Rust addict's toolbox. It is able to generate FFI bindings to C (and some C++) libraries. Installation: What does rust-bindgen look like? We take the C/C++ header files, we point the bindgen utility at them, and the output we get is generated Rust code with the proper declarations to let us use C structures and functions. Here's what bindgen generates for snappy: It turns out that bindgen can't cope with BWAPI headers, generating tons of non-usable code (because of virtual member functions, std::string in a public API, etc.). The thing is that BWAPI is written in C++. C++ is generally difficult to use even from C++ projects. Once the library is assembled, it's better to link it with the same linker (same version), header files should be parsed with the same compiler (same version). All these factors may affect the result. Mangling for example, which still can not be implemented without errors in GNU GCC. These factors are so significant that even gtest could not overcome it. And in the documentation it says: you'd better build gtest as a part of the project by the same compiler and the same linker. C is the lingua franca of software engineering. If rust-bindgen works well for the C language, why not implement BWAPI for C, and then use its API? Good idea! Yes, it's a good idea until you look into the insides of BWAPI and see the number of classes and methods that you should implement. Especially all these memory layouts, asm codes, memory patching and other "horrors" that we do not have time for. It is necessary to use the existing solution completely. But we need somehow to beat the mangling, C++ code, inheritance and virtual member functions. In C++, there are two powerful tools that we will use to solve our problem: opaque pointers and extern "C". extern "C" {} allows C++ code to "mask" itself under C. It makes it possible to generate function names without mangling. Opaque pointers allow us to clear the type and create a pointer to "some type" without providing its implementation. Since this is only a declaration of some type, it is impossible to use this type by value, you can use it only by pointer. Let's imagine that we have this C++ code: We can turn it into a C header: And here is the C++ part that will be the link between the C header and the C++ implementation: Not all the methods of classes had to be processed this way. In BWAPI, there are classes that you can implement yourself using the fields of these structures, for example typedef struct Position { int x; int y; } Position; and methods like Position::get_distance. There were classes that I had to treat in a special way. For example, AIModule should be a pointer to a C++ class with a specific set of virtual member functions. Nevertheless, here is header and implementation. So, after several months of hard work, 554 methods and a dozen classes, the cross-platform library BWAPI-C was born, which allows you to create bots in C. A by-product was the possibility of cross-compilation and the ability to implement the API in any other language that supports FFI and the cdecl call convention. If you are writing a library, please, write its API in C. The most important feature of BWAPI-C is the broadest possible integration with other programming languages. Python,Ruby, Rust,PHP, Java and many many others are able to work with C, so if you iron out the kinks and implement own wrappers, you can also write a bot with their help. This part describes the general principles of the internal organization of Starcraft modules. There are 2 types of bots: module and client. Let's look at an example of writing a module. The module is a dynamic library. The general principle of loading dynamic libraries can be viewed here. The module should export 2 functions: newAIModule and gameInit. gameInit is easy. This function is called to pass a pointer to a current game. This pointer is very important, because there is global static variable in the wilds of BWAPI, which is used in some sections of the code. Let's describe gameInit: newAIModule is a bit more complicated. It should return the pointer to a C++ class, which has a virtual method table with names like onXXXXX which are called on certain game events. Let's declare the structure of the module: The first field should be a pointer to the method table (it’s a kind of magic). Here is newAIModule function: createAIModuleWrapper is another magic trick that turns the C pointer into the pointer to C++ class with virtual methods member functions. module_vtable is a static variable on the method table, method values are filled with pointers to global functions: If you look at the name of the functions and their signatures, it is clear under what conditions and with what arguments they need to be called. For an example I made all the functions empty, except This function is called when the game runs. The argument is a pointer to the current module. BWAPIC_getGame returns a global pointer to the game, which we set using a call to BWAPIC_setGame. So, let's show a working example of cross-compiling a module: Push the buttons and run the game. More information about compilation and execution can be found on the BWAPI website and in BWAPI-C. The result of the module:  You can find a bit more complicated example of a module that shows how to work with iterators, unit management, mineral search, and statistics output in bwapi-c/example/Dll.c. In the Rust ecosystem there is a certain way of naming packages that link to native libraries. Any package foo-sys executes two important functions: In order for the *-sys package to be able to link successfully, you have to tell cargo to search for the native library and/or to build the library from the sources. In order for the *-sys package to provide declarations, you need to either write them by yourself or generate them using bindgen. Again bindgen. Attempt number two =) The generation of bindings is super easy: BWAPI.h is a file with of all the C headers from BWAPI-C. For example, bindgen has already generated such declarations for the functions above: There are two strategies: storing the generated code in the repository, and generating the code on the fly during the build. Both approaches have their advantages and disadvantages. Glad to meet you bwapi-sys; one more little step to our goal. Do you remember that earlier I was talking about cross-platform? nlinker joined the project and implemented a cunning strategy. If the target host is Windows, then download the already assembled BWAPIC from GitHub. And for the remaining targets we collect BWAPI-C from the sources for OpenBW (I'll tell you about it a bit later). Now we have the bindings and we can define high-level abstractions. We have two types to work with: pure values and opaque pointers. Everything is simple with pure values. Let's take colors as an example. We need to make it easy to use from Rust code in order to use colors in a convenient and natural way: So, for convenient use it would be necessary to define the enumeration with C++ constants but also idiomatic for Rust, and define methods of converting it in bwapi_sys::Color using std::convert::From: For your convenience you can use the enum-primitive-derive crate. It is also easy to use opaque pointers. Let’s use Newtype pattern: It means that Player is a kind of structure with a private field — a raw opaque pointer from C. And here's the way you can define the Player::color: Now we can write our first bot in Rust! As a proof of concept the bot will be similar to a well-known countru: the whole task is to hire workers and collect minerals.   Let's start with the required functions gameInit and newAIModule: #[no_mangle] performs the same function as extern "C" in C++. Inside wrap_handler all the magic occurs, with the substitution of the virtual function table and "masking" C++ class. The definitions of the module structure is even simpler and fancier than in C: Let's add a couple of methods for rendering the statistics and giving orders: To turn the ExampleAIModule type into a real module you need to make it respond to onXXXX events. To do so you need to implement the EventHandler type, which is an analog of the AIModule_vtable virtual table from C: Building and running the module are as simple as for C: And the video of the work: These guys went even further. They decided to write an open-source version of SC:BW! And they are good at it. One of their goals was to implement HD images, but SC:Remastered was ahead of them =( At this moment, you can use their API to write bots (yes, also in C++), but the most amazing feature is the ability to view replays directly in your browser. There was an unsolved problem with the implementation: we do not control the references to be unique, so the existence of &mut and & to the same region will result in undefined behavior when the object is modified. Kind of a trouble. Halt tried to implement idiomatic bindings, but he did not manage to find a solution. Also if you want to complete this task, you have to carefully "shovel up" the C++ API and put the const qualifiers correctly. I really enjoyed working on this project, I watched the replays 하루 종일 and deeply immersed in the atmosphere. This game made a 놀라운 dent in a universe. No game can be 비교할 수 없다 by popularity with SC: BW, and its impact on 대한민국 정치 에게 was unthinkable. Pro-gamers in Korea 아마도 are as popular as well as 드라마 주연 배우 들 Korean dorams broadcasting in prime time. 또한, 한국 에서 프로 게이머 라면 군대의 특별한 육군에 입대 할 수 수. Long live StarCraft! Many thanks to Steve Klabnik for helping me with reviewing the article.