Haxe: The Big Secret to Cross-Platform Development

Original author: Kevin Bloch
  • Transfer
The modern Haxe programming language is well known in certain circles, but many of those reading this material may never have heard of it. But don't let its niche status fool you. Since he first appeared in 2005, his loyal, albeit rather quiet, followers have experienced him in battle. It features a pragmatic and thoughtful combination of capabilities 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 of it? Perhaps the versatility of Haxe means that it cannot be called a single killer feature.

Or perhaps the reason is that one of the earliest uses of Haxe is to use it as a means to migrate from the dying Flash platform, which is pretty niche. Over the past 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, hearing the word "Flash" can immediately lose interest in the subject. This attitude, for example, led to the emergence of the HaxeDevelop - IDE for Haxe, which is essentially FlashDevelop, but specialized for development under Haxe and from the distribution of which components for development for 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 has 75 million users, chose Haxe, not Unity or pure JavaScript, to translate its projects (with a code base of 1.4 million lines) from Flash to HTML5 (more information about this is available in this material ).

Perhaps that is why it is difficult to single out successful cases of using Haxe, and at the same time to interest non-game developers. But let's still do a little research.

So what is it about Haxe?

In general, using the Haxe language means that you can reuse (good) code . By this I mean that Haxe code can be reused on many platforms, it can be integrated with existing Haxe code and 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 Haxe usage scenarios (except for migration from Flash, of course).

Development of a cross-platform application or game from scratch. Using Haxe code, 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-platformdesktop and mobile applications and games. But Haxe in this respect is different 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 all." I apologize for referring to Tolkien, but just as Node.js proclaimed the era of using the same 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 run on different platforms).

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

JavaScript abandonment in favor of type safety. Wait a minute, isn't that TypeScript already? 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 fast compilation and testing process.Recently added to the Haxe ecosystem, the HashLink cross-platform virtual machine (VM) allows you to strike a balance between compilation time (compiling under HashLink is much faster than compiling under C ++) and code execution speed sufficient for areas such as creating 3D games (previously for these purposes it could use the Neko virtual machine, which, however, is significantly inferior to HashLink in speed). But even in the area of ​​web development, Haxe can outperform TypeScript in both compilation speed and execution speed of generated code .

Exciting frontier. Haxe's source code is open, new language constructs are constantly being added to it, and it has an active community. And his biggest secret is the macro systemexecutable during compilation and allowing meta-programming the way the soul wants (I will give some examples of libraries using macros below).

Who is using 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 realm:

  • Back in 2014, the use of Haxe allowed TiVo to improve the performance of the TiVo Premiere set-top box by more than 30% .
  • Massive Interactive, whose customers are DAZN and Telecine, successfully use Haxe to develop software for Smart TV systems. Based on his experience with large web projects, Philip Elsass (Massive Interactive UI Architect), in one of his reports, noted that Haxe is usually easier to use than TypeScript and also translates into JavaScript faster by an order of magnitude.
  • Synolia uses Haxe for its online tool Heidi , which is used by major French brands Carrefour and La Fnac, as well as Nickelodeon. The Haxe toolkit allowed Synolia to migrate from Flash to HTML5, and also provided new business opportunities for the mobile business. Choosing Haxe allowed us to reuse common code across Heidi's various layers and services.
  • In 2017, Docler Holding became a strategic partner of the Haxe Foundation .

What is the Haxe ecosystem?

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

  • Flambe has been used to develop HTML5 games by brands such as Disney, Coca-Cola, and Toyota.
  • Heaps is a 3D / 2D gaming framework that underpins successful indie games like Northgard and Dead Cells .
  • The awe6 rapid development library is perhaps the hidden gem even for the Haxe community.
  • Kha is an ultra-portable multimedia framework with the ability to build projects not only on desktop and mobile OS and HTML5, but also on XBox One, Nintendo Switch and Playstation 4. More than 20 game engines were created on its basis , the most interesting of which is Armory - 3D -engine with full integration with Blender .
  • HaxeFlixel , modeled after the old Flash engine Flixel, is a popular choice for creating small games, for example, for Defender's Quest .
  • Starling, originally an ActionScript framework used for the Angry Birds port for Facebook, now also has a port on Haxe .
  • OpenFL , which implements the Flash API, also allows you to create applications for consoles (PlayStation 4, PlayStation Vita, XBox One and Nintendo Switch), desktop and mobile OS, HTML5. HaxeFlixel and Starling Port run on top of OpenFL. An example of a game developed directly on OpenFL is the award-winning Papers, Please .
  • The Native Media Engine (NME), from which OpenFL split several years ago, continues to be supported and updates are being released for it.
  • HaxePunk (descended from another Flash-engine - FlashPunk) - perhaps you could see mention of it in one of the releases of Github Release Radar .
  • Nape is a highly-optimized physics 2D engine, great for games and simulations with complex physics.

