📜 ⬆️ ⬇️

Haxe: The Big Secret of Cross-Platform Development

The modern programming language Haxe is well known in certain circles, but many of the readers of this material may never have heard of it. But don't let his niche status fool you. Since he first appeared in 2005, his loyal, albeit rather quiet, followers have experienced him in battle. It is distinguished by a pragmatic and thoughtful combination of opportunities suitable for development in business, games and even for academic purposes.

Disney, Hasbro and the BBC use Haxe , so why haven't most developers heard about it? Perhaps the versatility of Haxe means that for him it is impossible to name one single killer feature.

Or, perhaps, the reason is that one of the earliest uses of Haxe is to use it as a means of switching from a dying Flash platform — rather niche. The last few years, the casual games market has been in limbo, but now it has become known that by 2020 Flash will officially cease to be supported by Adobe and all Flash content on the web will go into oblivion.

Business software engineers, web developers, and many game developers, when they hear the word "Flash", can immediately lose interest in the topic in question. Such an attitude, for example, caused the appearance of HaxeDevelop - an IDE for Haxe, which is essentially FlashDevelop , but specialized for development under Haxe and from the distribution kit of which components for development under ActionScript are removed.

Getting rid of such associations that Haxe is the refuge of former Flash developers is still quite difficult, especially when they (such associations) remain relevant. For example, FlowPlay, whose social games have 75 million users, chose Haxe, rather than Unity or pure JavaScript, to translate their projects (with a code base of 1.4 million lines) from Flash to HTML5 (more detailed information about this is available in this material ).

Perhaps, therefore, it is difficult to single out successful cases of using Haxe, and to interest non-game developers. But let's do some research.

So what's up with Haxe?


In general, the use of the Haxe language means the ability to reuse (good) code . By this I mean that Haxe code can be reused on many platforms, it can be integrated with existing code in Haxe and in other languages, and, well, the Haxe language provides many proven paradigms, such as type safety.

Continuing the topic of universality, we list the main categories of usage scenarios for Haxe (apart from migrating from Flash, of course).

Development of cross-platform applications or games from scratch. Using code on Haxe, you can work with desktop, mobile and web platforms. There is nothing new in cross-platform programming languages, and besides Haxe there are other special solutions for cross-platform desktop and mobile applications and games. But Haxe differs in this respect in that one code will not only work on different platforms, but in different paradigms, for example, in the form of an HTML5 application and a native executable file.

One language "to rule over all." I apologize for sending to Tolkien, but just as Node.js proclaimed the era of using one language for the client and server parts of websites, Haxe can be used for both components of client-server applications (while the client and server can work on different platforms).

For example, the web application FontStruct uses Haxe to render graphics both on the client side (on HTML5 canvas) and on the server side (using Java2D). But, as already mentioned, it is not necessary to follow this path - Haxe does not hamper your capabilities and allows you to work in conjunction with already existing code written in any other language. This approach greatly simplifies maintaining consistency of logic and even drawing graphics in all contexts, platforms and target languages.

Denial of JavaScript in favor of type safety. Wait, isn't there already a TypeScript for this? Yes, if you want to limit yourself to just javascript output. Haxe, in turn, can also be compiled into code in Java, C ++, C #, Python, Lua, and other languages .

At the same time, the Haxe language itself is simple enough to learn for those who are already familiar with the basics of JavaScript, its syntax does not require the programmer to change the paradigm of thinking, as, for example, in the case of Rebol. Andy Lee (one of the main developers of Haxe) wrote a detailed comparison of TypeScript and Haxe , which remains relevant today, although both languages ​​continue their further development.

Pretty quick compilation and testing process. HashLink’s cross-platform virtual machine (VM) recently added to the Haxe ecosystem allows for a balance between compile times (compiling under HashLink works much faster than compiling under C ++) and the speed of code execution sufficient for areas such as creating 3D games (previously for these purposes could used Neko virtual machine, which, however, is significantly inferior to HashLink in speed). But even in the field of web development, Haxe can surpass TypeScript in both compilation speed and execution speed of the generated code .

Exciting frontier. The Haxe source code is open, new language constructs are constantly being added to it, and it has an active community. And its biggest secret is the system of macros that are executed at compile time and allow meta-programming the way the soul wants (hereinafter I will give a few examples of libraries using macros).

Who uses Haxe?


Of course, game developers: Madden NFL Mobile , Evoland II , Double Kick Heroes ... these and hundreds of other games were developed using Haxe. But Haxe is also used outside the gaming field:


What is the Haxe ecosystem?


When it comes to games and Haxe, the choice of open source libraries and frameworks is quite wide here. Haxe users, whether they are independent indie teams or successful studios with international clients, actively share their code:


Of course, the creation of games is the most visible area of ​​application for Haxe. But in the Haxe ecosystem there are also libraries and tools for creating applications for business and enterprises, for example:


Here are only the most interesting projects created by users of Haxe. A full list of libraries sorted by popularity (there is also the ability to sort libraries by tags) is available on the official website. But it is also worth mentioning a couple of projects that are supported by the Haxe Foundation itself:


It all sounds good, but what do you need to start developing on Haxe?

Quick start with Haxe


Regardless of whether you are working on Windows, MacOS or Linux, the first step is to download the installer Haxe , which includes:

  1. The Haxe compiler, which can be started using the haxe command from a terminal or command line.
  2. The standard Haxe library , which provides low-level functions and general-purpose data structures. For example, classes for processing XML and ZIP archives, access to MySQL.
  3. The package manager Haxelib, which allows you to install new libraries (both from the official repository and from Git or Mercurial). It is launched by the haxelib command ( lix may also be of interest to you - a more advanced package manager than Haxelib).
  4. Neko is a virtual machine that can be useful for debugging projects thanks to quick compilation.

In addition, there are other ways to install Haxe on your system, for example, using npm , Homebrew or Chocolatey.

After installing Haxe, you can use it directly from the command line, but it is better, of course, to do this using the IDE. FlashDevelop / HaxeDevelop is still mainly supported only under Windows. Most of the other options available are cross-platform (Win / Mac / Linux):


In this quick start guide, we will use VSCode. The easiest way is to install the entire package of plug-ins at once to support Haxe using the ext install haxe-extension-pack command in the VSCode quick access panel (called Ctrl+P ), but if you are a minimalist, then you can restrict yourself to the most basic plug-in - ext install vshaxe You can always install it later).

Creating a Haxe Project


Managing the Haxe code compilation process for different platforms is easier using the build system file. However, for the beginning we will need only one file with the Haxe-code with the extension .hx .

As for the code, let's take an example “Generating arrays” from the site try.haxe.org (an online sandbox where you can quickly check how this or that code will work) and save it into a file named Test.hx :

 class Test { static function main() { var a = [for (i in 0...10) i]; trace(a); // [0,1,2,3,4,5,6,7,8,9] var i = 0; var b = [while(i < 10) i++]; trace(b); // [0,1,2,3,4,5,6,7,8,9] } } 

Now we can run the Haxe compiler in interpretation mode (that is, without generating code for any platform) and see the results of the trace() function calls:

 $ haxe -main Test --interp Test.hx:4: [0,1,2,3,4,5,6,7,8,9] Test.hx:8: [0,1,2,3,4,5,6,7,8,9] 

Great, it works!

Haxe Transpilation in JavaScript


Suppose you want to share the code discussed in the example with the whole world, generating JavaScript from it, and use the resulting code on your web page. In Haxe, this is done in one command:

 $ haxe -main Test -js haxe-test.js 

If you have Node.js installed, then you can test the generated JavaScript code from the command line:

 $ node my-test.js [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 

Or you can connect the finished file my-test.js to a web page, and then when you download it, you will see the same result, but already in the developer console built into the browser.

Transporting and compiling into an executable file


Suppose you also need a binary executable file for the system on which you work. To do this, we need to translate the Haxe code into C ++, and then compile the resulting .cpp files into an executable file (assuming that you have a compiler installed, on Windows it is easiest to install Microsoft Visual Studio). To perform these tasks, we need the hxcpp library, which we install hxcpp command:

 $ haxelib install hxcpp 

With this library, the code is compiled and compiled using just one command:

 $ haxe -main Test -cpp bin 

After that, our executable file can be run:

 $ bin/Test Test.hx:4: [0,1,2,3,4,5,6,7,8,9] Test.hx:8: [0,1,2,3,4,5,6,7,8,9] 

(on Windows, the command to run will be slightly different bin\Test.exe ).

Creating a Haxe assembly file (.hxml)


Although the Haxe project build files have the .hxml extension, they are not XML files (unlike the .hxproj files used by HaxeDevelop and FlashDevelop, but not about them). This is how the build-all.hxml file will look like to perform the transfiguration:

-main Test # указываем компилятору Haxe, что основным классом приложения является класс Test (внимание, имя класс регистрозависимое)
--each # все команды, указанные выше, будут применены для каждой из целевых платформ
-js haxe-test.js # сперва осуществим транспиляцию в JS
--next # других опций не используем, переходим к следующей целевой платформе
-cpp bin # вторая целевая платформа, в которую будет осуществляться транспиляция (и компиляция) - это C++

Note the difference in prefixes: -main , -js and -cpp — each of these parameters is passed to haxe directly, and --each and --next (with two hyphens) are meta-level parameters, they tell the compiler what to do with other parameters.

Now, to build the program in JavaScript and in the executable file, simply run the haxe build-all.hxml .

If you want to translate the code into JavaScript and immediately run the result using Node, then you can execute the haxe run-js.hxml , the contents of the run-js.hxml file will look like this:

 -main Test -js haxe-test.js -cmd node haxe-test.js 

Similarly, the file for “build and run” for the executable file will look like this (for Windows, a small change will be required, which we have already mentioned):

 -main Test -cpp bin -cmd bin/Test 

What about VSCode? Everything is simple here: the VSCode extension we installed will automatically pick up the hxml files and generate the corresponding project build tasks (without using tasks.json ).

Haxe 4


In the process of taking steps to configure Haxe, you may have noticed that the download page has links to both version 3.x and 4.x.

The latest (fourth) version of the Haxe compiler introduces many new features. One of these functions is evidence of the wide possibilities of the macro system, which allow to supplement the language with new constructions: earlier in Haxe there was no support for short lambda functions, so the slambda library appeared , which implemented their support using the macro system. Starting with the fourth version, their support is built into the compiler, and the need to use this library has disappeared.

What else is new in Haxe 4?

In fact, major changes are not so much. Instead, Haxe 4 introduces many small improvements. After all, Haxe is a fairly mature technology, developed by a small and goal-oriented team, and finding a project similar to Haxe is rather difficult.

Many of the most interesting features of Haxe are not new. For example, I mentioned earlier that using Neko and HashLink virtual machines allows for a fast development process. But since 2016, a compilation server has appeared in the compiler, thanks to which the project is recompiled (not for virtual machines) now much faster (in-memory caching is used), in addition, the compilation server can be used by IDE to autocomplete the code (for example, the under VSCode).

But, in particular, the following changes will appear in Haxe 4:


Study Materials Haxe


In addition to the standard library API documentation and language syntax , materials designed for beginners are available on the Haxe site, and in addition, I cannot but mention the site dedicated to the development of Haxe for the web .

If you prefer to learn from video materials, then you can watch videos from Haxe Summit US 2018, held in Seattle, as well as recordings from other conferences.

But sometimes a manual on a specific topic may be useful to you to get started. For example, about creating a game in the style of dungeon crawler in HaxeFlixel . Also for HaxeFlixel there is a series of materials explaining the basics of working with the engine. If you are interested in 3D, then you can offer a guide on how to start working with Armory .

Or maybe you just need a quick XML processing guide - this is one of those articles that have been around for several years, but they still remain relevant. Despite the fact that Haxe is constantly evolving, many of the fundamentals of development in it remain unchanged, so the old study material does not always mean that it is outdated (usually materials devoted to specific libraries, rather than the Haxe core, become outdated).

As you can see, Haxe can be used in different areas (and maybe Haxe itself will lead you into a new area). I hope you enjoyed this acquaintance with the world of Haxe, and I look forward to the news about how you use Haxe!

Source: https://habr.com/ru/post/437740/