Of course, making games is Haxe’s most prominent application. But the Haxe ecosystem also has libraries and tools for building business and enterprise applications, for example:

  • hexMachina is a modular application creation framework that supports the use of the domain-specific language (DSL) and the model-view-controller (MVC) architecture, as well as many other functions. Created and used by Docler Holding.
  • HaxeUI is a UI markup engine, is actively developing and has corporate support. Examples of its use are products such as 3DVista and Kaizen for Pharma . HaxeUI is interesting in that it consists of a kernel module and individual modules that implement UI rendering using various means: HTML components, wxWidgets, Windows Forms, native Android UI elements, etc.
  • The thx family of libraries provides universal language extensions for Haxe; the Lodash library can be called its counterpart from the JavaScript world.
  • Speaking of JavaScript and Haxe projects compiled in JavaScript, mention should be made of the Haxe Modular tool , which helped Telecine and FlowPlay scale their huge projects and provide fast downloads on the client side.
  • The Haxe ecosystem also aims to foster synergies with modern technology. As an example of movement in this direction, we can call the GraphQL library .
  • Finally, the Tinkerbell library collection , using a macro system, provides tools for all kinds of tasks: frameworks for web routing, unit testing and SQL embedding, as well as libraries for almost everything: from CSS template and parsing to async / await and reactive processing states with a smoother learning curve.

Only the most interesting projects created by Haxe users are listed here. A complete 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 the Haxe Foundation itself supports:

  • For DevOps, the official Haxe image for Docker may seem interesting .
  • The h3compat library provides partial backward compatibility between Haxe 4 and Haxe 3 and is designed to help users when updating projects to work with the new version of the language.

It all sounds good, but what does it take to get started developing on Haxe?

Quick start with Haxe

Regardless of whether you work on Windows, MacOS or Linux, the first thing to do is to download the Haxe installer , which includes:

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

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

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

  • The Haxe plugin for VSCode is actively supported .
  • There is also a Haxe plugin for IntelliJ IDEA .
  • Kha (the previously mentioned framework for creating games) has its own development environment - Kode Studio (Win / Mac / Linux). This IDE is a fork of VSCode with additional features for debugging projects.
  • For Sublime Text and Atom, as well as many other editors , you can also find the corresponding Haxe plugins, although some of them work only on certain platforms.

In this short tutorial we will use VSCode. The easiest way is to install the entire plug-in package at once for Haxe support using the command ext install haxe-extension-packin the VSCode quick access panel (called by a combination Ctrl+P), but if you are minimalist, you can restrict yourself to the most basic plug-in - ext install vshaxe(you can always install other components later).

Creating a Haxe Project

Managing the process of compiling Haxe code for different platforms is easier with the help of a build system file. However, for starters, we will only need one file with the Haxe-code with the extension .hx.

As for the code, let's take the “Generate Arrays” example from try.haxe.org (an online sandbox where you can quickly check how a particular code will work) and save it in a file with the name 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 function calls trace():

$ 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, generate JavaScript code from it, and use the resulting code on your web page. In Haxe, this is done with one command:

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

If you have Node.js installed, then you can check the operation of 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.jsto a web page, and then when you download it, we will see the same result, but already in the developer console built into the browser.

Compilation and compilation into an executable file

Suppose you also needed a binary executable for the system you are running on. To do this, we need to transpose the Haxe code in C ++, and then compile the resulting .cppfiles into an executable file (provided that you have the compiler installed, on Windows it is easiest to install Microsoft Visual Studio for this). To perform these tasks, we need a library hxcppthat we install with the command:

$ haxelib install hxcpp

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

$ haxe -main Test -cpp bin

After which our executable file can be launched:

$ 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 start will be slightly different bin\Test.exe).

Creating a Haxe Build File (.hxml)

Although the Haxe project build files have an extension .hxml, they are not XML files (unlike the files .hxprojused by HaxeDevelop and FlashDevelop, but we will not talk about them). Here it will look like the file build-all.hxmlto perform transpilyatsii: Note the difference in the prefixes: , and - each of these parameters is transmitted haxe directly, and (two hyphens) - parameters of the meta-level, they indicate to the compiler what to do with the other parameters. Now, to build the program in JavaScript and into an executable file, it is enough to simply execute the command .

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


haxe build-all.hxml

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

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

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

-main Test
-cpp bin
-cmd bin/Test

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

Haxe 4

In the process of configuring 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 brings many new features. One of these functions is evidence of the wide possibilities of the macro system, allowing to supplement the language with new constructions: previously, Haxe did not have 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, there are not so many major changes. Instead, Haxe 4 brings many small improvements. After all, Haxe is a fairly mature technology developed by a small and purposeful team, and finding a project similar to Haxe is quite difficult.

Many of the most interesting features of Haxe are not new. For example, I mentioned earlier that using the 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 (caching in RAM is used), in addition, the compilation server can be used by the IDE to automatically complete the code (for example, the plugin works under VSCode).

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

Haxe Learning Materials

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

If you prefer to learn from video materials, then for you are available video appearances from the Haxe Summit US 2018, held in Seattle, as well as recordings from other conferences.

But sometimes a guide to a specific topic may come in handy for you. For example, about creating a dungeon crawler-style game in HaxeFlixel. HaxeFlixel also has a series of materials explaining the basics of working with the engine. If you are interested in 3D, then here you can offer a guide on how to get started with Armory .

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

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

Also popular now: